若该文为原创文章,转载请注明原文出处。
一、项目介绍
由于博主太懒,mediapipe如何实现鼠标控制的原理直接忽略,最初的想法是想控制摄像头识别手指控制鼠标,达到播放电影的效果。基本上效果也是可以的。简单的说是使用mediapipe检测出手指的关键点,通过检测食指关键点去移动鼠标,当食指和中指距离小于一定值,当成点击事件处理。
二、环境搭建
使用的是miniconda3终端,前面有提及如何安装,不懂或不明白,自行百度。
1、打开终端
2、创建mediapipe虚拟环境
conda create -n mediapipe_env python=3.8
创建过程中提示如个界面,输入y
等待一会,就创建好了,如果出错,自行换 conda源。
根据提示,激活环境
3、激活环境
conda activate mediapipe_env
三、依赖安装
在编写代码前,需要先在安装mediapipe等一些依赖,安装前确保环境已经被激活。
1、安装mediapipe
pip install mediapipe -i https://pypi.tuna.tsinghua.edu.cn/simple
2、安装numpy
pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple
3、安装autopy
pip install autopy -i https://pypi.tuna.tsinghua.edu.cn/simple
4、安装opencv
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
四、代码及测试
代码直接使用notepad++编辑,看个人习惯,可以使用VS或pycharm或其他的
运行直接在终端操作。使用pycharm等需要自行搭建环境。
下面直接上代码
1、虚拟鼠标
AiVirtualMouse.py
import cv2
import HandTrackingModule as htm
import autopy
import numpy as np
import time##############################
wCam, hCam = 1080, 720
frameR = 100
smoothening = 5
##############################
cap = cv2.VideoCapture(0) # 若使用笔记本自带摄像头则编号为0 若使用外接摄像头 则更改为1或其他编号
cap.set(3, wCam)
cap.set(4, hCam)
pTime = 0
plocX, plocY = 0, 0
clocX, clocY = 0, 0detector = htm.handDetector()
wScr, hScr = autopy.screen.size()
# print(wScr, hScr)while True:success, img = cap.read()# 1. 检测手部 得到手指关键点坐标img = detector.findHands(img)cv2.rectangle(img, (frameR, frameR), (wCam - frameR, hCam - frameR), (0, 255, 0), 2, cv2.FONT_HERSHEY_PLAIN)lmList = detector.findPosition(img, draw=False)# 2. 判断食指和中指是否伸出if len(lmList) != 0:x1, y1 = lmList[8][1:]x2, y2 = lmList[12][1:]fingers = detector.fingersUp()# 3. 若只有食指伸出 则进入移动模式if fingers[1] and fingers[2] == False:# 4. 坐标转换: 将食指在窗口坐标转换为鼠标在桌面的坐标# 鼠标坐标x3 = np.interp(x1, (frameR, wCam - frameR), (0, wScr))y3 = np.interp(y1, (frameR, hCam - frameR), (0, hScr))# smoothening valuesclocX = plocX + (x3 - plocX) / smootheningclocY = plocY + (y3 - plocY) / smootheningautopy.mouse.move(wScr - clocX, clocY)cv2.circle(img, (x1, y1), 15, (255, 0, 255), cv2.FILLED)plocX, plocY = clocX, clocY# 5. 若是食指和中指都伸出 则检测指头距离 距离够短则对应鼠标点击if fingers[1] and fingers[2]:length, img, pointInfo = detector.findDistance(8, 12, img)if length < 40:cv2.circle(img, (pointInfo[4], pointInfo[5]),15, (0, 255, 0), cv2.FILLED)autopy.mouse.click()cTime = time.time()fps = 1 / (cTime - pTime)pTime = cTimecv2.putText(img, f'fps:{int(fps)}', [15, 25],cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 255), 2)cv2.imshow("Image", img)cv2.waitKey(1)
HandTrackingModule.py
import cv2
import mediapipe as mp
import time
import mathclass handDetector():def __init__(self, mode=False, maxHands=2, detectionCon=0.8, trackCon=0.8):self.mode = modeself.maxHands = maxHandsself.detectionCon = detectionConself.trackCon = trackConself.mpHands = mp.solutions.handsself.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon, self.trackCon)self.mpDraw = mp.solutions.drawing_utilsself.tipIds = [4, 8, 12, 16, 20]def findHands(self, img, draw=True):imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)self.results = self.hands.process(imgRGB)print(self.results.multi_handedness) # 获取检测结果中的左右手标签并打印if self.results.multi_hand_landmarks:for handLms in self.results.multi_hand_landmarks:if draw:self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)return imgdef findPosition(self, img, draw=True):self.lmList = []if self.results.multi_hand_landmarks:for handLms in self.results.multi_hand_landmarks:for id, lm in enumerate(handLms.landmark):h, w, c = img.shapecx, cy = int(lm.x * w), int(lm.y * h)# print(id, cx, cy)self.lmList.append([id, cx, cy])if draw:cv2.circle(img, (cx, cy), 12, (255, 0, 255), cv2.FILLED)return self.lmListdef fingersUp(self):fingers = []# 大拇指if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] - 1][1]:fingers.append(1)else:fingers.append(0)# 其余手指for id in range(1, 5):if self.lmList[self.tipIds[id]][2] < self.lmList[self.tipIds[id] - 2][2]:fingers.append(1)else:fingers.append(0)# totalFingers = fingers.count(1)return fingersdef findDistance(self, p1, p2, img, draw=True, r=15, t=3):x1, y1 = self.lmList[p1][1:]x2, y2 = self.lmList[p2][1:]cx, cy = (x1 + x2) // 2, (y1 + y2) // 2if draw:cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), t)cv2.circle(img, (x1, y1), r, (255, 0, 255), cv2.FILLED)cv2.circle(img, (x2, y2), r, (255, 0, 255), cv2.FILLED)cv2.circle(img, (cx, cy), r, (0, 0, 255), cv2.FILLED)length = math.hypot(x2 - x1, y2 - y1)return length, img, [x1, y1, x2, y2, cx, cy]def main():pTime = 0cTime = 0cap = cv2.VideoCapture(0)detector = handDetector()while True:success, img = cap.read()img = detector.findHands(img) # 检测手势并画上骨架信息lmList = detector.findPosition(img) # 获取得到坐标点的列表if len(lmList) != 0:print(lmList[4])cTime = time.time()fps = 1 / (cTime - pTime)pTime = cTimecv2.putText(img, 'fps:' + str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3)cv2.imshow('Image', img)cv2.waitKey(1)if __name__ == "__main__":main()
虚拟鼠标功能,当食指和中指合在一起后,画面消失,此时界面就可以通过手指来控制。
运行后出现(arg0:int)-> mediapipe.python._framework_bindings.packet.PacketInvoked with: 0.5这个错误
处理方法:
修改错误提示中solution_base.py文件中595行,改为如下:
return getattr(packet_creator,'create_'+ packet_data_type.value)(True if round(data)>0 else False)
如有侵权,或需要完整代码,请及时联系博主。