Basically loop through each pixel in your found object and bin it into your grid using the modulus of your grid spacing. There are probably faster/ more efficient ways to do what you need, but this will get the job done.
int[][] grid
int gridSpacing
int[][] objectPix
for(objectPix[][] "x")
for(objectPix[] "y")
gridSpacing[Math.Floor(x/gridSpacing)][Math.Floor(y/gridSpacing)]++
Then in a final step (if you want percentage) go through grid and divide its value by the total number op pixels in the object.
With more details/ effort, you could probably make a clever recursive solution which split the rectangle until it only resided in one grid (and tracked area on each split). But I will leave that solution to you if you need the efficiency.
Recursive method only using vertices (in c#):
public void splitRectangle(ref int[][] grid, int gridSpacing, rect curRect)
{
//if rectangle has verticies in different grid zones, split it
if(Math.Floor(curRect.pt.x / gridSpacing) != Math.Floor((curRect.pt.x + curRect.width) / gridSpacing))
{
int xDiv = gridSpacing*(Math.Floor(curRect.pt.x / gridSpacing) + 1) - curRect.pt.x;
rect split1 = new rect(curRect.pt, xDiv, curRect.height);
rect split2 = new rect(new point(curRect.pt.x + xDiv, curRect.pt.y), curRect.width - xDiv, curRect.height);
splitRectangle(grid, gridSpacing, split1);
splitRectangle(grid, gridSpacing, split2);
}
else if (Math.Floor(curRect.pt.y / gridSpacing) != Math.Floor((curRect.pt.y + curRect.height) / gridSpacing))
{
int yDiv = gridSpacing*(Math.Floor(curRect.pt.y / gridSpacing) + 1) - curRect.pt.y;
rect split1 = new rect(curRect.pt, curRect.width, yDiv);
rect split2 = new rect(new point(curRect.pt.x, curRect.pt.y+yDiv), curRect.width, curRect.height-yDiv);
splitRectangle(grid, gridSpacing, split1);
splitRectangle(grid, gridSpacing, split2);
}
//if rectangle is fully contained within 1 grid zone, then add its area to that gridZone
else
{
grid[Math.Floor(curRect.pt.x / gridSpacing)][Math.Floor(curRect.pt.y / gridSpacing)] += curRect.width * curRect.height;
}
}
I wrote this quickly and did not test it, but it conveys the method that I think will allow you to do what you want. Again, the last step will be going through grid and dividing all cells by original rectangle area to turn them into percent...