If I am having a convex polygon vertices, then my area calculation in image is not coming accurate by the standard formula.
(For simiplicity) if I am having 3x3 square, and the vertices are (1,1) (1,3) (3,3) (3,1)
by polygon area calculation method depicted here
and dividing the summation by 2 we get the Area.
So for the 3 x 3 data above, we'll get area as 4 instead of 9.
This is happening because vertices are not points but a pixel.
this is the corresponding code. The coordinates are cyclic.
int X[] = { 1, 1, 3, 3, 1};
int Y[] = { 1, 3, 3, 1, 1};
double Sum1 = 0;
double Sum2 = 0;
int numElements = 5;
for (int k = 0; k < numElements-1; k++)
{
Sum1 += X[k] * Y[k + 1];
Sum2 += Y[k] * X[k + 1];
}
double area = std::abs((double)(Sum1 - Sum2))/2;
For square, we can do +1 to width and height and get the area correct. But what about the irregular polygons in the image? I hope the question makes sense.
The area can be calculated in following steps:
1) fetching the pixels between the vertices
2) sorting the pixels by x coordinates (or y coordinates)
3) taking the difference between min and max y coordinates (or x) for a particular x (or y) value and adding one to the difference
4) summing up the total difference
NOTE: the area might vary (if there are slanted edges in the polygon) depending on the line drawing method chosen