python - 如何使用python检测矩形物体

标签 python opencv

我正在用 python 做一个项目。我想通过使用 python 打开网络摄像头来检测矩形形状的对象。我试过了,但没有得到准确的答案。我在网络摄像头前面显示对象如果有手指触摸我们的对象它无法识别我们的对象。请任何人帮助我。提前致谢:) 这是我的代码: :

import math
import numpy as np
import cv2

#dictionary of all contours
contours = {}
#array of edges of polygon
approx = []
#scale of the text
scale = 2
#camera
cap = cv2.VideoCapture(0)
print("press q to exit")

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

#calculate angle
def angle(pt1,pt2,pt0):
    dx1 = pt1[0][0] - pt0[0][0]
    dy1 = pt1[0][1] - pt0[0][1]
    dx2 = pt2[0][0] - pt0[0][0]
    dy2 = pt2[0][1] - pt0[0][1]
    return float((dx1*dx2 + dy1*dy2))/math.sqrt(float((dx1*dx1 + dy1*dy1))*(dx2*dx2 + dy2*dy2) + 1e-10)

while(cap.isOpened()):
    #Capture frame-by-frame
    ret, frame = cap.read()
    if ret==True:
        #grayscale
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #Canny
        canny = cv2.Canny(frame,80,240,3)

        #contours
        canny2, contours, hierarchy = cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        for i in range(0,len(contours)):
            #approximate the contour with accuracy proportional to
            #the contour perimeter
            approx = cv2.approxPolyDP(contours[i],cv2.arcLength(contours[i],True)*0.02,True)

            #Skip small or non-convex objects
            if(abs(cv2.contourArea(contours[i]))<100 or not(cv2.isContourConvex(approx))):
                continue

            x,y,w,h = cv2.boundingRect(contours[i])
            vtc = len(approx)
            if(vtc==4):
                cv2.putText(frame,'RECTANGLE',(x,y),cv2.FONT_HERSHEY_SIMPLEX,scale,(255,255,255),2,cv2.LINE_AA)

        #Display the resulting frame
        out.write(frame)
        cv2.imshow('frame',frame)
        cv2.imshow('canny',canny)
        if cv2.waitKey(1) == 1048689: #if q is pressed
            break

#When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

这是我的输出:

非工作输出

first object output

工作输出

Another object Output

最佳答案

您当前的代码中包含此部分:

        #Skip small or non-convex objects
        if(abs(cv2.contourArea(contours[i]))<100 or not(cv2.isContourConvex(approx))):
            continue

        x,y,w,h = cv2.boundingRect(contours[i])
        vtc = len(approx)
        if(vtc==4):
            cv2.putText(frame,'RECTANGLE',(x,y),cv2.FONT_HERSHEY_SIMPLEX,scale,(255,255,255),2,cv2.LINE_AA)

这里可以围绕轮廓创建一个矩形并比较区域。为此,可以使用 boundingRect,但是,您的手机可能会稍微倾斜,因此 minAreaRect 更适用于此。它将返回 ((x,y), (w,h), angle) 您关心的是 (w,h) 部分,因为该区域是 w*h。您已经知道获取轮廓的实际区域很重要,因为它在您的代码中。

最后的代码应该是这样的:

        #Skip small or non-convex objects
        if(abs(cv2.contourArea(contours[i]))<100 or not(cv2.isContourConvex(approx))):
            continue

        x,y,w,h = cv2.boundingRect(contours[i])
        vtc = len(approx)
        rect = cv2.minAreaRect(contours[i])
        rectArea = rect[1][0] * rect[1][1]
        contourArea = cv2.contourArea(contours[i])
        # now it will check if the difference is less than 10% of the rect area
        if vtc==4 or abs(rectArea - contourArea) < rectArea * .10:
            cv2.putText(frame,'RECTANGLE',(x,y),cv2.FONT_HERSHEY_SIMPLEX,scale,(255,255,255),2,cv2.LINE_AA)

这可能会奏效,但您可能需要调整阈值(我使用了 10% 的 rectArea)。即使是 4 点检查也可以省略,如果它是一个矩形,它将有一个完美的拟合 (rectarea-contourarea) = 0。

我希望这会有所帮助,但这是一种简单的方法。更多可能的答案也适用于此。您甚至可以用机器学习算法或矩形拟合算法来思考。

关于python - 如何使用python检测矩形物体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47427767/

相关文章:

python - 'from modulename import function/variable' 是否将整个模块放入 sys 模块字典中?

python - get_dummies 分割字符

c++ - 使用 OpenCV 和 BCM2835 在 Raspberry Pi 上工作

opencv - 对图像进行上采样

opencv - OpenCV Hough线变换可提供不存在的水平线

python - 从 Pandas 数据框中的前一行中减去日期时间值

python - Alexa 技能 : Get user location

Python - 根据值附加特定的 numpy 数组

python - cv2将c++的Range和copyTo函数转换为python

user-interface - 用于实验 OpenCV 的 GUI 发生了什么变化?