代码和笔记
import cv2
import numpy as np
import time
from cvzone. HandTrackingModule import HandDetector"""
项目:虚拟计数器
cvzone:cv任务开源库
mediapipe:姿态估计开源库(在cvzone里面)
"""
cap = cv2. VideoCapture( 0 )
cap. set ( 3 , 1280 )
cap. set ( 4 , 720 )
class Button : def __init__ ( self, pos, width, height, value) : self. pos = posself. width = widthself. height = heightself. value = valuedef draw ( self, _img) : cv2. rectangle( _img, ( self. pos[ 0 ] , self. pos[ 1 ] ) , ( self. pos[ 0 ] + self. width, self. pos[ 1 ] + self. height) , ( 225 , 225 , 225 ) , - 1 ) cv2. rectangle( _img, ( self. pos[ 0 ] , self. pos[ 1 ] ) , ( self. pos[ 0 ] + self. width, self. pos[ 1 ] + self. height) , ( 0 , 0 , 0 ) , 3 ) cv2. putText( _img, self. value, ( self. pos[ 0 ] + 30 , self. pos[ 1 ] + 70 ) , cv2. FONT_HERSHEY_PLAIN, 2 , ( 50 , 50 , 50 ) , 2 ) def check_click ( self, x, y) : if self. pos[ 0 ] < x < self. pos[ 0 ] + self. width and self. pos[ 1 ] < y < self. pos[ 1 ] + self. height: cv2. rectangle( img, ( self. pos[ 0 ] + 3 , self. pos[ 1 ] + 3 ) , ( self. pos[ 0 ] + self. width - 3 , self. pos[ 1 ] + self. height - 3 ) , ( 255 , 255 , 255 ) , - 1 ) cv2. putText( img, self. value, ( self. pos[ 0 ] + 25 , self. pos[ 1 ] + 80 ) , cv2. FONT_HERSHEY_PLAIN, 5 , ( 0 , 0 , 0 ) , 5 ) return True else : return False
button_values = [ [ '7' , '8' , '9' , '*' ] , [ '4' , '5' , '6' , '-' ] , [ '1' , '2' , '3' , '+' ] , [ '0' , '/' , '.' , '=' ] ] button_list = [ ]
for x in range ( 4 ) : for y in range ( 4 ) : x_pos = x * 100 + 800 y_pos = y * 100 + 150 button = Button( ( x_pos, y_pos) , 100 , 100 , button_values[ y] [ x] ) button_list. append( button)
detector = HandDetector( maxHands= 1 , detectionCon= 0.8 )
equation = ''
delay_count = 0 while True : flag, img = cap. read( ) img = cv2. flip( img, 1 ) hands, img = detector. findHands( img, flipType= False ) if flag: for button in button_list: button. draw( img) cv2. rectangle( img, ( 800 , 70 ) , ( 800 + 400 , 70 + 80 ) , ( 225 , 225 , 225 ) , - 1 ) cv2. rectangle( img, ( 800 , 70 ) , ( 800 + 400 , 70 + 80 ) , ( 50 , 50 , 50 ) , 3 ) if hands: lmList = hands[ 0 ] [ 'lmList' ] lmList = [ x[ : 2 ] for x in lmList] length, _, img = detector. findDistance( lmList[ 8 ] , lmList[ 12 ] , img) x, y = lmList[ 8 ] if length < 50 and delay_count == 0 : for i, button in enumerate ( button_list) : if button. check_click( x, y) : values = button_values[ int ( i % 4 ) ] [ int ( i / 4 ) ] if values == '=' : try : equation = str ( eval ( equation) ) except Exception: equation = '' else : equation += valuesdelay_count = 1 if delay_count != 0 : delay_count += 1 if delay_count > 10 : delay_count = 0 cv2. putText( img, equation, ( 810 , 130 ) , cv2. FONT_HERSHEY_PLAIN, 3 , ( 0 , 0 , 0 ) , 3 ) cv2. imshow( 'img' , img) key = cv2. waitKey( 1 ) if key == ord ( 'q' ) : break elif key == ord ( 'c' ) : equation = '' else : print ( '摄像头打开失败' ) break cap. release( )
cv2. destroyAllWindows( )