【发布时间】:2022-01-27 15:53:53
【问题描述】:
我正在尝试在图像中找到水果的轮廓并将其填充为黑色,以便我可以将其添加到另一张图像或对其进行遮罩。
但是,根据下面的意外结果图像,我只得到没有填充颜色的轮廓。这可能是由于线路断开造成的,但是我试图扩大我的图像并模糊以解决但没有成功。 有什么建议吗?
import cv2
import numpy as np
img=cv2.imread('/home/usr/Desktop/fruit.png')
image_edges = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#
image_edges = cv2.GaussianBlur(image_edges,(3,3),1) #To connect broken lines
image_edges=cv2.Canny(image_edges,100,200)#Edge detection
image_edges=cv2.dilate(image_edges,(3,3),iterations=3)
image_edges=cv2.erode(image_edges,(3,3),iterations=3)
contours_draw, hierarchy = cv2.findContours(image_edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
mask = np.zeros(img.shape, np.uint8)
mask.fill(255)
for c in contours_draw:
area = cv2.contourArea(c)
if area > 100: # greater the value, less detail will be shown
cv2.drawContours(mask, [c], -1, (0, 0, 0), -1)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
cv2.imshow('img', mask)
cv2.waitKey(0)
原图
意外结果:
【问题讨论】:
-
大纲未关闭。在顶部有一个 1 像素的间隙。 ——为什么所有的杂技,尤其是 Canny,往往会使情况变得更糟?简单地说阈值,你有一个明亮的物体在黑暗的背景。
-
谢谢。我正在为下一届奥运会做准备。