【问题标题】:python Cv2-Draw Contours and fill black is ignoring perimeterpython Cv2-Draw Contours and fill black忽略了周长
【发布时间】:2022-01-27 16:43:06
【问题描述】:

我正在尝试使用以下方法从图像中移除对象,但是,从结果图像中可以看出,每个对象周围都有一条残留的细彩色线。虽然我已经放大了我的图像,但线条仍然存在。

有没有办法去掉这些线?

import cv2
import numpy as np

img = cv2.imread('TRY.jpg')
  
image_edges = cv2.GaussianBlur(img,(3,3),1) #Helps in defining the edges
image_edges=cv2.Canny(image_edges,100,200)

image_edges=cv2.dilate(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:

    cv2.drawContours(mask, [c], -1, (0, 0, 0), -1) 

mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)


res = img.copy()
res[mask == 0] = 255


cv2.imshow('img', res)
cv2.waitKey(0)

原图

--

结果图片

【问题讨论】:

  • 原因是因为开放(非封闭)轮廓。你可以使用for c in contours_draw: for i in range(len(c)-1): cv2.line(mask,tuple(c[i][0]),tuple(c[i+1][0]),(0,0,0),1)

标签: python opencv


【解决方案1】:

轮廓还在,因为门槛太高了。

试试这个:

imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 20, 255, 0)
contours_draw, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

您传递给阈值函数的值决定了 findContours 函数的包容性或排斥性。如果您想要低阈值,请输入低数字,如果您想要高阈值,请输入高数字。

【讨论】:

  • 感谢您的反馈。当我应用阈值时,它完全删除了 8 个形状。我仍然想得到它们的轮廓,以防我想修复它们或对这些轮廓执行任何操作。
  • 等等,您不想删除形状的轮廓,只删除那些轮廓中的颜色?
  • 我想删除剩余的轮廓,但我也想要所有形状的轮廓。当我应用阈值时,所有几何形状都被删除(除了中间书写),所以我将无法获得几何形状的轮廓。理想情况下,当我应用 RETR_External 时,所有轮廓都应该在轮廓内?不知道为什么会有残留线。
猜你喜欢
  • 2019-12-19
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 2018-03-24
  • 1970-01-01
相关资源
最近更新 更多