Search code examples
pythonflood-fillopencv

OpenCV fill holes gives a white image


My goal is to fill black holes with white pixels in an image. For example on this image, I pointed out in red the blacks holes that I want to be filled with white.

objective

I'm using this piece of code to accomplish it.

im_floodfill = im_in.copy()
h, w = im_floodfill.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(im_floodfill, mask, (0,0), 255)
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
im_out = im_in | im_floodfill_inv

It works fine with most images but sometimes gives a white image.

Example with this input :

im_in im_in

im_floodfill_inv im_floodfill_inv

im_out im_out

Could you help me understand why I sometimes have a white im_out and how to fix it ?


Solution

  • I used a different approach by finding the contours on the image and using the hierarchy to determine if the contours found are children (there are no holes/contours inside them) then used those contours to fill in the holes. I used the screenshots you uploaded here, please next time try to upload the actual image you are using and not a screenshot.

    import cv2
    img = cv2.imread('vmHcy.png',0)
    
    cv2.imshow('img',img)
    
    # Find contours and hierarchy in the image
    contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    drawing = []
    for i,c in enumerate(contours):
        # Add contours which don't have any children, value will be -1 for these
        if hierarchy[0,i,1] < 0:
            drawing.append(c)
    img = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
    # Draw filled contours
    cv2.drawContours(img, drawing, -1, (255,255,255), thickness=cv2.FILLED)
    # Draw contours around filled areas with red just to indicate where these happened
    cv2.drawContours(img, drawing, -1, (0,0,255), 1)
    cv2.imshow('filled',img)
    
    cv2.waitKey(0)
    

    Result image with contours shown of the filled areas in red:

    enter image description here

    Zoomed in part you were showing:

    enter image description here