目录
PS:一个来自印度老哥的cvzone网站的小项目,这里做源码的讲解
效果演示:
原理及流程:
代码如下:
源码剖析:
'''
1.链接摄像头
2.识别手势
3.绘制键盘
3.1创建键盘字母List
3.2通过循环绘制键盘
4.根据坐标,取得返回字母
4.1 利用lmList[8]食指之间坐标,判断选中的字母
4.2 利用食指与中指之间的距离,确认输入的字母
5.扩展,修改键盘背景
6.利用pynput模拟真实键盘输入
'''
import cv2
from cvzone.HandTrackingModule import HandDetector
from time import sleep
import numpy as np
import cvzone
from pynput.keyboard import Key,Controller
cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)
#识别手势
detector = HandDetector(detectionCon=0.8)
keyboard = Controller()
#键盘关键字
keys = [['Q','W','E','R','T','Y','U','I','O','P'],
['A','S','D','F','G','H','J','K','L',';'],
['Z','X','C','V','B','N','M',',','.','/']]
class Button():
def __init__(self,pos,text,size = [50,50]):
self.pos = pos
self.text = text
self.size = size
buttonList = []
finalText = ''
for j in range(len(keys)):
for x,key in enumerate(keys[j]):
#循环创建buttonList对象列表
buttonList.append(Button([60*x+20,100+j*60],key))
def drawAll(img,buttonList):
for button in buttonList:
x, y = button.pos
w, h = button.size
cvzone.cornerRect(img,(x,y,w,h),20,rt = 0)
cv2.rectangle(img, button.pos, (x + w, y + h), (255, 0, 255), cv2.FILLED)
cv2.putText(img, button.text, (x + 10, y + 40),
cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 2)
return img
while True:
success,img = cap.read()
#识别手势
img = detector.findHands(img)
lmList,bboxInfo = detector.findPosition(img)
img = drawAll(img,buttonList )
if lmList:
for button in buttonList:
x,y = button.pos
w,h = button.size
if x
cap.set(3,1280) #设置摄像头窗口的宽度为1280 cap.set(4,720) #设置摄像头窗口的高度为720
from pynput.keyboard import Key,Controller
keyboard = Controller() #获取键盘的操控对象
class Button(): #创建虚拟键盘的按钮对象,分别是位置,内容,和默认为50*50的大小
def __init__(self,pos,text,size = [50,50]):
self.pos = pos
self.text = text
self.size = size
buttonList = []
for j in range(len(keys)):
for x,key in enumerate(keys[j]):
buttonList.append(Button([60*x+20,100+j*60],key)) #循环创建buttonList对象列表
def drawAll(img,buttonList): #在图像上绘制所有的自定义键盘按钮 for button in buttonList: x, y = button.pos w, h = button.size cvzone.cornerRect(img,(x,y,w,h),20,rt = 0) #在按钮图像的轮廓边缘进行以四个角延伸20px的绿色线条 cv2.rectangle(img, button.pos, (x + w, y + h), (255, 0, 255), cv2.FILLED) #以红色填充键盘按钮区域 cv2.putText(img, button.text, (x + 10, y + 40), cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 2)#将自定义的键盘的内容显示到图像上的指定位置,以FONT_HERSHEY_PLAIN字体,3的字体大小,白色颜色,2px的粗细 return img
输出选中的信息框 cv2.rectangle(img, (20,350), (600, 400), (175, 0, 175), cv2.FILLED) #绘制输出框 cv2.putText(img, finalText, (20, 390), cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 4) #将已经录入的字符全部显示到图像帧上对应的输出框中
lmList,bboxInfo = detector.findPosition(img) #会在识别出手部信息后在周围框上绿色的框