Repository navigation
Expand file tree
/
Copy pathgesture_control.py
More file actions
96 lines (73 loc) · 2.72 KB
/
Copy pathgesture_control.py
File metadata and controls
96 lines (73 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import cv2
import mediapipe as mp
import pyautogui
import time
import numpy as np
pyautogui.FAILSAFE = False
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
hands = mp_hands.Hands(max_num_hands=1, min_detection_confidence=0.6)
cap = cv2.VideoCapture(1)
start_pos = None
start_time = 0
cooldown = 0.4 # seconds
last_action_time = time.time()
SWIPE_DIST_THRESHOLD = 35 # lowered threshold
SWIPE_TIME_MAX = 0.7 # easier swipe timing
def detect_gesture(start, end, elapsed):
dx = end[0] - start[0]
dy = end[1] - start[1]
dist = np.sqrt(dx*dx + dy*dy)
if dist < SWIPE_DIST_THRESHOLD:
return None
if elapsed > SWIPE_TIME_MAX:
return None
if abs(dx) > abs(dy):
return "right" if dx > 0 else "left"
else:
return "down" if dy > 0 else "up"
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 1)
h, w, c = frame.shape
result = hands.process(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
gesture = "None"
if result.multi_hand_landmarks:
hand = result.multi_hand_landmarks[0]
mp_drawing.draw_landmarks(frame, hand, mp_hands.HAND_CONNECTIONS)
palm = np.mean([(lm.x * w, lm.y * h) for lm in hand.landmark], axis=0)
cv2.circle(frame, (int(palm[0]), int(palm[1])), 8, (255, 0, 0), -1)
fingers_open = sum([1 if hand.landmark[i].y < hand.landmark[i-2].y else 0
for i in [8, 12, 16, 20]])
currently_open = fingers_open >= 3
if currently_open:
if start_pos is None:
start_pos = palm
start_time = time.time()
else:
cv2.circle(frame, (int(start_pos[0]), int(start_pos[1])), 10, (0,255,0), -1)
elapsed = time.time() - start_time
detected = detect_gesture(start_pos, palm, elapsed)
if detected:
if time.time() - last_action_time >= cooldown:
gesture = detected
last_action_time = time.time()
start_pos = None
else:
start_pos = None
# ✅ Trigger Game Actions
if gesture == "up":
pyautogui.press("up")
elif gesture == "down":
pyautogui.press("down")
elif gesture == "left":
pyautogui.press("left")
elif gesture == "right":
pyautogui.press("right")
cv2.putText(frame, f"Gesture: {gesture}", (10, 45),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 3)
cv2.imshow("Gesture Control Debug", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()