Skip to content

Commit 8edd494

Browse files
Create 02. AI_Virtual_Mouse_Project.py
1 parent 6472835 commit 8edd494

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import cv2
2+
import numpy as np
3+
import HandTrackingModule as htm
4+
import time
5+
import autopy
6+
##########################
7+
wCam, hCam = 640, 480
8+
frameR = 100 # Frame Reduction
9+
smoothening = 7
10+
#########################
11+
12+
pTime = 0
13+
plocX, plocY = 0, 0
14+
clocX, clocY = 0, 0
15+
16+
cap = cv2.VideoCapture(1)
17+
cap.set(3, wCam)
18+
cap.set(4, hCam)
19+
detector = htm.handDetector(maxHands=1)
20+
wScr, hScr = autopy.screen.size()
21+
# print(wScr, hScr)
22+
23+
while True:
24+
# 1. Find hand Landmarks
25+
success, img = cap.read()
26+
img = detector.findHands(img)
27+
lmList, bbox = detector.findPosition(img)
28+
# 2. Get the tip of the index and middle fingers
29+
if len(lmList) != 0:
30+
x1, y1 = lmList[8][1:]
31+
x2, y2 = lmList[12][1:]
32+
# print(x1, y1, x2, y2)
33+
34+
# 3. Check which fingers are up
35+
fingers = detector.fingersUp()
36+
# print(fingers)
37+
cv2.rectangle(img, (frameR, frameR), (wCamframeR, hCamframeR),
38+
(255, 0, 255), 2)
39+
# 4. Only Index Finger : Moving Mode
40+
if fingers[1] == 1 and fingers[2] == 0:
41+
# 5. Convert Coordinates
42+
x3 = np.interp(x1, (frameR, wCamframeR), (0, wScr))
43+
y3 = np.interp(y1, (frameR, hCamframeR), (0, hScr))
44+
# 6. Smoothen Values
45+
clocX = plocX + (x3plocX) / smoothening
46+
clocY = plocY + (y3plocY) / smoothening
47+
48+
# 7. Move Mouse
49+
autopy.mouse.move(wScrclocX, clocY)
50+
cv2.circle(img, (x1, y1), 15, (255, 0, 255), cv2.FILLED)
51+
plocX, plocY = clocX, clocY
52+
53+
# 8. Both Index and middle fingers are up : Clicking Mode
54+
if fingers[1] == 1 and fingers[2] == 1:
55+
# 9. Find distance between fingers
56+
length, img, lineInfo = detector.findDistance(8, 12, img)
57+
print(length)
58+
# 10. Click mouse if distance short
59+
if length < 40:
60+
cv2.circle(img, (lineInfo[4], lineInfo[5]),
61+
15, (0, 255, 0), cv2.FILLED)
62+
autopy.mouse.click()
63+
64+
# 11. Frame Rate
65+
cTime = time.time()
66+
fps = 1 / (cTimepTime)
67+
pTime = cTime
68+
cv2.putText(img, str(int(fps)), (20, 50), cv2.FONT_HERSHEY_PLAIN, 3,
69+
(255, 0, 0), 3)
70+
# 12. Display
71+
cv2.imshow(“Image”, img)
72+
cv2.waitKey(1)

0 commit comments

Comments
 (0)