-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandFaceTracker.py
More file actions
2866 lines (2330 loc) · 112 KB
/
HandFaceTracker.py
File metadata and controls
2866 lines (2330 loc) · 112 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import cv2
import numpy as np
import mediapipe as mp
import math
import json
import os
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
from obswebsocket import obsws, requests
OBS_HOST = "localhost"
OBS_PORT = 4455
OBS_PASSWORD = "PeppaPig53**"
# Try to import landmark groups from the external file
try:
from landmark_groups import feature_groups, face_connections
LANDMARK_GROUPS_AVAILABLE = True
print("✅ Landmark groups loaded successfully")
except ImportError:
LANDMARK_GROUPS_AVAILABLE = False
print("❌ landmark_groups.py not found - face connections will not be drawn")
# ============================================================================
# GESTURE MAPPING SYSTEM
# ============================================================================
class GestureMapping:
"""Maps gestures to actions, separate from radial menu"""
def __init__(self, tracker):
self.tracker = tracker
self.mappings = {} # gesture_name -> action_function
self.config_file = "gesture_mappings.json"
# Initialize with default gesture mappings (but delay action functions)
self._init_default_mappings()
self.load_config()
# Create a reverse lookup for display purposes
self.action_to_gestures = {}
self._update_reverse_lookup()
def _init_default_mappings(self):
"""Initialize default gesture to action mappings (without circular references)"""
# We'll use placeholder functions that will be replaced later
self.mappings = {
'Closed_Fist': self._placeholder_action,
'Open_Palm': self._placeholder_action,
'Pointing_Up': self._placeholder_action,
'Thumb_Down': self._placeholder_action,
'Thumb_Up': self._placeholder_action,
'Victory': self._placeholder_action,
'ILoveYou': self._placeholder_action,
}
def _placeholder_action(self):
"""Placeholder that will be replaced with real actions"""
print(" ⚠️ Gesture action not initialized yet")
def update_actions(self, gesture_controller):
"""Update the action functions after gesture_controller is created"""
self.mappings = {
'Closed_Fist': lambda: self.tracker.toggle('show_red', 'RED channel'),
'Open_Palm': lambda: self.tracker.toggle('show_green', 'GREEN channel'),
'Pointing_Up': lambda: self.tracker.toggle('show_blue', 'BLUE channel'),
'Thumb_Down': gesture_controller.action1,
'Thumb_Up': gesture_controller.action2,
'Victory': gesture_controller.take_screenshot,
'ILoveYou': lambda: self.tracker.toggle('show_text', 'Text overlay'),
}
# Reload config to override with saved mappings
self.load_config()
def get_available_gestures(self):
"""Return list of all gesture names that can be mapped"""
return [
'Closed_Fist',
'Open_Palm',
'Pointing_Up',
'Thumb_Down',
'Thumb_Up',
'Victory',
'ILoveYou',
'None' # Empty/placeholder
]
def get_available_actions(self):
"""Return list of all available actions that gestures can be mapped to"""
return [
("toggle_red", "Toggle Red", "🔴", lambda: self.tracker.toggle('show_red', 'RED channel')),
("toggle_green", "Toggle Green", "🟢", lambda: self.tracker.toggle('show_green', 'GREEN channel')),
("toggle_blue", "Toggle Blue", "🔵", lambda: self.tracker.toggle('show_blue', 'BLUE channel')),
("toggle_faces", "Toggle Faces", "😀", lambda: self.tracker.toggle('show_faces', 'Face tracking')),
("toggle_hands", "Toggle Hands", "✋", lambda: self.tracker.toggle('show_hands', 'Hand tracking')),
("screenshot", "Take Screenshot", "📸", self._get_screenshot_action()),
("toggle_text", "Toggle Text", "📝", lambda: self.tracker.toggle('show_text', 'Text overlay')),
("gesture_menu", "Open Gesture Menu", "⚙️", self._get_gesture_menu_action()),
("empty", "No Action", "○", None),
]
def _get_screenshot_action(self):
"""Get screenshot action (handles circular reference)"""
if hasattr(self.tracker, 'gesture_controller'):
return self.tracker.gesture_controller.take_screenshot
return lambda: print(" 📸 Screenshot (gesture controller not ready)")
def _get_gesture_menu_action(self):
"""Get gesture menu action (handles circular reference)"""
if hasattr(self.tracker, 'open_gesture_mapping_menu'):
return self.tracker.open_gesture_mapping_menu
return lambda: print(" ⚙️ Gesture menu (tracker not ready)")
def map_gesture(self, gesture_name, action_id):
"""Map a gesture to an action"""
actions_list = self.get_available_actions()
action_data = None
# Find the action
for action in actions_list: # Changed from actions
if action[0] == action_id:
action_data = action
break
if action_data:
self.mappings[gesture_name] = action_data[3] # The lambda function
self.save_config()
self._update_reverse_lookup()
return True
return False
def get_gesture_action(self, gesture_name):
"""Get the action function for a gesture"""
return self.mappings.get(gesture_name)
def execute_gesture(self, gesture_name):
"""Execute the action mapped to a gesture"""
action = self.get_gesture_action(gesture_name)
if action:
action()
return True
return False
def _update_reverse_lookup(self):
"""Update the reverse lookup dictionary for display"""
self.action_to_gestures = {}
actions_list = self.get_available_actions()
for gesture, gesture_action_func in self.mappings.items():
# Find which action this function corresponds to
for action_id, name, icon, action_func in actions_list:
if action_func == gesture_action_func:
if name not in self.action_to_gestures:
self.action_to_gestures[name] = []
self.action_to_gestures[name].append(gesture)
break
def save_config(self):
"""Save gesture mappings to file"""
# Convert functions to their string IDs
config = {"mappings": {}, "version": "1.0"}
for gesture, action_func in self.mappings.items():
# Find the action ID for this function
for action_id, name, icon, func in self.get_available_actions():
if func == action_func:
config["mappings"][gesture] = action_id
break
try:
with open(self.config_file, 'w') as f:
json.dump(config, f, indent=2)
except Exception as e:
print(f"❌ Failed to save gesture mappings: {e}")
def load_config(self):
"""Load gesture mappings from file"""
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r') as f:
config = json.load(f)
# Load saved mappings
saved_mappings = config.get("mappings", {})
for gesture, action_id in saved_mappings.items():
# Don't use map_gesture here to avoid recursion
# Just update the mapping directly
for action in self.get_available_actions():
if action[0] == action_id:
self.mappings[gesture] = action[3]
break
print(f"✅ Loaded gesture mappings from {self.config_file}")
self._update_reverse_lookup()
except Exception as e:
print(f"❌ Failed to load gesture mappings: {e}")
# Fall back to defaults (will be updated later)
else:
print(f"⚠️ No gesture mappings found. Using default mappings.")
# ============================================================================
# SCROLLABLE DATA DISPLAY WINDOWS
# ============================================================================
class ScrollableDataWindow:
"""Base class for scrollable data display windows"""
def __init__(self, window_name, window_width=400, window_height=600):
self.window_name = window_name
self.window_width = window_width
self.window_height = window_height
# Scroll settings
self.scroll_offset = 0
self.max_scroll = 100
self.row_height = 25
self.col_width = 120
# Colors
self.bg_color = (30, 30, 40)
self.header_color = (60, 60, 100)
self.data_color = (200, 200, 220)
self.grid_color = (60, 60, 70)
self.scrollbar_color = (100, 100, 150)
self.scrollbar_active_color = (150, 150, 200)
# Create the window
cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
cv2.resizeWindow(self.window_name, self.window_width, self.window_height)
# Display data
self.display_data = []
self.column_headers = []
def update_data(self, data):
"""Update the data to display"""
self.display_data = data
self.calculate_scroll_limit()
def calculate_scroll_limit(self):
"""Calculate maximum scroll based on data rows"""
visible_rows = (self.window_height - 100) // self.row_height
total_rows = len(self.display_data)
self.max_scroll = max(0, total_rows - visible_rows)
self.scroll_offset = min(self.scroll_offset, self.max_scroll)
def handle_scroll(self, delta):
"""Handle scroll wheel input"""
self.scroll_offset = max(0, min(self.max_scroll, self.scroll_offset + delta))
def draw_scrollbar(self, canvas):
"""Draw scrollbar on the right side"""
if self.max_scroll <= 0:
return
scrollbar_width = 15
scrollbar_x = self.window_width - scrollbar_width - 5
# Calculate scrollbar thumb position and size
visible_ratio = min(1.0, (self.window_height - 100) / (len(self.display_data) * self.row_height))
thumb_height = max(20, int((self.window_height - 100) * visible_ratio))
if self.max_scroll > 0:
thumb_position = (self.scroll_offset / self.max_scroll) * (self.window_height - 100 - thumb_height)
else:
thumb_position = 0
# Draw scrollbar track
cv2.rectangle(canvas, (scrollbar_x, 50),
(scrollbar_x + scrollbar_width, self.window_height - 50),
self.scrollbar_color, -1)
# Draw scrollbar thumb
thumb_y = 50 + int(thumb_position)
cv2.rectangle(canvas, (scrollbar_x, thumb_y),
(scrollbar_x + scrollbar_width, thumb_y + thumb_height),
self.scrollbar_active_color, -1)
# Draw scroll indicator
if self.max_scroll > 0:
page_info = f"{self.scroll_offset+1}-{min(self.scroll_offset + (self.window_height-100)//self.row_height, len(self.display_data))}/{len(self.display_data)}"
cv2.putText(canvas, page_info, (scrollbar_x - 100, self.window_height - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (150, 150, 150), 1, cv2.LINE_AA)
def draw_table(self, canvas):
"""Draw the data table with current scroll offset"""
# Draw title
cv2.putText(canvas, self.window_name, (20, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2, cv2.LINE_AA)
# Draw column headers
y_pos = 60
for i, header in enumerate(self.column_headers):
x_pos = 20 + i * self.col_width
cv2.rectangle(canvas, (x_pos - 5, y_pos - 20),
(x_pos + self.col_width - 5, y_pos + 5), self.header_color, -1)
cv2.putText(canvas, header, (x_pos, y_pos),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
y_pos += 10
# Draw grid lines for headers
for i in range(len(self.column_headers) + 1):
x_line = 15 + i * self.col_width
cv2.line(canvas, (x_line, 40), (x_line, y_pos), self.grid_color, 1)
# Draw data rows
start_row = self.scroll_offset
visible_rows = (self.window_height - y_pos - 30) // self.row_height
for row_idx in range(start_row, min(start_row + visible_rows, len(self.display_data))):
row_data = self.display_data[row_idx]
row_y = y_pos + (row_idx - start_row) * self.row_height
# Alternate row colors
row_color = self.data_color if row_idx % 2 == 0 else (180, 180, 200)
for col_idx, cell_value in enumerate(row_data):
x_pos = 20 + col_idx * self.col_width
cv2.putText(canvas, str(cell_value), (x_pos, row_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, row_color, 1, cv2.LINE_AA)
# Draw horizontal grid line
cv2.line(canvas, (15, row_y + 5),
(15 + len(self.column_headers) * self.col_width, row_y + 5),
self.grid_color, 1)
# Draw vertical grid lines for data
for i in range(len(self.column_headers) + 1):
x_line = 15 + i * self.col_width
cv2.line(canvas, (x_line, y_pos),
(x_line, y_pos + visible_rows * self.row_height), self.grid_color, 1)
# Draw scrollbar
self.draw_scrollbar(canvas)
# Draw instructions
instructions = "Mouse wheel: Scroll | R: Reset scroll | ESC: Close window"
cv2.putText(canvas, instructions, (20, self.window_height - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (150, 150, 150), 1, cv2.LINE_AA)
def update_window(self):
"""Update and redraw the window"""
canvas = np.full((self.window_height, self.window_width, 3), self.bg_color, dtype=np.uint8)
self.draw_table(canvas)
cv2.imshow(self.window_name, canvas)
def close(self):
"""Close the window"""
cv2.destroyWindow(self.window_name)
class FaceDataWindow(ScrollableDataWindow):
"""Window for displaying face landmark data"""
def __init__(self):
super().__init__("Face Landmarks", window_width=600, window_height=700)
self.column_headers = ["ID", "Name", "X", "Y", "Z", "Visibility"]
# Face landmark names (MediaPipe has 478 face landmarks)
self.face_names = [
"Lips Upper Outer", "Lips Upper Inner", "Lips Lower Outer", "Lips Lower Inner",
"Nose Tip", "Nose Bridge", "Left Eye Outer", "Left Eye Inner",
"Right Eye Outer", "Right Eye Inner", "Left Ear", "Right Ear",
"Mouth Left Corner", "Mouth Right Corner", "Forehead", "Chin",
"Left Cheek", "Right Cheek", "Left Eyebrow Outer", "Left Eyebrow Inner",
"Right Eyebrow Outer", "Right Eyebrow Inner"
]
def update_from_landmarks(self, face_landmarks_list):
"""Convert face landmarks to display data"""
if not face_landmarks_list:
self.update_data([])
return
display_rows = []
# Face has 468 landmarks (or 478 with refine_landmarks=True)
for i in range(min(len(face_landmarks_list), 468)):
landmark = face_landmarks_list[i]
# FIXED: Check both that landmark exists AND visibility is not None
if landmark is None:
row = [str(i), f"Point_{i}", "N/A", "N/A", "N/A", "N/A"]
else:
name = self.face_names[i] if i < len(self.face_names) else f"Point_{i}"
# FIXED: Check if visibility exists AND is not None
if hasattr(landmark, 'visibility') and landmark.visibility is not None:
visibility = f"{landmark.visibility:.4f}"
else:
visibility = "N/A"
row = [
str(i),
name,
f"{landmark.x:.4f}",
f"{landmark.y:.4f}",
f"{landmark.z:.4f}",
visibility # Now safe
]
display_rows.append(row)
self.update_data(display_rows)
class HandDataWindow(ScrollableDataWindow):
"""Window for displaying hand landmark data"""
def __init__(self):
super().__init__("Hand Landmarks", window_width=700, window_height=600)
self.column_headers = ["ID", "Name", "X", "Y", "Z", "Dist Wrist", "Angle"]
# Hand landmark names (21 points)
self.hand_names = [
"WRIST", "THUMB_CMC", "THUMB_MCP", "THUMB_IP", "THUMB_TIP",
"INDEX_MCP", "INDEX_PIP", "INDEX_DIP", "INDEX_TIP",
"MIDDLE_MCP", "MIDDLE_PIP", "MIDDLE_DIP", "MIDDLE_TIP",
"RING_MCP", "RING_PIP", "RING_DIP", "RING_TIP",
"PINKY_MCP", "PINKY_PIP", "PINKY_DIP", "PINKY_TIP"
]
def update_from_landmarks(self, hand_landmarks, gesture=None):
"""Convert hand landmarks to display data"""
if not hand_landmarks or len(hand_landmarks) < 21:
self.update_data([])
return
display_rows = []
wrist = hand_landmarks[0]
for i in range(len(hand_landmarks)):
landmark = hand_landmarks[i]
name = self.hand_names[i] if i < len(self.hand_names) else f"Point_{i}"
# Calculate distance from wrist
dist_x = landmark.x - wrist.x
dist_y = landmark.y - wrist.y
distance = math.sqrt(dist_x**2 + dist_y**2)
# Calculate angle from wrist (in degrees)
angle = math.degrees(math.atan2(dist_y, dist_x)) if i > 0 else 0
angle = (angle + 360) % 360 # Normalize to 0-360
# Format the row
row = [
str(i),
name,
f"{landmark.x:.4f}",
f"{landmark.y:.4f}",
f"{landmark.z:.4f}",
f"{distance:.4f}",
f"{angle:.1f}°"
]
display_rows.append(row)
# Add gesture info as first row if available
if gesture:
display_rows.insert(0, ["GESTURE", gesture, "", "", "", "", ""])
self.update_data(display_rows)
class MultiHandDataWindow:
"""Window for displaying multiple hands data with touch detection"""
def __init__(self):
self.window_name = "Multi-Hand Data"
self.window_width = 800
self.window_height = 500
# Colors
self.bg_color = (30, 30, 40)
self.left_hand_color = (100, 200, 255) # Cyan for left
self.right_hand_color = (255, 150, 100) # Orange for right
self.text_color = (220, 220, 220)
self.touch_color = (100, 255, 100) # Green for touch
self.no_touch_color = (255, 100, 100) # Red for no touch
# Touch detection settings
self.touch_threshold = 0.02
self.finger_tip_indices = [4, 8, 12, 16, 20]
self.finger_names = {
4: "Thumb", 8: "Index", 12: "Middle", 16: "Ring", 20: "Pinky"
}
# Touch tracking with visual effects
self.current_touches = [] # List of current active touches
self.touch_history = [] # History for visual effects
self.last_touch_print = 0
self.cooldown_duration = 6.0 # Seconds before points can touch again
# Create the window
cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
cv2.resizeWindow(self.window_name, self.window_width, self.window_height)
def calculate_distance(self, point1, point2):
"""Calculate 3D Euclidean distance between two landmarks"""
dx = point1.x - point2.x
dy = point1.y - point2.y
dz = point1.z - point2.z
return math.sqrt(dx*dx + dy*dy + dz*dz)
def detect_touches(self, hand_results):
"""Detect touches between finger tips of different hands"""
import time
current_time = time.time()
# Remove old touches from history
self.touch_history = [t for t in self.touch_history
if current_time - t['touch_time'] < self.cooldown_duration]
# Get cooldown points (points that recently touched)
cooldown_points = set()
for touch in self.touch_history:
key1 = f"{touch['hand1']}_{touch['finger1']}"
key2 = f"{touch['hand2']}_{touch['finger2']}"
cooldown_points.add(key1)
cooldown_points.add(key2)
self.current_touches = []
if not hand_results or not hand_results.hand_landmarks:
return
# Need at least 2 hands for inter-hand touches
if len(hand_results.hand_landmarks) < 2:
return
# Get hand labels (left/right)
hand_labels = []
for i in range(len(hand_results.hand_landmarks)):
label = "Unknown"
if hand_results.handedness and i < len(hand_results.handedness):
if hand_results.handedness[i]:
label = hand_results.handedness[i][0].display_name
hand_labels.append(label)
# Check all combinations of hands
for i in range(len(hand_results.hand_landmarks)):
for j in range(i + 1, len(hand_results.hand_landmarks)):
hand1_landmarks = hand_results.hand_landmarks[i]
hand2_landmarks = hand_results.hand_landmarks[j]
hand1_label = hand_labels[i]
hand2_label = hand_labels[j]
# Check all finger tip combinations
for idx1 in self.finger_tip_indices:
for idx2 in self.finger_tip_indices:
# Check if points are in cooldown
key1 = f"{hand1_label}_{self.finger_names[idx1]}"
key2 = f"{hand2_label}_{self.finger_names[idx2]}"
if key1 in cooldown_points or key2 in cooldown_points:
continue # Skip points in cooldown
point1 = hand1_landmarks[idx1]
point2 = hand2_landmarks[idx2]
distance = self.calculate_distance(point1, point2)
if distance <= self.touch_threshold:
touch_info = {
'hand1': hand1_label,
'hand2': hand2_label,
'finger1': self.finger_names[idx1],
'finger2': self.finger_names[idx2],
'distance': distance,
'hand1_index': i,
'hand2_index': j,
'point1_idx': idx1,
'point2_idx': idx2,
'point1': point1,
'point2': point2,
'touch_time': current_time,
'max_distance': distance, # Track max distance for line stretching
'line_color': [0, 255, 0], # Start white
'point1_color': [0, 0, 255], # Red
'point2_color': [0, 0, 255], # Red
'touch_id': f"{hand1_label}_{self.finger_names[idx1]}_{hand2_label}_{self.finger_names[idx2]}"
}
self.current_touches.append(touch_info)
self.touch_history.append(touch_info.copy())
def update_visual_effects(self, hand_results):
"""Update colors and lines based on touch state"""
import time
current_time = time.time()
for touch in self.current_touches + self.touch_history:
# Update point colors (fade from red back to normal)
elapsed = current_time - touch['touch_time']
if elapsed < self.cooldown_duration:
# Calculate color fade (red → normal)
fade_factor = elapsed / self.cooldown_duration
# Red fades to hand's normal color
if "Left" in touch['hand1']:
normal_color = list(self.left_hand_color)
else:
normal_color = list(self.right_hand_color)
if "Left" in touch['hand2']:
normal_color2 = list(self.left_hand_color)
else:
normal_color2 = list(self.right_hand_color)
# Interpolate color
touch['point1_color'] = [
int(touch['point1_color'][0] * (1 - fade_factor) + normal_color[0] * fade_factor),
int(touch['point1_color'][1] * (1 - fade_factor) + normal_color[1] * fade_factor),
int(touch['point1_color'][2] * (1 - fade_factor) + normal_color[2] * fade_factor)
]
touch['point2_color'] = [
int(touch['point2_color'][0] * (1 - fade_factor) + normal_color2[0] * fade_factor),
int(touch['point2_color'][1] * (1 - fade_factor) + normal_color2[1] * fade_factor),
int(touch['point2_color'][2] * (1 - fade_factor) + normal_color2[2] * fade_factor)
]
# Update line properties based on current distance
if hand_results and len(hand_results.hand_landmarks) > max(touch['hand1_index'], touch['hand2_index']):
hand1 = hand_results.hand_landmarks[touch['hand1_index']]
hand2 = hand_results.hand_landmarks[touch['hand2_index']]
if len(hand1) > touch['point1_idx'] and len(hand2) > touch['point2_idx']:
current_point1 = hand1[touch['point1_idx']]
current_point2 = hand2[touch['point2_idx']]
current_distance = self.calculate_distance(current_point1, current_point2)
# Update max distance if current is larger
if current_distance > touch['max_distance']:
touch['max_distance'] = current_distance
# Calculate line properties based on distance
# Line fades as distance increases
fade_amount = min(1.0, current_distance / (touch['max_distance'] + 0.001))
# Line thickness based on distance (thinner when far)
touch['line_thickness'] = max(1, int(3 * (1 - fade_amount)))
# Line color fades from white to invisible
touch['line_color'] = [
int(1 * (1 - fade_amount * 0.8)),
int(255 * (1 - fade_amount * 0.8)),
int(1 * (1 - fade_amount * 0.8))
]
def update_from_results(self, hand_results):
"""Update display from hand recognition results"""
canvas = np.full((self.window_height, self.window_width, 3), self.bg_color, dtype=np.uint8)
# Detect touches
self.detect_touches(hand_results)
# Update visual effects
self.update_visual_effects(hand_results)
# Print to console
self.print_touches_to_console()
# Title
cv2.putText(canvas, "MULTI-HAND TRACKING", (20, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2, cv2.LINE_AA)
# Display touch status
touch_status = f"Touch Threshold: {self.touch_threshold}"
cv2.putText(canvas, touch_status, (20, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), 1, cv2.LINE_AA)
# Cooldown status
import time
active_cooldowns = sum(1 for t in self.touch_history
if time.time() - t['touch_time'] < self.cooldown_duration)
cooldown_text = f"Cooldown: {active_cooldowns} point(s)"
cv2.putText(canvas, cooldown_text, (20, 85),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), 1, cv2.LINE_AA)
if not hand_results or not hand_results.hand_landmarks:
cv2.putText(canvas, "No hands detected", (20, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (150, 150, 150), 1, cv2.LINE_AA)
cv2.imshow(self.window_name, canvas)
return
y_offset = 120
# Display touch summary
if self.current_touches:
touch_color = self.touch_color
touch_text = f"ACTIVE TOUCHES: {len(self.current_touches)}"
else:
touch_color = self.no_touch_color
touch_text = "NO ACTIVE TOUCHES"
cv2.putText(canvas, touch_text, (20, y_offset),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, touch_color, 1, cv2.LINE_AA)
y_offset += 30
# Display individual touch details
for touch in self.current_touches[:3]: # Show first 3 to save space
touch_detail = f"{touch['hand1']} {touch['finger1']} ↔ {touch['hand2']} {touch['finger2']}"
cv2.putText(canvas, touch_detail, (40, y_offset),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, self.touch_color, 1, cv2.LINE_AA)
y_offset += 20
y_offset += 10
# Draw instructions
instructions = [
f"Finger tips: {len(self.finger_tip_indices)} per hand",
f"Touch threshold: {self.touch_threshold}",
f"Cooldown: {self.cooldown_duration}s",
"Line: White→fades | Points: Red→fades"
]
for i, line in enumerate(instructions):
cv2.putText(canvas, line, (20, self.window_height - 60 + i*15),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (150, 150, 150), 1, cv2.LINE_AA)
cv2.imshow(self.window_name, canvas)
def print_touches_to_console(self):
"""Print touch events to console (serial monitor)"""
import time
current_time = time.time()
# Print only if we have new touches and enough time has passed
if self.current_touches and (current_time - self.last_touch_print > 1.0):
print("\n" + "="*60)
print("TOUCH DETECTED - VISUAL FEEDBACK ACTIVATED")
print("="*60)
for touch in self.current_touches:
print(f" {touch['hand1']} {touch['finger1']} ↔ {touch['hand2']} {touch['finger2']}")
print(f" Distance: {touch['distance']:.4f}")
print(f" Points now RED (fading over {self.cooldown_duration}s)")
print(f" Connecting line drawn")
print("-" * 40)
self.last_touch_print = current_time
def close(self):
"""Close the window"""
cv2.destroyWindow(self.window_name)
# ============================================================================
# GESTURE MAPPING MENU
# ============================================================================
class GestureMappingMenu:
"""Menu for mapping gestures to actions"""
def __init__(self, gesture_mapping):
self.gesture_mapping = gesture_mapping
self.enabled = False
# Display settings
self.width = 400
self.height = 500
# Colors
self.bg_color = (40, 40, 60)
self.header_color = (60, 60, 100)
self.cell_color = (50, 50, 70)
self.cell_hover_color = (70, 70, 90)
self.text_color = (255, 255, 255)
self.highlight_color = (100, 200, 255)
# Selection
self.selected_gesture = None
self.selected_action = None
def toggle(self):
"""Toggle menu visibility"""
self.enabled = not self.enabled
self.selected_gesture = None
self.selected_action = None
return self.enabled
def draw(self, frame):
"""Draw the gesture mapping menu"""
if not self.enabled:
return frame
h, w = frame.shape[:2]
# Calculate position (centered)
x1 = max(0, (w - self.width) // 2)
y1 = max(0, (h - self.height) // 2)
x2 = x1 + self.width
y2 = y1 + self.height
# Draw overlay
overlay = frame.copy()
cv2.rectangle(overlay, (0, 0), (w, h), (0, 0, 0), -1)
frame = cv2.addWeighted(overlay, 0.3, frame, 0.7, 0)
# Draw menu background
cv2.rectangle(frame, (x1, y1), (x2, y2), self.bg_color, -1)
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 255, 255), 2)
# Draw title
title = "GESTURE MAPPING EDITOR"
cv2.putText(frame, title, (x1 + 20, y1 + 40),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2, cv2.LINE_AA)
# Draw column headers
cv2.rectangle(frame, (x1 + 20, y1 + 60), (x1 + 190, y1 + 90), self.header_color, -1)
cv2.putText(frame, "GESTURE", (x1 + 60, y1 + 85),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
cv2.rectangle(frame, (x1 + 210, y1 + 60), (x1 + 380, y1 + 90), self.header_color, -1)
cv2.putText(frame, "ACTION", (x1 + 260, y1 + 85),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
# Draw gesture list
gestures = self.gesture_mapping.get_available_gestures()
start_y = y1 + 100
cell_height = 35
for i, gesture in enumerate(gestures):
cell_y = start_y + i * cell_height
# Highlight selected gesture
cell_color = self.highlight_color if gesture == self.selected_gesture else self.cell_color
cv2.rectangle(frame, (x1 + 20, cell_y), (x1 + 190, cell_y + cell_height), cell_color, -1)
# Draw gesture name with emoji
emoji_map = {
'Closed_Fist': '✊',
'Open_Palm': '🖐️',
'Pointing_Up': '☝️',
'Thumb_Down': '👎',
'Thumb_Up': '👍',
'Victory': '✌️',
'ILoveYou': '🤟',
'None': '○'
}
emoji = emoji_map.get(gesture, '')
gesture_text = f"{emoji} {gesture}"
cv2.putText(frame, gesture_text, (x1 + 30, cell_y + 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, self.text_color, 1, cv2.LINE_AA)
# Draw actions list
actions = self.gesture_mapping.get_available_actions()
for i, action in enumerate(actions):
action_id, action_name, action_icon, _ = action
cell_y = start_y + i * cell_height
# Highlight selected action
cell_color = self.highlight_color if action_id == self.selected_action else self.cell_color
cv2.rectangle(frame, (x1 + 210, cell_y), (x1 + 380, cell_y + cell_height), cell_color, -1)
# Draw action
action_text = f"{action_icon} {action_name}"
cv2.putText(frame, action_text, (x1 + 220, cell_y + 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, self.text_color, 1, cv2.LINE_AA)
# Draw current mappings
mapping_y = y1 + 100 + len(gestures) * cell_height + 20
cv2.putText(frame, "CURRENT MAPPINGS:", (x1 + 20, mapping_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 100), 1, cv2.LINE_AA)
mapping_y += 25
for name, gesture_list in self.gesture_mapping.action_to_gestures.items():
if gesture_list:
mapping_text = f"{name}: {', '.join(gesture_list)}"
cv2.putText(frame, mapping_text, (x1 + 20, mapping_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), 1, cv2.LINE_AA)
mapping_y += 20
# Draw instructions
instr_y = y2 - 40
cv2.putText(frame, "Select gesture → Select action → Press 'S' to save mapping",
(x1 + 20, instr_y), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (200, 200, 200), 1, cv2.LINE_AA)
cv2.putText(frame, "Press 'G' to close menu",
(x1 + 20, instr_y + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (200, 200, 200), 1, cv2.LINE_AA)
return frame
def handle_click(self, x, y):
"""Handle clicks in the menu"""
if not self.enabled:
return False
h, w = 480, 640 # Default dimensions
x1 = max(0, (w - self.width) // 2)
y1 = max(0, (h - self.height) // 2)
# Check if click is in menu bounds
if x1 <= x <= x1 + self.width and y1 <= y <= y1 + self.height:
# Check gesture column
if x1 + 20 <= x <= x1 + 190:
start_y = y1 + 100
cell_height = 35
gestures = self.gesture_mapping.get_available_gestures()
for i, gesture in enumerate(gestures):
cell_y = start_y + i * cell_height
if cell_y <= y <= cell_y + cell_height:
self.selected_gesture = gesture
return True
# Check action column
elif x1 + 210 <= x <= x1 + 380:
start_y = y1 + 100
cell_height = 35
actions = self.gesture_mapping.get_available_actions()
for i, action in enumerate(actions):
cell_y = start_y + i * cell_height
if cell_y <= y <= cell_y + cell_height:
self.selected_action = action[0] # action_id
return True
return True # Click was in menu
return False # Click outside menu
def save_mapping(self):
"""Save the current selection as a mapping"""
if self.selected_gesture and self.selected_action:
success = self.gesture_mapping.map_gesture(self.selected_gesture, self.selected_action)
if success:
print(f"✓ Mapped {self.selected_gesture} to {self.selected_action}")
self.selected_gesture = None
self.selected_action = None
return True
return False
# ============================================================================
# SIMPLE RADIAL MENU (for actions only)
# ============================================================================
class SimpleRadialMenu:
"""Simple radial menu for executing actions, not related to gestures"""
def __init__(self, window_width, window_height):
self.enabled = False
self.window_width = window_width
self.window_height = window_height
self.center_x = window_width // 2
self.center_y = window_height // 2
# Menu settings
self.radius = min(window_width, window_height) // 4
self.square_size = 50
self.square_half = self.square_size // 2
# Colors
self.square_color_normal = (100, 100, 200)
self.square_color_hover = (150, 150, 255)
self.square_color_active = (200, 200, 255)
self.square_border_color = (255, 255, 255)
self.text_color = (255, 255, 255)
# Menu items
self.items = []
self.hovered_item = -1
self.clicked_item = -1
# Item labels (simple numbers 1-8)
self.item_labels = ["1", "2", "3", "4", "5", "6", "7", "8"]
# Actions for each button (defaults)
self.button_actions = [
lambda: print(" 🎮 Button 1 clicked"),
lambda: print(" 🎮 Button 2 clicked"),
lambda: print(" 🎮 Button 3 clicked"),
lambda: print(" 🎮 Button 4 clicked"),
lambda: print(" 🎮 Button 5 clicked"),
lambda: print(" 🎮 Button 6 clicked"),
lambda: print(" 🎮 Button 7 clicked"),
lambda: print(" 🎮 Button 8 clicked"),
]
# Create menu layout
self.create_menu_items()
def create_menu_items(self):
"""Create 8 menu items arranged in a circle"""
self.items = []
for i in range(8):
# Calculate angle
angle = (2 * math.pi / 8) * i - math.pi / 8
# Calculate position
x = self.center_x + int(self.radius * math.cos(angle))
y = self.center_y - int(self.radius * math.sin(angle))
# Create square coordinates
x1 = x - self.square_half