使用 Python (3.7) 在 OpenCV (4.2.0) 中检测矩形, [英] Detect rectangles in OpenCV (4.2.0) using Python (3.7),

查看:108
本文介绍了使用 Python (3.7) 在 OpenCV (4.2.0) 中检测矩形,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a personal project where I detect rectangles (all the same dimensions) and then place those rectangles inside a list in the same order (top-bottom) and then process the information inside each rectangle using some function. Below is my test image.

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

I have managed to detect the rectangle of interest, however I keep getting other rectangles that I don't want. As you can see I only want the three rectangles with the information (6,9,3) into a list.

我的代码

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

推荐答案

Contour 中有一个叫做 cv2.contourArea 的特征,你的轮廓尺寸是这样输入的 cv2.contourArea(轮廓).您可以使用条件,

There is a feature in Contour called cv2.contourArea for which your contour dimensions are input like this cv2.contourArea(contours) . You can use the condition,

if cv2.contourArea(contours)>#Rectangle area

通过使用它,您的问题将得到解决

By using this your problem will be solved

这篇关于使用 Python (3.7) 在 OpenCV (4.2.0) 中检测矩形,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆