opencv实现手势识别进行虚拟拖放

opencv实现手势识别进行虚拟拖放

本文将实现一些通过手拖放一些框,我们可以使用这个技术实现一些游戏,控制机械臂等很多有趣的事情。

第一步

通过opencv设置显示框和调用摄像头显示当前画面

import cv2

cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)

while True:
    succes, img = cap.read()
    cv2.imshow("Image", img)
    cv2.waitKey(1)

第二步

在当前画面中找到手,本文将使用cv zone中的手跟踪模块

from cvzone.HandTrackingModule import HandDetector

detector = HandDetector(detectionCon=0.8)#更改了默认的置信度,让其检测更加准确

找到手的完整代码

import cv2
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)

detector = HandDetector(detectionCon=0.8)
while True:
    succes, img = cap.read()
    detector.findHands(img)
    lmList, _ = detector.findPosition(img)
    cv2.imshow("Image", img)
    cv2.waitKey(1)

在这里插入图片描述

第三步

第三步首先创建一个方块

cv2.rectangle(img, (100,100), (300,300), (0, 0 , 255),cv2.FILLED)

在这里插入图片描述
然后检测我们的食指有没有进入到这个方框中,如果进入的话,这个方框就改变颜色

    if lmList:
        cursor = lmList[8]
        if 100<cursor[0]<300 and 100<cursor[1]<300:
            colorR =0, 255, 0
        else:
            colorR = 0,0,255

    cv2.rectangle(img, (100,100), (300,300), colorR,cv2.FILLED)

在这里插入图片描述
然后检测我们是否点击这个方框
当我们食指的之间在这个方框的中心,就会跟随为我们的指尖运动。
在这里插入图片描述
但是这样的话,我们不想这个方块跟随我,我就得很快的将手移开,不是很方便。
所以我们要模拟鼠标点击确定是否选中它,所以我们就在加入了一根中指来作为判断,那判断的依据就是中指和食指指尖的距离。

l,_,_ = detector.findDistance(8,12,img)

在这里插入图片描述
假设俩指尖的距离小于30就选中,大于30就取消

        if l<30:
            cursor = lmList[8]
            if cx-w//2<cursor[0]<cx+w//2 and cy-h//2<cursor[1]<cy+h//2:
                colorR =0, 255, 0
                cx, cy = cursor
            else:
                colorR = 0,0,255

完整代码

import cv2
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)
colorR =(0, 0, 255)
detector = HandDetector(detectionCon=0.8)
cx, cy, w, h= 100, 100, 200, 200

while True:
    succes, img = cap.read()
    img = cv2.flip(img, 1)
    detector.findHands(img)
    lmList, _ = detector.findPosition(img)
    if lmList:
        l,_,_ = detector.findDistance(8,12,img)
        print(l)
        if l<30:
            cursor = lmList[8]
            if cx-w//2<cursor[0]<cx+w//2 and cy-h//2<cursor[1]<cy+h//2:
                colorR =0, 255, 0
                cx, cy = cursor
            else:
                colorR = 0,0,255

    cv2.rectangle(img, (cx-w//2,cy-h//2), (cx+w//2,cy+h//2), colorR,cv2.FILLED)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

希望本文对大家有所帮助,有问题的同学可以留言哦,喜欢的同学可以关注一下。

Guess you like

Origin blog.csdn.net/hyayq8124/article/details/122465633