forked from nishtha981/hand-gesture-control
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtempCodeRunnerFile.python
94 lines (67 loc) · 3.18 KB
/
tempCodeRunnerFile.python
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
import numpy as np
import mediapipe as mp
import cv2
import time
import threading
import hand_position
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
cap = cv2.VideoCapture(0)
def are_hands_crossed(hand_landmarks, width):
if len(hand_landmarks) < 2:
return False
left_wrist_x = hand_landmarks[0].landmark[mp_hands.HandLandmark.WRIST].x * width
right_wrist_x = hand_landmarks[1].landmark[mp_hands.HandLandmark.WRIST].x * width
return left_wrist_x > right_wrist_x
def hand_tracking():
with mp_hands.Hands(
model_complexity=1,
min_detection_confidence=0.4,
min_tracking_confidence=0.4) as hands:
hands_crossed = False
while cap.isOpened():
success, image = cap.read()
h, w, c = image.shape
start = time.perf_counter()
image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
image.flags.writeable = False
results = hands.process(image)
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
if hand_landmarks.landmark:
mp_drawing.draw_landmarks(image, hand_landmarks, mp_hands.HAND_CONNECTIONS,
mp_drawing_styles.get_default_hand_landmarks_style(),
mp_drawing_styles.get_default_hand_connections_style())
if are_hands_crossed(results.multi_hand_landmarks, w):
if not hands_crossed:
hands_crossed = True
print("Hands crossed. Stopping the code.")
break
else:
hands_crossed = False
index_finger_tip = hand_landmarks.landmark[0]
index_finger_tip_x = index_finger_tip.x * w
index_finger_tip_y = index_finger_tip.y * h
if index_finger_tip_x > w/2:
cv2.putText(image, "Right", (500, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 250))
elif index_finger_tip_x < w/2:
cv2.putText(image, "Left", (500, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (250, 0))
cv2.line(image, (int(w/2), 0), (int(w/2), h), (0, 255, 0), 2)
end = time.perf_counter()
totalTime = end - start
fps = 1/totalTime
cv2.putText(image, f'FPS: {int(fps)}', (20, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 0), 2)
cv2.imshow('MediaPipe Hands', image)
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
key_stimulation_thread = threading.Thread(target=hand_position.stimulate_keys)
key_stimulation_thread.start()
hand_tracking()