mrgloom
mrgloom

Reputation: 21642

cv2.fillPoly strange results

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?

Upvotes: 3

Views: 943

Answers (1)

Dan Mašek
Dan Mašek

Reputation: 19041

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:

  • 3 columns are used (0 to 2, inclusive, meaning (2 - 0) + 1 == 3).
  • 3 rows are used (0 to 2, inclusive, meaning (2 - 0) + 1 == 3).

Similarly, in your case: (100 - 0 + 1) * (100 - 0 + 1) = 101 * 101 = 10201

Upvotes: 3

Related Questions