【问题标题】:Detect rectangles in OpenCV (4.2.0) using Python (3.7),使用 Python (3.7) 在 OpenCV (4.2.0) 中检测矩形,
【发布时间】:2020-07-24 17:32:06
【问题描述】:

我正在做一个个人项目,我检测矩形(所有相同的尺寸),然后将这些矩形以相同的顺序(从上到下)放在一个列表中,然后使用一些函数处理每个矩形内的信息。下面是我的测试图。

我已经设法检测到感兴趣的矩形,但是我不断得到其他我不想要的矩形。如您所见,我只希望将包含信息 (6,9,3) 的三个矩形放入一个列表中。

我的代码

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

【问题讨论】:

    标签: python-3.x opencv opencv-contour


    【解决方案1】:

    Contour 中有一个名为 cv2.contourArea 的功能,您的轮廓尺寸是这样输入的 cv2.contourArea(contours) 。你可以使用条件,

    if cv2.contourArea(contours)>#Rectangle area
    

    你的问题就解决了

    【讨论】:

    • 我用过那个函数,但是我得到了 4 个大矩形而不是 3 个。
    • @AlanJones 您提供的#Rectangle 区域是什么?并使用and 关键字或任何其他方式将其添加到您的if Statement 中?
    • 我正在遍历所有区域以查看每个轮廓的区域。这就是为什么我看到 4 个大区域而不是 3 个(如预期的那样)。
    【解决方案2】:

    我建议您获取轮廓的边界矩形,然后按面积降序对矩形进行排序。默认情况下裁剪第一个矩形,然后遍历剩余的矩形并裁剪它们,假设它们 >=90% 的第一个矩形的区域。这将确保您拥有较大的矩形而忽略较小的矩形。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2012-04-10
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      相关资源
      最近更新 更多