使用Python(3.7)和OpenCV(4.2.0)检测矩形。

6
我正在进行一个个人项目,其中我检测矩形(所有矩形具有相同的尺寸),然后按照顶部-底部的顺序将这些矩形放入列表中,然后使用某些函数处理每个矩形内部的信息。以下是我的测试图像。

Test Image

我已经成功检测到感兴趣的矩形,但我仍然得到了其他不需要的矩形。如您所见,我只想将包含信息(6,9,3)的三个矩形放入列表中。

My output when I run my code

我的代码

import cv2

width=700
height=700
y1=0
y2=700
x1=500
x2=700
img=cv2.imread('test.jpg') #read image
img=cv2.resize(img,(width,height)) #resize image
roi = img[y1:y2, x1:x2] #region of interest i.e where the rectangles will be
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) #convert roi into gray
Blur=cv2.GaussianBlur(gray,(5,5),1) #apply blur to roi
Canny=cv2.Canny(Blur,10,50) #apply canny to roi

#Find my contours
contours =cv2.findContours(Canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[0]

#Loop through my contours to find rectangles and put them in a list, so i can view them individually later.
cntrRect = []
for i in contours:
        epsilon = 0.05*cv2.arcLength(i,True)
        approx = cv2.approxPolyDP(i,epsilon,True)
        if len(approx) == 4:
            cv2.drawContours(roi,cntrRect,-1,(0,255,0),2)
            cv2.imshow('Roi Rect ONLY',roi)
            cntrRect.append(approx)



cv2.waitKey(0)
cv2.destroyAllWindows()
2个回答

4
Contour 中有一个名为 cv2.contourArea 的特性,用于输入轮廓的尺寸信息,如下: cv2.contourArea(contours)。您可以使用以下条件:
if cv2.contourArea(contours)>#Rectangle area

通过使用这个,您的问题将会得到解决。


我已经使用了那个函数,但是我得到了4个大矩形而不是3个。 - Alan Jones
@AlanJones,您提供的#矩形面积是多少?您是使用“and”关键字还是其他方式将其添加到您的“if语句”中? - Sreevathsabr
我正在循环遍历所有区域,以查看每个轮廓的面积是多少。这就是为什么我看到了4个大区域,而不是预期的三个。 - Alan Jones

0
我建议您获取轮廓的边界矩形,然后按面积降序排序。默认情况下裁剪第一个矩形,然后循环遍历其余矩形并裁剪它们,如果它们的面积大于或等于第一个矩形的90%,则进行裁剪。这将确保您拥有更大的矩形,并忽略较小的矩形。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接