使用 python 在图像中查找轮廓后删除异常值线



我想检测图像中的所有矩形,我在OpenCv中使用findContours,我想删除由FindContours识别的不必要的形状。

我的图像 https://i.stack.imgur.com/eLb1s.png

我的结果:https://i.stack.imgur.com/xQqeF.png

我的代码:

img =cv2.imread('CD/A.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
img1=np.ones(img.shape, dtype=np.uint8)*255
ret,thresh = cv2.threshold(gray,127,255,1)
(_,contours,h) = cv2.findContours(thresh,1,2)
for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    if len(approx)==4:
        cv2.drawContours(img1,[cnt],0,(0,255,0),2)
cv2.imshow('Detected line',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

我想删除矩形中存在的这些极端线条:
https://i.stack.imgur.com/n9byP.png

需要你的帮助伙计们.

您可以做的一件事是找到连接的组件并删除较小的组件:

from skimage.morphology import label
import numpy as np
comps = label(thresh) # get the label map of the connected components
# The comps array will have a unique integer for each connected component
# and 0 for the background. np.unique gets the unique label values.
#
# Therefore, this loop allows us to pluck out each component from the image
for i in range(1, len(np.unique(comps))):
    # comps == i will convert the array into True (1) if that pixel is in the
    # i-th component and False (0) if it is not.
    #
    # Therefore, np.sum(comps == i) returns the "area" of the component
    if np.sum(comps == i) < small_number:
        # If the area is less than some number of pixels,
        # set the pixels of this component to 0 in the thresholded image
        thresh[comps == i] = 0

你也可以用OpenCV做标签,也可以用connectedComponentsWithStats或类似的东西,但我更熟悉skimage。

如果可以将图像转换为二进制图像(具有简单的阈值(,则可以执行形态打开操作,该操作可以帮助您过滤掉矩形内图像中的小线条,然后在新图像上再次找到轮廓。

https://docs.opencv.org/trunk/d9/d61/tutorial_py_morphological_ops.html

相关内容

  • 没有找到相关文章