Home > Back-end >  Generic fill shapes using Python & OpenCV
Generic fill shapes using Python & OpenCV

Time:12-22

I want to know the area (number of 'white' pixels) of some shapes in a image.

After some image processing I'm getting a binary images like that: enter image description here

And want to 'fill' the empty shapes in white and than count the white pixels to know the area of the shapes.

To do so I'm using this code:

# Filling shapes
kernel = np.ones((1000, 500), np.uint8)
closing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel, iterations=1)

And this gives me the expected image: enter image description here

Than I'm counting the white pixels and gets the area (in pixels) of the shapes.

My issue is that the shapes is always different and I don't know how to make my code more generic to fill any other shapes - For example this shapes image: enter image description here

Gives me this unwanted result (in the left side in this case) with the same filling shapes code: enter image description here

Any ideas what can I do for more generic fill kernel (or something else..)?

Many thanks in advance!

CodePudding user response:

When the contours are closed, seed filling or polygon filling are standard methods. When they are not, morphological closing as large as the contour interruptions can help.

The "left side" effect that you see is due to the dilation reaching the left edge. If you enlarge the image on the left, this will no more be produced (as long as the two shapes do not come in contact).

  • Related