0

I want to detect all rectangles in image and I use findContours in OpenCv , and I want to delete unnecessary shapes that have been identified by FindContours.

My image https://i.stack.imgur.com/eLb1s.png

My result: https://i.stack.imgur.com/xQqeF.png

My code:

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()

I want to remove these extreme lines that exist within the rectangles :
https://i.stack.imgur.com/n9byP.png

Need your help guys .

4

2 回答 2

1

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

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

您也可以使用 OpenCVconnectedComponentsWithStats或类似的东西进行标记,但我更熟悉 skimage。

于 2018-07-26T19:39:22.070 回答
0

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

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

于 2018-03-25T22:37:09.853 回答