首页 > 解决方案 > OpenCV 填充孔给出了一个白色的图像

问题描述

我的目标是用图像中的白色像素填充黑洞。例如在这张图片上,我用红色指出了我想用白色填充的黑洞。

客观的

我正在使用这段代码来完成它。

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

它适用于大多数图像,但有时会给出白色图像。

此输入的示例:

算我一个 算我一个

im_floodfill_inv im_floodfill_inv

我出去了 我出去了

你能帮我理解为什么我有时会有一个白色的 im_out 以及如何解决它吗?

标签: pythonflood-fillopencv-python

解决方案


我使用了另一种方法,通过查找图像上的轮廓并使用层次结构来确定找到的轮廓是否是子轮廓(其中没有孔/轮廓),然后使用这些轮廓来填充孔。我使用了您在此处上传的屏幕截图,请下次尝试上传您正在使用的实际图像而不是屏幕截图。

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)

结果图像,红色填充区域的轮廓显示:

在此处输入图像描述

放大您显示的部分:

在此处输入图像描述


推荐阅读