Filling holes inside a binary object

There are two methods to do this:

1) Contour Filling:

First, invert the image, find contours in the image, fill it with black and invert back.

des = cv2.bitwise_not(gray)
contour,hier = cv2.findContours(des,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contour:
    cv2.drawContours(des,[cnt],0,255,-1)

gray = cv2.bitwise_not(des)

Resulting image:

enter image description here

2) Image Opening:

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
res = cv2.morphologyEx(gray,cv2.MORPH_OPEN,kernel)

The resulting image is as follows:

enter image description here

You can see, there is not much difference in both cases.

NB: gray – grayscale image, All codes are in OpenCV-Python


Reference. OpenCV Morphological Transformations

Leave a Comment