虚拟键盘AI

简介: 本文提供了一个虚拟键盘AI项目的详细代码实现,包括链接摄像头、手势识别、绘制键盘、确定选中字母以及使用`pynput`库模拟真实键盘输入的步骤,并附有环境配置指南。

虚拟键盘AI

网上有许多人写了原理,我就做重复工作了,唯一的愿望就是让后来者能无痛跑通代码
下面代码我下次更新会加上备注与层次说明,今天有点晚了
全部代码如下:

'''
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=1)
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
    # def draw(self,img):
    #     x,y = self.pos
    #     w,h = self.size
    #     cv2.rectangle(img, self.pos, (x+w,y+h), (255, 0, 255), cv2.FILLED)
    #     cv2.putText(img, self.text, (x+10,y+40),
    #                 cv2.FONT_HERSHEY_PLAIN, 3,(255, 255, 255), 2)
    #     return img
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))
#mybutton = Button([100,100],"Q")
def drawAll(img,buttonList):
    img1=img.copy()

    for button in buttonList:
        x, y = button.pos
        w, h = button.size
        cvzone.cornerRect(img1,(x,y,w,h),20,rt = 0)
        cv2.rectangle(img1, button.pos, (x + w, y + h), (255, 0, 255), cv2.FILLED)
        cv2.putText(img1, button.text, (x + 10, y + 40),
                    cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 2)
    img=cv2.addWeighted(img,0.5,img1,0.5,0)
    return img

flag=True
prePress='0'#prePress和count都是为了控制按键的
count = 0

prex=0
prey=0
pretext='A'
while True:
    success,img = cap.read()
    #识别手势
    img = cv2.flip(img, 1)
    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<lmList[8][0]<x+w and y<lmList[8][1]<y+h:
                cv2.rectangle(img, (x-5,y-5), (x + w + 5, y + h + 5), (175, 0, 175), cv2.FILLED)# 修改外矩形
                cv2.putText(img, button.text, (x + 10, y + 40),
                            cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 2)
                l,_,_ = detector.findDistance(8,12,img,draw=False)
                #print('中指(12)和食指(8)之间的距离:',l)
                fingerUpList=detector.fingersUp()
                print(str(lmList[8][0]) + " " + str(lmList[8][1]))
                num=fingerUpList[0]+fingerUpList[1]+fingerUpList[2]+fingerUpList[3]+fingerUpList[4]
                if len(lmList)>8 and num<=2:

                    count+=1
                    num1=int(lmList[8][0])
                    num2=int(lmList[8][1])
                    if (num1-prex)*(num1-prex)+(num2-prey)*(num2-prey)>300:#如果上一按過這個鍵,那這一轮就不能摁
                        keyboard.press(button.text)
                        cv2.rectangle(img, button.pos, (x + w, y + h), (0, 255, 0), cv2.FILLED)
                        cv2.putText(img, button.text, (x + 10, y + 40),cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 2)
                        finalText += button.text
                        print('当前选中的是:', button.text)

        prex = int(lmList[8][0])
        prey = int(lmList[8][1])

    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)
    cv2.namedWindow("Image",cv2.WINDOW_FREERATIO)
    cv2.imshow("Image",img)
    if cv2.waitKey(1)==ord('q'):
        break

配置环境

pip install cvzone==1.4.1 -i https://pypi.tuna.tsinghua.edu.cn/simple/
在这里插入图片描述
得下载1.41版本,最新版本会报错
pip install Controller -i https://pypi.tuna.tsinghua.edu.cn/simple/
在这里插入图片描述
pip install pynput -i https://pypi.tuna.tsinghua.edu.cn/simple/
在这里插入图片描述
pip install mediapipe -i https://pypi.tuna.tsinghua.edu.cn/simple/
在这里插入图片描述
运行效果:
请添加图片描述

相关文章
|
iOS开发 开发者
【教程】苹果 iOS 证书制作教程
【教程】苹果 iOS 证书制作教程
|
缓存 NoSQL Linux
Linux调试
本文介绍了Linux调试、性能分析和追踪的培训资料,涵盖调试、性能分析和追踪的基础知识及常用工具。
1875 63
Linux调试
|
11月前
|
数据采集 机器学习/深度学习 人工智能
YOLOv11浅浅解析:架构创新
YOLOv11是YOLO系列最新升级版,通过C3k2模块、SPPF优化和解耦检测头等创新,显著提升检测精度与速度,mAP提高2-5%,推理更快,支持多平台部署,适用于工业、安防、自动驾驶等场景。
|
11月前
|
存储 Unix PHP
初识PHP-快速上手指南
本文介绍了PHP编程的基础知识,涵盖语法格式、变量定义、数据类型、运算符、流程控制语句(如if、switch、循环)、常用内置函数、超全局变量及表单处理示例,帮助初学者快速掌握PHP核心语法与实际应用。
557 2
初识PHP-快速上手指南
|
8月前
|
人工智能 JavaScript 程序员
Wispr Flow 平替, 这款开源中文语音助手,程序员真该试试,本地离线的中文语音输入神器来了(开源白嫖版)
小华同学推荐开源神器「蛐蛐QuQu」:本地语音识别+AI润色,中文友好、隐私安全,免订阅费替代Wispr Flow。支持通义千问等国产模型,程序员专属语音工作流,写代码、记会议、回邮件效率翻倍!
1205 0
Wispr Flow 平替, 这款开源中文语音助手,程序员真该试试,本地离线的中文语音输入神器来了(开源白嫖版)
|
存储 监控 容灾
容灾备份的具体操作步骤
【10月更文挑战第28天】容灾备份是指为了防止因自然灾害、人为破坏、系统故障等原因导致数据丢失或业务中断,而提前采取的一系列数据备份和恢复措施。
|
安全 网络安全 网络虚拟化
Cisco-三层交换机实现VLAN间路由
Cisco-三层交换机实现VLAN间路由
617 0
|
开发工具 图形学 Android开发
从零开始的unity3d入门教程(一)----环境配置
该文章是《从零开始的Unity3D入门教程》系列的第一篇,详细介绍了Unity3D的环境配置过程,包括注册Unity账户、下载安装Unity Hub和Unity编辑器、配置许可证、创建Unity项目、下载安装Visual Studio 2022以及将Unity与Visual Studio相关联等步骤。
从零开始的unity3d入门教程(一)----环境配置
|
监控 安全 计算机视觉
实战 | 18行代码轻松实现人脸实时检测【附完整代码与源码详解】Opencv、人脸检测
实战 | 18行代码轻松实现人脸实时检测【附完整代码与源码详解】Opencv、人脸检测