-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHand_ctrl.py
More file actions
346 lines (284 loc) · 13.4 KB
/
Hand_ctrl.py
File metadata and controls
346 lines (284 loc) · 13.4 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import cv2
import mediapipe as mp
import rsautogui
import math
from enum import IntEnum
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
from google.protobuf.json_format import MessageToDict
import screen_brightness_control as sbc
rsautogui.FAILSAFE = False
mp_draw = mp.solutions.drawing_utils
mp_hand = mp.solutions.hands
class GestureType(IntEnum):
CLOSED = 0
LITTLE = 1
FOURTH = 2
MIDDLE = 4
LAST_THREE = 7
POINTER = 8
FIRST_TWO = 12
LAST_FOUR = 15
THUMB = 16
OPEN = 31
VICTORY = 33
TWO_CLOSED = 34
PINCH_MAIN = 35
PINCH_SECONDARY = 36
class HandType(IntEnum):
SECONDARY = 0
PRIMARY = 1
class GestureRecognizer:
def __init__(self, hand_type):
self.digit = 0
self.initial_gesture = GestureType.OPEN
self.last_gesture = GestureType.OPEN
self.frame_count = 0
self.hand_data = None
self.hand_type = hand_type
def update_hand_data(self, hand_data):
self.hand_data = hand_data
def calculate_distance(self, point_a, point_b):
return math.sqrt(
(self.hand_data.landmark[point_a].x - self.hand_data.landmark[point_b].x)**2 +
(self.hand_data.landmark[point_a].y - self.hand_data.landmark[point_b].y)**2
)
def calculate_signed_distance(self, point_a, point_b):
sign = 1 if self.hand_data.landmark[point_a].y < self.hand_data.landmark[point_b].y else -1
return sign * self.calculate_distance([point_a, point_b])
def calculate_depth(self, point_a, point_b):
return abs(self.hand_data.landmark[point_a].z - self.hand_data.landmark[point_b].z)
def set_digit_state(self):
if self.hand_data is None:
return
finger_points = [[8,5,0], [12,9,0], [16,13,0], [20,17,0]]
self.digit = 0
for idx, point in enumerate(finger_points):
dist_tip_mid = self.calculate_signed_distance(point[0], point[1])
dist_mid_base = self.calculate_signed_distance(point[1], point[2])
ratio = round(dist_tip_mid / (dist_mid_base or 0.01), 1)
self.digit = self.digit << 1
if ratio > 0.5:
self.digit = self.digit | 1
def recognize_gesture(self):
if self.hand_data is None:
return GestureType.OPEN
current_gesture = GestureType.OPEN
if self.digit in [GestureType.LAST_THREE, GestureType.LAST_FOUR] and self.calculate_distance([8,4]) < 0.05:
current_gesture = GestureType.PINCH_SECONDARY if self.hand_type == HandType.SECONDARY else GestureType.PINCH_MAIN
elif GestureType.FIRST_TWO == self.digit:
dist_fingertips = self.calculate_distance([8,12])
dist_knuckles = self.calculate_distance([5,9])
if dist_fingertips / dist_knuckles > 1.7:
current_gesture = GestureType.VICTORY
elif self.calculate_depth([8,12]) < 0.1:
current_gesture = GestureType.TWO_CLOSED
else:
current_gesture = GestureType.MIDDLE
else:
current_gesture = self.digit
if current_gesture == self.last_gesture:
self.frame_count += 1
else:
self.frame_count = 0
self.last_gesture = current_gesture
if self.frame_count > 4:
self.initial_gesture = current_gesture
return self.initial_gesture
class InputController:
prev_x, prev_y = 0, 0
is_v_gesture = False
is_fist = False
is_pinch_main = False
is_pinch_secondary = False
pinch_start_x, pinch_start_y = None, None
pinch_direction = None
prev_pinch_level = 0
pinch_level = 0
frame_count = 0
prev_hand_position = None
pinch_threshold = 0.3
@staticmethod
def get_pinch_level_y(hand_data):
return round((InputController.pinch_start_y - hand_data.landmark[8].y) * 10, 1)
@staticmethod
def get_pinch_level_x(hand_data):
return round((hand_data.landmark[8].x - InputController.pinch_start_x) * 10, 1)
@staticmethod
def adjust_brightness():
current_brightness = sbc.get_brightness(display=0) / 100.0
new_brightness = max(0.0, min(1.0, current_brightness + InputController.pinch_level / 50.0))
sbc.fade_brightness(int(100 * new_brightness), start=sbc.get_brightness(display=0))
@staticmethod
def adjust_volume():
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
current_volume = volume.GetMasterVolumeLevelScalar()
new_volume = max(0.0, min(1.0, current_volume + InputController.pinch_level / 50.0))
volume.SetMasterVolumeLevelScalar(new_volume, None)
@staticmethod
def scroll_vertical():
rsautogui.scroll(120 if InputController.pinch_level > 0.0 else -120)
@staticmethod
def scroll_horizontal():
rsautogui.keyDown('shift')
rsautogui.keyDown('ctrl')
rsautogui.scroll(-120 if InputController.pinch_level > 0.0 else 120)
rsautogui.keyUp('ctrl')
rsautogui.keyUp('shift')
@staticmethod
def get_cursor_position(hand_data):
point = 9
screen_width, screen_height = rsautogui.size()
x = int(hand_data.landmark[point].x * screen_width)
y = int(hand_data.landmark[point].y * screen_height)
if InputController.prev_hand_position is None:
InputController.prev_hand_position = x, y
delta_x = x - InputController.prev_hand_position[0]
delta_y = y - InputController.prev_hand_position[1]
distance_sq = delta_x**2 + delta_y**2
smoothing_factor = 0 if distance_sq <= 25 else 0.07 * (distance_sq ** 0.5) if distance_sq <= 900 else 2.1
current_x, current_y = rsautogui.position()
new_x = current_x + delta_x * smoothing_factor
new_y = current_y + delta_y * smoothing_factor
InputController.prev_hand_position = [x, y]
return (new_x, new_y)
@staticmethod
def initialize_pinch(hand_data):
InputController.pinch_start_x = hand_data.landmark[8].x
InputController.pinch_start_y = hand_data.landmark[8].y
InputController.pinch_level = 0
InputController.prev_pinch_level = 0
InputController.frame_count = 0
@staticmethod
def handle_pinch(hand_data, horizontal_action, vertical_action):
if InputController.frame_count == 5:
InputController.frame_count = 0
InputController.pinch_level = InputController.prev_pinch_level
if InputController.pinch_direction:
horizontal_action()
else:
vertical_action()
level_x = InputController.get_pinch_level_x(hand_data)
level_y = InputController.get_pinch_level_y(hand_data)
if abs(level_y) > abs(level_x) and abs(level_y) > InputController.pinch_threshold:
InputController.pinch_direction = False
if abs(InputController.prev_pinch_level - level_y) < InputController.pinch_threshold:
InputController.frame_count += 1
else:
InputController.prev_pinch_level = level_y
InputController.frame_count = 0
elif abs(level_x) > InputController.pinch_threshold:
InputController.pinch_direction = True
if abs(InputController.prev_pinch_level - level_x) < InputController.pinch_threshold:
InputController.frame_count += 1
else:
InputController.prev_pinch_level = level_x
InputController.frame_count = 0
@staticmethod
def process_gesture(gesture, hand_data):
cursor_x, cursor_y = None, None
if gesture != GestureType.OPEN:
cursor_x, cursor_y = InputController.get_cursor_position(hand_data)
if gesture != GestureType.CLOSED and InputController.is_fist:
InputController.is_fist = False
rsautogui.mouseUp(button="left")
if gesture != GestureType.PINCH_MAIN and InputController.is_pinch_main:
InputController.is_pinch_main = False
if gesture != GestureType.PINCH_SECONDARY and InputController.is_pinch_secondary:
InputController.is_pinch_secondary = False
if gesture == GestureType.VICTORY:
InputController.is_v_gesture = True
rsautogui.moveTo(cursor_x, cursor_y, duration=0.1)
elif gesture == GestureType.CLOSED:
if not InputController.is_fist:
InputController.is_fist = True
rsautogui.mouseDown(button="left")
rsautogui.moveTo(cursor_x, cursor_y, duration=0.1)
elif gesture == GestureType.MIDDLE and InputController.is_v_gesture:
rsautogui.click()
InputController.is_v_gesture = False
elif gesture == GestureType.POINTER and InputController.is_v_gesture:
rsautogui.click(button='right')
InputController.is_v_gesture = False
elif gesture == GestureType.TWO_CLOSED and InputController.is_v_gesture:
rsautogui.doubleClick()
InputController.is_v_gesture = False
elif gesture == GestureType.PINCH_SECONDARY:
if not InputController.is_pinch_secondary:
InputController.initialize_pinch(hand_data)
InputController.is_pinch_secondary = True
InputController.handle_pinch(hand_data, InputController.scroll_horizontal, InputController.scroll_vertical)
elif gesture == GestureType.PINCH_MAIN:
if not InputController.is_pinch_main:
InputController.initialize_pinch(hand_data)
InputController.is_pinch_main = True
InputController.handle_pinch(hand_data, InputController.adjust_brightness, InputController.adjust_volume)
class GestureControlMain:
is_active = 0
video_capture = None
FRAME_HEIGHT = None
FRAME_WIDTH = None
primary_hand = None
secondary_hand = None
is_right_dominant = True
def __init__(self):
GestureControlMain.is_active = 1
GestureControlMain.video_capture = cv2.VideoCapture(0)
GestureControlMain.FRAME_HEIGHT = GestureControlMain.video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
GestureControlMain.FRAME_WIDTH = GestureControlMain.video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)
@staticmethod
def categorize_hands(results):
left, right = None, None
try:
for idx, hand_handedness in enumerate(results.multi_handedness):
handedness_dict = MessageToDict(hand_handedness)
if handedness_dict['classification'][0]['label'] == 'Right':
right = results.multi_hand_landmarks[idx]
else:
left = results.multi_hand_landmarks[idx]
except:
pass
GestureControlMain.primary_hand = right if GestureControlMain.is_right_dominant else left
GestureControlMain.secondary_hand = left if GestureControlMain.is_right_dominant else right
def run(self):
primary_recognizer = GestureRecognizer(HandType.PRIMARY)
secondary_recognizer = GestureRecognizer(HandType.SECONDARY)
with mp_hand.Hands(max_num_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands:
while GestureControlMain.video_capture.isOpened() and GestureControlMain.is_active:
success, frame = GestureControlMain.video_capture.read()
if not success:
print("Failed to capture frame.")
continue
frame = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
frame.flags.writeable = False
results = hands.process(frame)
frame.flags.writeable = True
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
if results.multi_hand_landmarks:
GestureControlMain.categorize_hands(results)
primary_recognizer.update_hand_data(GestureControlMain.primary_hand)
secondary_recognizer.update_hand_data(GestureControlMain.secondary_hand)
primary_recognizer.set_digit_state()
secondary_recognizer.set_digit_state()
gesture = secondary_recognizer.recognize_gesture()
if gesture == GestureType.PINCH_SECONDARY:
InputController.process_gesture(gesture, secondary_recognizer.hand_data)
else:
gesture = primary_recognizer.recognize_gesture()
InputController.process_gesture(gesture, primary_recognizer.hand_data)
for hand_landmarks in results.multi_hand_landmarks:
mp_draw.draw_landmarks(frame, hand_landmarks, mp_hand.HAND_CONNECTIONS)
else:
InputController.prev_hand_position = None
cv2.imshow('Gesture Control Interface', frame)
if cv2.waitKey(5) & 0xFF == 13: # Enter key
break
GestureControlMain.video_capture.release()
cv2.destroyAllWindows()
# Main execution
if __name__ == "__main__":
gesture_control = GestureControlMain()
gesture_control.run()