python正方形检测_如何使用python检测矩形物体

我正在用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()

以下是我的输出:

非工作输出

工作输出

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值