这篇文章主要介绍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)
以上是“OpenCV如何利用手势识别实现虚拟拖放效果”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注天达云行业资讯频道!