Trying to rasterize simple poly using cv2.fillPoly I get strange result - sum of no zero pixels is 10201, but it should be 100*100.
pts = np.array([[0, 0], [100, 0], [100, 100], [0, 100], [0, 0]])
img = np.zeros((256, 256))
vertices = np.array([pts], dtype=np.int32)
mask = cv2.fillPoly(img, vertices, color=255)
print('np.count_nonzero(mask)', np.count_nonzero(mask))
What wrong?
You made a simple off-by-one error -- it should be 101 * 101 (which is 10201).
To illustrate why, let's scale the problem down, and run your algorithm of the following set of points:
[[0, 0], [2, 0], [2, 2], [0, 2], [0, 0]]
and illustrate the progress on the following grid:

The call to cv2.fillPoly with those vertices does (conceptually) the following 5 things:
Draw line from (0,0) to (2,0)

Draw line from (2,0), to (2,2)

Draw line from (2,2), to (0,2)

Draw line from (0,2), to (0,0)

Fill the polygon

The result being

As you can see, there are 9 pixels filled:
(2 - 0) + 1 == 3).(2 - 0) + 1 == 3).Similarly, in your case: (100 - 0 + 1) * (100 - 0 + 1) = 101 * 101 = 10201
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With