python - 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_out 以及如何解决它吗?
解决方案
我使用了另一种方法,通过查找图像上的轮廓并使用层次结构来确定找到的轮廓是否是子轮廓(其中没有孔/轮廓),然后使用这些轮廓来填充孔。我使用了您在此处上传的屏幕截图,请下次尝试上传您正在使用的实际图像而不是屏幕截图。
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)
结果图像,红色填充区域的轮廓显示:
放大您显示的部分:
推荐阅读
- c# - 脚本标签不起作用 ASP.NET 核心、webpack、打字稿和淘汰赛
- javascript - javascript 错误“电子邮件”未定义。[no-undef]
- rust - 在没有特征(move_ref_pattern)或 mem::replace 的情况下处理具有组合移动和参考的模式的策略是什么?
- python - SimpleImputer 使用两列计算平均值
- javascript - 如何迭代 Promise 值并填写表格?
- html - 如何从图像中删除此蓝色框?
- kubernetes - Calico Dual Stack 设置问题:服务无法访问其他节点的 pod
- javascript - Javascript TypeError:仅在 Safari 中使用 IntersectionObserver() 时出现类型错误
- javascript - 如何仅使用列出的键创建对象?
- javascript - 无法在 NavDropDown 上正确应用 css