在最终图像上应用轮廓掩模

2024-04-19 11:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

在尝试从背景中分割植物时,我遇到了一个问题 通过色调值创建遮罩并对其使用“关闭”和“打开”操作符后,我进入以下情况: mask and original image

在这之后,我想删除图像边缘的小块,我通过以下操作完成了这一点:

_, cont, heir = cv2.findContours(mask_final, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
contour_sizes = [cv2.contourArea(contour) for contour in cont]
for con, size in zip(cont, contour_sizes):
    if size > 5000:
        mask_final = cv2.drawContours(mask_final, [con], -1, (255, 255, 255), cv2.FILLED)

应用此选项时,已移除斑点,但应用时:

final = cv2.bitwise_and(img_rgb,img_rgb, mask = mask_final)

我得到以下结果:

not working

可以看出,遮罩没有正确地应用在图像上,有人知道为什么会发生这种情况吗


Tags: in图像imgforsize情况maskrgb
1条回答
网友
1楼 · 发布于 2024-04-19 11:38:48

不要在cv2.drawContours函数中使用mask_final,而是创建一个与原始图像形状相同的新mask,并执行如下操作:

mask = np.zeros(img.shape, np.uint8)

for con, size in zip(contours, contour_sizes):
    if size > 5000:
        mask = cv2.drawContours(mask, [con], -1, (255, 255, 255), cv2.FILLED)

final = cv2.bitwise_and(img_rgb, img_rgb, mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY))

相关问题 更多 >