我想检测图像中的所有矩形,并在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
需要你的帮助。
答案 0 :(得分: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
您也可以使用OpenCV进行标签制作,也可以使用connectedComponentsWithStats
或类似的工具制作标签,但是我对skimage更为熟悉。
答案 1 :(得分:0)
如果您可以将图像转换为二进制图像(具有简单的阈值),则可以执行形态学打开操作,这可以帮助您在矩形内过滤掉图像中的小线条,然后在新图像上再次找到轮廓线
https://docs.opencv.org/trunk/d9/d61/tutorial_py_morphological_ops.html