import cv2
import math
import numpy as np
import cvzone
frameWidth=640
frameHeight=480
cap=cv2.VideoCapture(2)
cap.set(3,frameWidth)
cap.set(4,frameHeight)
cap.set(10,150)
x=[400,445,400,360,300,245,200,170,145,130,112,103,93,87,80,75,70,67,62,59,57] #下面计算出的distance
y=[0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100] #手与摄像头的距离
coff=np.polyfit(x,y,2)
def getContours(img):
contours,hieracrhy=cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area=cv2.contourArea(cnt)
if area>50:
cv2.drawContours(imgContour,cnt,-1,(255,0,0),3) #画轮廓
peri=cv2.arcLength(cnt,True)
approx=cv2.approxPolyDP(cnt,0.02*peri,True)
x,y,w,h=cv2.boundingRect(approx)
# print(w,h)
distance=int(math.sqrt((w**2+h**2)))
A, B ,C= coff
distanceCM = A * distance + B * distance + C # Ax+Bx+C 该图像为二次函数
# print(A,B)
print(distance,distanCM)
cvzone.putTextRect(imgContour, f'{int(distanceCM)-30}cm', (x , y ))
cv2.rectangle(imgContour,(x,y),(x+w,y+h),(255,0,0),2)
while True:
success,img=cap.read()
imgContour=img.copy()
imgHSV=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
# [[20, 0, 117, 97, 253, 150], # 黄色
# [66, 136, 0, 179, 255, 255], # 蓝色
# [0, 166, 72, 90, 255, 255]] # 红色
color=[66, 136, 0, 179, 255, 255]
lower = np.array(color[0:3])
upper = np.array(color[3:6])
mask=cv2.inRange(imgHSV,lower,upper) #返回白色想要获取部分
Result=cv2.bitwise_and(img,img,mask=mask) #第一个为输入图像,第二个为输出
mask1=cv2.cvtColor(mask,cv2.COLOR_GRAY2BGR)
getContours(mask)
cv2.imshow('imgContour',imgContour)
# cv2.imshow('imgResult',Result)
# cv2.imshow('imgMASK',mask1)
# cv2.imshow('img',img)
cv2.waitKey(1)