【涵子来信&python大全】——第二季——opencv第四篇-用手势控制屏幕鼠标

各位亲爱的读者,博主:

大家好,我是涵子。今天我们需要使用cv2,mediapipe和pyautogui用手势控制屏幕鼠标。


目录

一、准备

二、代码


可以先去看看之前的文章哦。

一、准备

首先pip好所有包:

pip install opencv-python
pip install mediapipe
pip install pyautogui

如果pip有问题,请到这篇文章进行学习:

python大全-那些有用的包icon-default.png?t=N176https://blog.csdn.net/B20111003/article/details/125536325?spm=1001.2014.3001.5502 

如果之前的文章没有读过,请先去专栏界面进行选择和阅读。 

opencv专栏界面icon-default.png?t=N176https://blog.csdn.net/b20111003/category_12174317.html?spm=1001.2014.3001.5482

Tips:

如果你用的是mac的话,需要先在设置中设置好允许python控制电脑

windows不需要哦。 如果用的是没有摄像头的台式机或者老电脑,请事先准备好外置摄像头。

二、代码

因为内容过于难,所以我只给代码了...

思路:

1.导入库

2.让程序知道什么是手(hands)

3.写一个能让程序判断手指(食指)的函数

4.打开摄像头

5.显示摄像头并判断和操控

6.循环并检测

7.如果退出,关掉窗口,停止进程

import mediapipe as mp
import pyautogui as pa
import cv2
hands = mp.solutions.hands.Hands(min_detection_confidence=0.7,
                                min_tracking_confidence=0.7)

def isIndexFinger():
    fingerDict = {}
    for idx in range(21):
        fingerDict[idx] = hand_landmarks.landmark[idx].y
    fingerOrder = sorted(fingerDict, key = fingerDict.__getitem__)
    if fingerOrder[:3] == [8, 7, 6]:
        return True
    else:
        return False


controlFlag = 0
cam = cv2.VideoCapture(0)#打开摄像头
ret,frame = cam.read()#读取第一帧图像
print("Runing Program...")
while ret:#当图像读取成功的时候
    img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # 图像颜色模式转换
    width, height = img.shape[1], img.shape[0]
    result = hands.process(img)  # 用手部模型处理图片
    if result.multi_hand_landmarks:  # 两只手是否存在
        for hand_landmarks in result.multi_hand_landmarks:
            for i in range(21):
                x = int(hand_landmarks.landmark[i].x * width)
                y = int(hand_landmarks.landmark[i].y * height)
                cv2.circle(img,(x,y),5,(0,255,0),-1)
            x = int(hand_landmarks.landmark[8].x * width)
            y = int(hand_landmarks.landmark[8].y * height)
            if (hand_landmarks.landmark[8].y * height < hand_landmarks.landmark[12].y * height and hand_landmarks.landmark[16].y * height):
                if controlFlag == 0:
                    controlFlag = 1
                    x_p, y_p = x, y
                    x_n, y_n = x, y
                else:
                    x_p, y_p = x_n, y_n
                    x_n, y_n = x, y
                pa.moveRel(x_p - x_n, y_n - y_p)
            else:
                pass
    img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
    cv2.imshow("camera",img)
    cv2.waitKey(10)
    ret, frame = cam.read()#读取下一帧图像
cam.release()
cv2.destroyAllWindows()

最后,请大家给个关注,谢谢! 

好了,今天的文章就到这里了,我们下一期见!

涵子

2023/2/19

猜你喜欢

转载自blog.csdn.net/B20111003/article/details/129107415