Home > front end >  How to fill color correctly in closed curve using opencv python
How to fill color correctly in closed curve using opencv python

Time:12-19

I would like to fill black and white image using floodfill operation but some parts are missing as shown by first row images and some parts are not filled properly (looks some parts become separated from main object) as shown by second row images . To describe, I show some examples below :

Before vs after floodfill:

enter image description here

Below is my code :

 im_in = cv2.imread(path to image,cv2.IMREAD_GRAYSCALE)
 th, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY_INV)
 im_floodfill = im_th.copy()
 h, w = im_th.shape[:2]
 mask = np.zeros((h 2, w 2), np.uint8)
 cv2.floodFill(im_floodfill, mask, (0,0), 255)

please advise

thank you

CodePudding user response:

The reason some parts of the image seems to be missing is because the cv2.floodFill() method does not include the outlines of a shape as part of the area that needs to be filled.

If you want to keep the lines, you can use the cv2.RETR_TREE flag in the cv2.findContours() method:

import cv2
import numpy as np

img = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE)
img_canny = cv2.Canny(img, 50, 50)
img_dilate = cv2.dilate(img_canny, None, iterations=1)
img_erode = cv2.erode(img_dilate, None, iterations=1)

mask = np.full(img.shape, 255, "uint8")
contours, hierarchies = cv2.findContours(img_erode, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
    cv2.drawContours(mask, [cnt], -1, 0, -1)
    
cv2.imshow("result", mask)
cv2.waitKey(0)

Input file:

enter image description here

Output file:

enter image description here

  • Related