OpenCV利用手勢識別實現(xiàn)虛擬拖放效果
本文將實現(xiàn)一些通過手拖放一些框,我們可以使用這個技術實現(xiàn)一些游戲,控制機械臂等很多有趣的事情。
第一步
通過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)
第三步
第三步首先創(chuàng)建一個方塊
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利用手勢識別實現(xiàn)虛擬拖放效果的文章就介紹到這了,更多相關OpenCV手勢識別 虛擬拖放內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳盡講述用Python的Django框架測試驅動開發(fā)的教程
這篇文章主要介紹了詳盡講述用Python的Django框架測試驅動開發(fā)的教程,主要使用TDD工具,全文介紹非常詳細,需要的朋友可以參考下2015-04-04VSCode中Python環(huán)境配置、創(chuàng)建虛擬環(huán)境及pip的一些常用命令
這篇文章主要給大家介紹了關于VSCode中Python環(huán)境配置、創(chuàng)建虛擬環(huán)境及pip的一些常用命令,Python環(huán)境的創(chuàng)建是在VSCode中很常見的一個需求,特別是當我們需要開發(fā)或者調試多個Python項目時,使用虛擬環(huán)境是一種好的方式,需要的朋友可以參考下2023-10-10Python實現(xiàn)的井字棋(Tic Tac Toe)游戲示例
這篇文章主要介紹了Python實現(xiàn)的井字棋(Tic Tac Toe)游戲,結合實例形式分析了井字棋的原理及Python相關實現(xiàn)技巧,需要的朋友可以參考下2018-01-01OpenCV-Python實現(xiàn)圖像梯度與Sobel濾波器
在實際應用中我們只需要將圖像矩陣與Sobel濾波器卷積就可以得到圖像的梯度矩陣了。具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06