-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonitorTracking.py
More file actions
2361 lines (2093 loc) · 97.1 KB
/
MonitorTracking.py
File metadata and controls
2361 lines (2093 loc) · 97.1 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 os
import mediapipe as mp
import time
import math
from scipy.spatial.transform import Rotation as Rscipy
from collections import deque
import pyautogui
import threading
import keyboard
import ctypes
import csv
import json
# Screen and mouse control setup (from old script)
MONITOR_WIDTH, MONITOR_HEIGHT = pyautogui.size()
CENTER_X = MONITOR_WIDTH // 2
CENTER_Y = MONITOR_HEIGHT // 2
mouse_control_enabled = False
filter_length = 10
gaze_length = 350
# === Stabilization parameters (Phase 1) ===
SMOOTH_TAU_BASE = 0.06
SMOOTH_TAU_MIN = 0.028
SMOOTH_TAU_MAX = 0.16
MAX_SPEED_BASE_PX_S = 3200.0
GAZE_FILTER_FREQ = 120.0
GAZE_MIN_CUTOFF = 1.0
GAZE_BETA = 0.65
GAZE_D_CUTOFF = 1.0
GAZE_SPEED_ALPHA = 0.25
GAZE_SPEED_SAT = 8.0
DEADZONE_PX = 0.25
DEADZONE_EXTRA_STILL = 2.2
SPEED_GAIN_MIN = 1.2
SPEED_GAIN_MAX = 3.5
IVT_FIX_NORM = 0.03
IVT_SACCADE_NORM = 999.0
IVT_FIX_DWELL_SEC = 0.12
SACCADE_FREEZE_SEC = 0.0
FIXATION_RADIUS_BASE = 6.0
FIX_HOLD_MIN_S = 0.40
FIX_RADIUS_GAIN_PLANE = 0.25
FIX_RADIUS_GAIN_DPI = 0.15
# === Velocity-mode control (intent→velocity→cursor) ===
VELOCITY_MODE_DEFAULT = False
BIO_DEADZONE_PX = 3.0 # deadzone sinh học (px)
VEL_GAIN_BASE_X = 2800.0 # px/s cho |dx_norm|=1 (đã hạ để giảm loạn)
VEL_GAIN_BASE_Y = 2800.0 # px/s cho |dy_norm|=1 (đã hạ để giảm loạn)
INTENT_EMA_ALPHA = 0.22 # EMA chậm hơn → ổn định hơn
BASELINE_TAU_S = 0.8 # baseline cập nhật chậm (giây)
AB_INTENT_DEADZONE = 0.08 # deadzone trên (a,b) cho ý định (tỷ lệ 0..1)
VEL_SHAPE_GAMMA = 1.6 # shaping |x|^gamma để bóp nhỏ nhiễu gần 0
BASELINE_PCT_DEADZONE = 0.008 # 0.8% theo kích thước khung, cho baseline delta
VEL_MAX_PX_S = 1800.0 # trần tốc độ
VEL_MAX_ACC_PX_S2 = 9000.0 # trần gia tốc
VEL_EMA_ALPHA = 0.28 # mượt vận tốc đầu ra
# --- Head-motion compensation (Phase 2.1) ---
HEAD_ROT_SAT_DEG_S = 45.0
HEAD_TRANS_SAT_WORLD_S = 160.0
HEAD_MOTION_ALPHA = 0.30
SACCADE_BOOST_DEG_S = 25.0
SACCADE_BOOST_DURATION_S = 0.10
# --- Orbit camera state for the debug view ---
orbit_yaw = -151.0 # radians, left/right
orbit_pitch = 00.0 # radians, up/down
orbit_radius = 1500.0 # distance from head center
orbit_fov_deg = 50.0 # horizontal FOV for projection
# --- Debug-view world freeze (pivot fixed after center calibration) ---
debug_world_frozen = False
orbit_pivot_frozen = None # world-space point the debug camera orbits (monitor center at calib)
# Stored gaze markers on the monitor plane (as (a,b) in plane coords)
# a = 0..1 across width (p0->p1), b = 0..1 down height (p0->p3)
gaze_markers = []
# --- 3D monitor plane state (world space) ---
monitor_corners = None # list of 4 world points (p0..p3)
monitor_center_w = None # world center of the plane
monitor_normal_w = None # world normal
units_per_cm = None # world units per centimeter (computed at calibration)
# Shared mouse target position
mouse_target = [CENTER_X, CENTER_Y]
mouse_lock = threading.Lock()
# --- Camera orientation control (rotate captured frame) ---
camera_orientation_index = 0 # 0=default, 1=90° CW, 2=180°, 3=270° CW
CAMERA_ORIENTATION_LABELS = [
"0° (landscape)",
"90° CW (portrait)",
"180°",
"270° CW"
]
# Calibration offsets for screen mapping
calibration_offset_yaw = 0
calibration_offset_pitch = 0
# --- Simple monitor-edge calibration state ---
# 0 = waiting for center, 1 = waiting for left edge, 2 = done
calib_step = 0
# Buffers to store recent gaze data for smoothing
combined_gaze_directions = deque(maxlen=filter_length)
# reference matrices to fix coordinate flipping issue
# These help keep the axes consistent from frame to frame by stabilizing eigenvector directions
R_ref_nose = [None]
R_ref_forehead = [None]
calibration_nose_scale = None
# Initialize MediaPipe FaceMesh
mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(
static_image_mode=False,
max_num_faces=1,
refine_landmarks=True,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
# === Open webcam ===
cap = cv2.VideoCapture(3)
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# === Nose-only landmark indices (for stable up/down eye sphere tracking) ===
# These landmarks are near the nose and are less affected by lateral head movement
nose_indices = [4, 45, 275, 220, 440, 1, 5, 51, 281, 44, 274, 241,
461, 125, 354, 218, 438, 195, 167, 393, 165, 391,
3, 248]
# ===== NEW: File writing for screen position =====
screen_position_file = "C:/Users/white/Desktop/EyeTracker-main/gaze_vector.txt"
def write_screen_position(x, y):
"""Write screen position to file, overwriting the same line"""
with open(screen_position_file, 'w') as f:
f.write(f"{x},{y}\n")
def _rot_x(a):
ca, sa = math.cos(a), math.sin(a)
return np.array([[1, 0, 0],
[0, ca, -sa],
[0, sa, ca]], dtype=float)
def _rot_y(a):
ca, sa = math.cos(a), math.sin(a)
return np.array([[ ca, 0, sa],
[ 0, 1, 0],
[-sa, 0, ca]], dtype=float)
def _normalize(v):
v = np.asarray(v, dtype=float)
n = np.linalg.norm(v)
return v / n if n > 1e-9 else v
def apply_camera_orientation(frame):
"""Rotate incoming camera frame theo hướng người dùng chọn."""
if camera_orientation_index == 1:
return cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
if camera_orientation_index == 2:
return cv2.rotate(frame, cv2.ROTATE_180)
if camera_orientation_index == 3:
return cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)
return frame
class OneEuroFilter:
def __init__(self, freq, min_cutoff=1.0, beta=0.0, d_cutoff=1.0):
self.freq = freq
self.min_cutoff = min_cutoff
self.beta = beta
self.d_cutoff = d_cutoff
self.x_prev = None
self.dx_prev = 0.0
self.t_prev = None
@staticmethod
def _alpha(cutoff, dt):
tau = 1.0 / (2 * math.pi * cutoff)
return 1.0 / (1.0 + tau / dt)
def filter(self, x, timestamp=None):
x = float(x)
if self.x_prev is None:
self.x_prev = x
self.dx_prev = 0.0
self.t_prev = timestamp
return x
if timestamp is not None:
dt = max(1e-6, (timestamp - self.t_prev) if self.t_prev is not None else (1.0 / self.freq))
self.t_prev = timestamp
else:
dt = 1.0 / self.freq
dx = (x - self.x_prev) / dt
a_d = self._alpha(self.d_cutoff, dt)
dx_hat = a_d * dx + (1.0 - a_d) * self.dx_prev
cutoff = self.min_cutoff + self.beta * abs(dx_hat)
a = self._alpha(max(cutoff, 1e-6), dt)
x_hat = a * x + (1.0 - a) * self.x_prev
self.x_prev = x_hat
self.dx_prev = dx_hat
return x_hat
# Filters and stabilization state
gaze_filter_x = OneEuroFilter(GAZE_FILTER_FREQ, GAZE_MIN_CUTOFF, GAZE_BETA, GAZE_D_CUTOFF)
gaze_filter_y = OneEuroFilter(GAZE_FILTER_FREQ, GAZE_MIN_CUTOFF, GAZE_BETA, GAZE_D_CUTOFF)
smoothed_mouse_pos = [CENTER_X, CENTER_Y]
last_move_time = time.perf_counter()
prev_step_len = 0.0
current_smooth_tau = SMOOTH_TAU_BASE
current_max_speed = MAX_SPEED_BASE_PX_S
current_deadzone_px = DEADZONE_PX
current_speed_gain = 1.0
gaze_speed_ema = 0.0
last_filtered_target = None
last_filter_timestamp = None
saccade_freeze_until = 0.0
fix_low_start_time = None
fixation_anchor = None
fixation_anchor_time = None
fix_anchor_hold_until = 0.0
stabilization_enabled = True
stabilization_warmup_until = 0.0
fixation_enabled = False
plane_mapping_enabled = True
plane_invert_x = False
plane_invert_y = False
# --- DPI per-axis scale (user adjustable) ---
dpi_scale_x = 1.6
dpi_scale_y = 2.0
plane_gain_x = 5.27
plane_gain_y = 7.51
PLANE_GAMMA_X = 1.25
PLANE_GAMMA_Y = 1.30
# --- Debug print for plane params (a,b) ---
ab_debug_enabled = False
ab_debug_last_print = 0.0
# --- Axis-dominance gating to reduce cross-axis drift at edges ---
ab_last_pair = None # (a,b) from previous frame
AB_H_DOM_RATIO = 2.0 # horizontal dominates when |da| > R * |db|
AB_V_DOM_RATIO = 2.0 # vertical dominates when |db| > R * |da|
AB_MAX_B_STEP = 0.010 # max change of b per frame when horizontal dominates
AB_MAX_A_STEP = 0.030 # max change of a per frame when vertical dominates
ab_anchor_b = None
ab_anchor_on = False
ab_anchor_last = 0.0
AB_ANCHOR_EDGE_A = 0.85
AB_ANCHOR_TIMEOUT_S = 0.30
AB_ANCHOR_CENTER_DEV = 0.20
AB_H_MIN_DA = 0.015
AB_V_MIN_DB = 0.015
AB_H_DOT_RATIO = 1.25
AB_H_MIN_DOT = 0.10
ab_last_stable_b = None
# Mild temporal smoothing for (a,b) to giảm jitter nhưng giữ độ chính xác
ab_hist_a = deque(maxlen=5)
ab_hist_b = deque(maxlen=5)
ab_ema_a = None
ab_ema_b = None
AB_EMA_ALPHA_BASE = 0.28 # chuyển động chậm → mượt hơn
AB_EMA_ALPHA_FAST = 0.65 # chuyển động nhanh → bám sát hơn
AB_SPEED_THRESH = 0.06 # ngưỡng tốc độ (đơn vị a/b per frame)
# === Online training (guided target) ===
training_enabled = False
training_window_name = "Gaze Trainer"
training_window_created = False
training_targets = []
training_index = 0
training_state = 0
training_state_until = 0.0
training_point_duration_s = 1.2
training_pause_s = 0.4
training_collect_eye = []
training_collect_head = []
training_collect_phi = []
saved_mouse_control = False
last_gpm_ab = None
last_raw_yaw_pitch = None
training_records = []
training_csv_path = os.path.join(os.path.dirname(__file__), "training_data.csv")
# === RLS models for adaptive DPI (speed & tau) ===
class RLSModel:
def __init__(self, n_features, lam=0.995, delta=1000.0):
self.lam = lam
self.w = np.zeros((n_features, 1), dtype=float)
self.P = (1.0 / delta) * np.eye(n_features, dtype=float)
self.n = n_features
def update(self, phi, y):
# phi shape (n,), y scalar
phi = np.asarray(phi, dtype=float).reshape((self.n, 1))
y = float(y)
# RLS update
P = self.P
w = self.w
lam = self.lam
Pi_phi = P @ phi
gain_denom = lam + float(phi.T @ Pi_phi)
K = Pi_phi / gain_denom
err = y - float(phi.T @ w)
w_new = w + K * err
P_new = (P - (K @ phi.T @ P)) / lam
self.w = w_new
self.P = P_new
def predict(self, phi):
phi = np.asarray(phi, dtype=float).reshape((self.n, 1))
return float(phi.T @ self.w)
def rls_save(path, model_speed, model_tau):
try:
data = {
'speed': {'w': model_speed.w.flatten().tolist(), 'P': model_speed.P.tolist(), 'lam': model_speed.lam},
'tau': {'w': model_tau.w.flatten().tolist(), 'P': model_tau.P.tolist(), 'lam': model_tau.lam},
}
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f)
except Exception:
pass
def rls_load(path, n_features):
try:
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
ms = RLSModel(n_features, lam=float(data['speed'].get('lam', 0.995)))
mt = RLSModel(n_features, lam=float(data['tau'].get('lam', 0.995)))
ms.w = np.asarray(data['speed']['w'], dtype=float).reshape((n_features, 1))
ms.P = np.asarray(data['speed']['P'], dtype=float)
mt.w = np.asarray(data['tau']['w'], dtype=float).reshape((n_features, 1))
mt.P = np.asarray(data['tau']['P'], dtype=float)
return ms, mt
except Exception:
return RLSModel(n_features), RLSModel(n_features)
rls_feature_dim = 8
rls_model_path = os.path.join(os.path.dirname(__file__), 'dpi_model.json')
rls_speed_model, rls_tau_model = rls_load(rls_model_path, rls_feature_dim)
rls_training_enabled = True
def compute_context_features(fx=None, fy=None):
# distance to target normalized
try:
sx, sy = smoothed_mouse_pos
except Exception:
sx, sy = CENTER_X, CENTER_Y
if fx is None or fy is None:
fx, fy = sx, sy
dist = math.hypot(float(fx) - float(sx), float(fy) - float(sy))
diag = max(1.0, math.hypot(MONITOR_WIDTH, MONITOR_HEIGHT))
m_norm = float(np.clip(dist / (0.35 * diag), 0.0, 1.0))
total = float(max(1e-6, head_motion_ema + eye_motion_ema))
eye_ratio = float(eye_motion_ema / total)
head_ratio = float(head_motion_ema / total)
pm_flag = 1.0 if plane_mapping_enabled else 0.0
cx, cy = CENTER_X, CENTER_Y
dc = math.hypot(float(fx) - cx, float(fy) - cy) / (0.71 * diag)
phi = np.array([
1.0,
m_norm,
eye_ratio,
head_ratio,
float(head_motion_ema),
float(eye_motion_ema),
pm_flag,
float(np.clip(dc, 0.0, 1.0)),
], dtype=float)
return phi
# --- Dynamic motion/adaptation state ---
current_smooth_tau = SMOOTH_TAU_BASE
current_max_speed = MAX_SPEED_BASE_PX_S
prev_head_R = None
prev_head_center = None
prev_gaze_dir = None
head_motion_ema = 0.0
eye_motion_ema = 0.0
last_motion_sample_time = None
saccade_boost_until = 0.0
# === Velocity-mode state ===
velocity_mode_enabled = VELOCITY_MODE_DEFAULT
baseline_px = None # [x, y] in pixels, slow-updated
last_velocity_time = None
intent_ema_x = 0.0
intent_ema_y = 0.0
last_raw_screen_xy = None
intent_still_since = None
def update_cursor_target(screen_x, screen_y):
global last_filtered_target, last_filter_timestamp, gaze_speed_ema
global current_deadzone_px, current_speed_gain
global saccade_freeze_until, fix_low_start_time, fixation_anchor
global fixation_anchor_time, fix_anchor_hold_until
raw = np.array([float(screen_x), float(screen_y)], dtype=float)
now = time.perf_counter()
if not stabilization_enabled:
# Bỏ qua lọc: trả về raw trực tiếp (clamped)
raw[0] = np.clip(raw[0], 0.0, MONITOR_WIDTH - 1)
raw[1] = np.clip(raw[1], 0.0, MONITOR_HEIGHT - 1)
last_filtered_target = raw.copy()
last_filter_timestamp = now
return raw
# Warmup: bỏ saccade/fixation/deadzone trong ~0.7s sau calibrate để tránh kẹt
if now < stabilization_warmup_until:
filtered = np.array([
gaze_filter_x.filter(raw[0], now),
gaze_filter_y.filter(raw[1], now)
], dtype=float)
filtered[0] = np.clip(filtered[0], 0.0, MONITOR_WIDTH - 1)
filtered[1] = np.clip(filtered[1], 0.0, MONITOR_HEIGHT - 1)
last_filtered_target = filtered
last_filter_timestamp = now
return filtered.copy()
if last_filtered_target is None:
filtered = np.array([
gaze_filter_x.filter(raw[0], now),
gaze_filter_y.filter(raw[1], now)
], dtype=float)
filtered[0] = np.clip(filtered[0], 0.0, MONITOR_WIDTH - 1)
filtered[1] = np.clip(filtered[1], 0.0, MONITOR_HEIGHT - 1)
last_filtered_target = filtered
last_filter_timestamp = now
current_speed_gain = SPEED_GAIN_MIN
current_deadzone_px = DEADZONE_PX + DEADZONE_EXTRA_STILL
return filtered.copy()
dt = max(1e-3, now - last_filter_timestamp)
delta = raw - last_filtered_target
delta_norm = np.array([
delta[0] / max(1.0, MONITOR_WIDTH),
delta[1] / max(1.0, MONITOR_HEIGHT)
])
speed_norm = np.linalg.norm(delta_norm) / dt
capped_speed = min(speed_norm, GAZE_SPEED_SAT)
gaze_speed_ema = ((1.0 - GAZE_SPEED_ALPHA) * gaze_speed_ema + GAZE_SPEED_ALPHA * capped_speed)
# If user moved far from fixation anchor, drop anchor (escape condition)
if fixation_enabled and fixation_anchor is not None:
try:
dpi_factor_tmp = float(max(0.1, math.sqrt(max(0.1, dpi_scale_x) * max(0.1, dpi_scale_y))))
plane_gain_mean = float((plane_gain_x + plane_gain_y) * 0.5)
fix_r_dyn = float(FIXATION_RADIUS_BASE * (1.0 + FIX_RADIUS_GAIN_PLANE * (plane_gain_mean - 1.0)) * (1.0 + FIX_RADIUS_GAIN_DPI * (dpi_factor_tmp - 1.0)))
except Exception:
fix_r_dyn = float(FIXATION_RADIUS_BASE)
if float(np.linalg.norm(raw - fixation_anchor)) > (fix_r_dyn * 1.15):
fixation_anchor = None
fix_low_start_time = None
# I-VT saccade detection → freeze
if speed_norm > IVT_SACCADE_NORM:
saccade_freeze_until = now + SACCADE_FREEZE_SEC
fix_low_start_time = None
fixation_anchor = None
if now < saccade_freeze_until and last_filtered_target is not None:
raw = last_filtered_target.copy()
else:
# Mandatory hold while within hold window
if fixation_enabled and fixation_anchor is not None and now < fix_anchor_hold_until:
raw = fixation_anchor.copy()
# Fixation dwell → stick to anchor (only when enabled)
elif fixation_enabled and speed_norm < IVT_FIX_NORM:
if fix_low_start_time is None:
fix_low_start_time = now
fixation_anchor = last_filtered_target.copy() if last_filtered_target is not None else None
fixation_anchor_time = now
elif (now - fix_low_start_time) >= IVT_FIX_DWELL_SEC and fixation_anchor is not None:
dist_anchor = float(np.linalg.norm(raw - fixation_anchor))
try:
dpi_factor_tmp = float(max(0.1, math.sqrt(max(0.1, dpi_scale_x) * max(0.1, dpi_scale_y))))
plane_gain_mean = float((plane_gain_x + plane_gain_y) * 0.5)
fix_r = float(FIXATION_RADIUS_BASE * (1.0 + FIX_RADIUS_GAIN_PLANE * (plane_gain_mean - 1.0)) * (1.0 + FIX_RADIUS_GAIN_DPI * (dpi_factor_tmp - 1.0)))
except Exception:
fix_r = float(FIXATION_RADIUS_BASE)
if dist_anchor <= fix_r:
raw = fixation_anchor.copy()
fix_anchor_hold_until = max(fix_anchor_hold_until, now + FIX_HOLD_MIN_S)
else:
fix_low_start_time = None
fixation_anchor = None
# Dynamic deadzone & speed gain from gaze speed
gaze_ratio = float(np.clip(gaze_speed_ema / max(GAZE_SPEED_SAT, 1e-6), 0.0, 1.0))
current_speed_gain = float(SPEED_GAIN_MIN + (SPEED_GAIN_MAX - SPEED_GAIN_MIN) * gaze_ratio)
current_deadzone_px = float(DEADZONE_PX + DEADZONE_EXTRA_STILL * (1.0 - gaze_ratio))
# Low-motion freeze: khi rất yên, giữ nguyên mục tiêu để cắt trôi chậm
if gaze_ratio <= 0.08 and np.linalg.norm(delta) <= (current_deadzone_px * 0.8):
raw = last_filtered_target.copy()
if np.linalg.norm(delta) <= current_deadzone_px:
# cho phép dịch chuyển nhỏ thay vì khoá cứng để tránh cảm giác "không di chuyển"
soft_k = float(np.clip(0.15 + 0.65 * gaze_ratio, 0.10, 0.80))
raw = last_filtered_target.copy() + delta * soft_k
# Thích nghi tham số OneEuro theo tốc độ nhìn: chậm → cắt thấp (mượt), nhanh → cắt cao (nhạy)
try:
dyn_min_cut = float(np.clip(0.55 + 0.65 * gaze_ratio, 0.40, 1.40))
dyn_beta = float(np.clip(0.35 + 0.45 * gaze_ratio, 0.25, 0.80))
gaze_filter_x.min_cutoff = dyn_min_cut
gaze_filter_y.min_cutoff = dyn_min_cut
gaze_filter_x.beta = dyn_beta
gaze_filter_y.beta = dyn_beta
except Exception:
pass
filtered = np.array([
gaze_filter_x.filter(raw[0], now),
gaze_filter_y.filter(raw[1], now)
], dtype=float)
filtered[0] = np.clip(filtered[0], 0.0, MONITOR_WIDTH - 1)
filtered[1] = np.clip(filtered[1], 0.0, MONITOR_HEIGHT - 1)
last_filtered_target = filtered
last_filter_timestamp = now
return filtered.copy()
def apply_camera_orientation(frame):
"""Rotate incoming camera frame theo hướng người dùng chọn."""
if camera_orientation_index == 1:
return cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
if camera_orientation_index == 2:
return cv2.rotate(frame, cv2.ROTATE_180)
if camera_orientation_index == 3:
return cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)
return frame
def _focal_px(width, fov_deg):
# horizontal pinhole focal length
return 0.5 * width / math.tan(math.radians(fov_deg) * 0.5)
def create_monitor_plane(head_center, R_final, face_landmarks, w, h,
forward_hint=None, gaze_origin=None, gaze_dir=None):
"""
Build a 60cm x 40cm plane 50cm in front of the face, in world units.
Monitor is oriented horizontally like a real monitor (top edge parallel to global X-axis).
"""
# 1) Estimate scale from chin<->forehead distance
try:
lm_chin = face_landmarks[152]
lm_fore = face_landmarks[10]
chin_w = np.array([lm_chin.x * w, lm_chin.y * h, lm_chin.z * w], dtype=float)
fore_w = np.array([lm_fore.x * w, lm_fore.y * h, lm_fore.z * w], dtype=float)
face_h_units = np.linalg.norm(fore_w - chin_w)
upc = face_h_units / 15.0 # units per cm
except Exception:
upc = 5.0
# 2) Monitor geometry in world units
dist_cm = 50.0
mon_w_cm, mon_h_cm = 60.0, 40.0
half_w = (mon_w_cm * 0.5) * upc
half_h = (mon_h_cm * 0.5) * upc
# Head forward vector
head_forward = -R_final[:, 2]
if forward_hint is not None:
head_forward = forward_hint / np.linalg.norm(forward_hint)
# --- NEW: use gaze ray intersection ---
if gaze_origin is not None and gaze_dir is not None:
gaze_dir = gaze_dir / np.linalg.norm(gaze_dir)
# Place the monitor so its center is exactly at some point on the gaze ray
# For simplicity: choose intersection at 50 cm from head_center along head_forward
plane_point = head_center + head_forward * (50.0 * upc)
plane_normal = head_forward
denom = np.dot(plane_normal, gaze_dir)
if abs(denom) > 1e-6:
t = np.dot(plane_normal, plane_point - gaze_origin) / denom
center_w = gaze_origin + t * gaze_dir
else:
# fallback: use fixed distance
center_w = head_center + head_forward * (50.0 * upc)
else:
# fallback: original placement
center_w = head_center + head_forward * (50.0 * upc)
# Compute right/up using head orientation
world_up = np.array([0, -1, 0], dtype=float)
head_right = np.cross(world_up, head_forward)
head_right /= np.linalg.norm(head_right)
head_up = np.cross(head_forward, head_right)
head_up /= np.linalg.norm(head_up)
# Corners
p0 = center_w - head_right * half_w - head_up * half_h
p1 = center_w + head_right * half_w - head_up * half_h
p2 = center_w + head_right * half_w + head_up * half_h
p3 = center_w - head_right * half_w + head_up * half_h
normal_w = head_forward / (np.linalg.norm(head_forward) + 1e-9)
return [p0, p1, p2, p3], center_w, normal_w, upc
def update_orbit_from_keys():
"""Keyboard orbit controls that PRINT every frame while a key is held."""
global orbit_yaw, orbit_pitch, orbit_radius
yaw_step = math.radians(1.5)
pitch_step = math.radians(1.5)
zoom_step = 12.0
changed = False
# Rotate
if keyboard.is_pressed('j'): # yaw left
orbit_yaw -= yaw_step; changed = True
if keyboard.is_pressed('l'): # yaw right
orbit_yaw += yaw_step; changed = True
if keyboard.is_pressed('i'): # pitch up
orbit_pitch += pitch_step; changed = True
if keyboard.is_pressed('k'): # pitch down
orbit_pitch -= pitch_step; changed = True
# Zoom
if keyboard.is_pressed('['): # zoom out
orbit_radius += zoom_step; changed = True
if keyboard.is_pressed(']'): # zoom in
orbit_radius = max(80.0, orbit_radius - zoom_step); changed = True
# Reset (prints every frame while held)
if keyboard.is_pressed('r'):
orbit_yaw = 0.0
orbit_pitch = 0.0
orbit_radius = 600.0
changed = True
# Clamp pitch & radius
orbit_pitch = max(math.radians(-89), min(math.radians(89), orbit_pitch))
orbit_radius = max(80.0, orbit_radius)
if changed:
print(f"[Orbit Debug] yaw={math.degrees(orbit_yaw):.2f}°, "
f"pitch={math.degrees(orbit_pitch):.2f}°, "
f"radius={orbit_radius:.2f}, "
f"fov={orbit_fov_deg:.1f}°")
def compute_scale(points_3d):
# Use average pairwise distance for robustness
n = len(points_3d)
total = 0
count = 0
for i in range(n):
for j in range(i + 1, n):
dist = np.linalg.norm(points_3d[i] - points_3d[j])
total += dist
count += 1
return total / count if count > 0 else 1.0
def draw_gaze(frame, eye_center, iris_center, eye_radius, color, gaze_length):
# Gaze vector
gaze_direction = iris_center - eye_center
gaze_direction /= np.linalg.norm(gaze_direction)
gaze_endpoint = eye_center + gaze_direction * gaze_length
cv2.line(frame, tuple(int(v) for v in eye_center[:2]), tuple(int(v) for v in gaze_endpoint[:2]), color, 2)
# Segment points
iris_offset = eye_center + gaze_direction * (1.2 * eye_radius)
# ---- PART 1: back segment (behind iris) ----
cv2.line(
frame,
(int(eye_center[0]), int(eye_center[1])),
(int(iris_offset[0]), int(iris_offset[1])),
color,
1
)
# ---- IRIS (occludes part of the ray) ----
up_dir = np.array([0, -1, 0])
right_dir = np.cross(gaze_direction, up_dir)
if np.linalg.norm(right_dir) < 1e-6:
right_dir = np.array([1, 0, 0])
up_dir = np.cross(right_dir, gaze_direction)
up_dir /= np.linalg.norm(up_dir)
right_dir /= np.linalg.norm(right_dir)
ellipse_axes = (
int((eye_radius / 3) * np.linalg.norm(right_dir[:2])),
int((eye_radius / 3) * np.linalg.norm(up_dir[:2]))
)
angle = math.degrees(math.atan2(gaze_direction[1], gaze_direction[0]))
# ---- PART 2: front segment (on top of iris) ----
cv2.line(
frame,
(int(iris_offset[0]), int(iris_offset[1])),
(int(gaze_endpoint[0]), int(gaze_endpoint[1])),
color,
1
)
def draw_wireframe_cube(frame, center, R, size=80):
# Given a center and rotation matrix, draw a cube aligned to that orientation
right = R[:, 0]
up = -R[:, 1]
forward = -R[:, 2]
hw, hh, hd = size * 1, size * 1, size * 1
def corner(x_sign, y_sign, z_sign):
return (center +
x_sign * hw * right +
y_sign * hh * up +
z_sign * hd * forward)
# 8 corners of the cube
corners = [corner(x, y, z) for x in [-1, 1] for y in [1, -1] for z in [-1, 1]]
projected = [(int(pt[0]), int(pt[1])) for pt in corners]
# Edges connecting the corners
edges = [
(0, 1), (1, 3), (3, 2), (2, 0),
(4, 5), (5, 7), (7, 6), (6, 4),
(0, 4), (1, 5), (2, 6), (3, 7)
]
for i, j in edges:
cv2.line(frame, projected[i], projected[j], (255, 128, 0), 2)
def compute_and_draw_coordinate_box(frame, face_landmarks, indices, ref_matrix_container, color=(0, 255, 0), size=80):
# Extract 3D positions of selected landmarks
points_3d = np.array([
[face_landmarks[i].x * w, face_landmarks[i].y * h, face_landmarks[i].z * w]
for i in indices
])
# Compute the average position as the center of this substructure
center = np.mean(points_3d, axis=0)
# Draw the raw 2D landmark points
for i in indices:
x, y = int(face_landmarks[i].x * w), int(face_landmarks[i].y * h)
cv2.circle(frame, (x, y), 3, color, -1)
# PCA-based orientation: Compute eigenvectors of the covariance matrix
centered = points_3d - center
cov = np.cov(centered.T)
eigvals, eigvecs = np.linalg.eigh(cov)
eigvecs = eigvecs[:, np.argsort(-eigvals)] # Sort by descending eigenvalue (major axes)
# Ensure the orientation matrix is right-handed
if np.linalg.det(eigvecs) < 0:
eigvecs[:, 2] *= -1
# Convert to Euler angles and re-construct rotation matrix (optional but clarifies the transform)
r = Rscipy.from_matrix(eigvecs)
roll, pitch, yaw = r.as_euler('zyx', degrees=False)
yaw *= 1
roll *= 1
R_final = Rscipy.from_euler('zyx', [roll, pitch, yaw]).as_matrix()
# === Stabilize rotation with reference matrix to avoid flipping during eigenvector sign change ===
if ref_matrix_container[0] is None:
ref_matrix_container[0] = R_final.copy()
else:
R_ref = ref_matrix_container[0]
for i in range(3):
if np.dot(R_final[:, i], R_ref[:, i]) < 0:
R_final[:, i] *= -1
# Draw cube and orientation axes on the image
draw_wireframe_cube(frame, center, R_final, size)
# Draw X (green), Y (blue), Z (red) axes
axis_length = size * 1.2
axis_dirs = [R_final[:, 0], -R_final[:, 1], -R_final[:, 2]]
axis_colors = [(0, 255, 0), (0, 0, 255), (255, 0, 0)]
for i in range(3):
end_pt = center + axis_dirs[i] * axis_length
cv2.line(frame, (int(center[0]), int(center[1])), (int(end_pt[0]), int(end_pt[1])), axis_colors[i], 2)
return center, R_final, points_3d
def convert_gaze_to_screen_coordinates(combined_gaze_direction, calibration_offset_yaw, calibration_offset_pitch):
"""
Convert 3D gaze direction vector to 2D screen coordinates
This function is adapted from the old script's vector-to-screen mapping logic
"""
# Reference forward direction (camera looking straight ahead)
reference_forward = np.array([0, 0, -1]) # Z-axis into the screen
# Normalize the gaze direction
avg_direction = combined_gaze_direction / np.linalg.norm(combined_gaze_direction)
# Horizontal (yaw) angle from reference (project onto XZ plane)
xz_proj = np.array([avg_direction[0], 0, avg_direction[2]])
xz_proj /= np.linalg.norm(xz_proj)
yaw_rad = math.acos(np.clip(np.dot(reference_forward, xz_proj), -1.0, 1.0))
if avg_direction[0] < 0:
yaw_rad = -yaw_rad # left is negative
# Vertical (pitch) angle from reference (project onto YZ plane)
yz_proj = np.array([0, avg_direction[1], avg_direction[2]])
yz_proj /= np.linalg.norm(yz_proj)
pitch_rad = math.acos(np.clip(np.dot(reference_forward, yz_proj), -1.0, 1.0))
# down (y>0) -> positive pitch, up (y<0) -> negative pitch
if avg_direction[1] > 0:
pitch_rad = +pitch_rad
else:
pitch_rad = -pitch_rad
# Convert to degrees and re-center around 0
yaw_deg = np.degrees(yaw_rad)
pitch_deg = np.degrees(pitch_rad)
#yaw is now converted to -90 (looking directly left) to +90 (looking directly right), wrt camera
#pitch is now converted to +90 (looking straight up) and -90 (looking straight down), wrt camera
raw_yaw_deg = yaw_deg
raw_pitch_deg = pitch_deg
# Specify degrees at which screen border will be reached
yawDegrees = 15.0 # x degrees left or right
pitchDegrees = 10.0 # x degrees up or down
# Apply calibration offsets
yaw_deg += calibration_offset_yaw
pitch_deg += calibration_offset_pitch
# Map to full screen resolution
screen_x = int(((yaw_deg + yawDegrees) / (2 * yawDegrees)) * MONITOR_WIDTH)
# pitch_deg > 0 khi nhìn xuống => y phải tăng
screen_y = int(((pitch_deg + pitchDegrees) / (2 * pitchDegrees)) * MONITOR_HEIGHT)
# Clamp screen position to monitor bounds
screen_x = max(10, min(screen_x, MONITOR_WIDTH - 10))
screen_y = max(10, min(screen_y, MONITOR_HEIGHT - 10))
return screen_x, screen_y, raw_yaw_deg, raw_pitch_deg
def gaze_point_on_monitor(origin, direction):
"""Project gaze ray (origin, direction) to calibrated monitor plane and map to screen pixels.
Returns (x, y, a, b) or None if invalid/outside.
Ensure local axes are ordered TL->TR (u) and TL->BL (v) so b grows downward.
"""
if (monitor_corners is None or monitor_center_w is None or monitor_normal_w is None):
return None
O = np.asarray(origin, dtype=float)
D = _normalize(np.asarray(direction, dtype=float))
C = np.asarray(monitor_center_w, dtype=float)
N = _normalize(np.asarray(monitor_normal_w, dtype=float))
denom = float(np.dot(N, D))
if abs(denom) < 1e-6:
return None
t = float(np.dot(N, (C - O)) / denom)
if t <= 0.0:
return None
P = O + t * D
p0, p1, p2, p3 = [np.asarray(p, dtype=float) for p in monitor_corners]
# Local axes from construction
u = p1 - p0 # width vector
v = p3 - p0 # height vector
uu = float(np.dot(u, u))
vv = float(np.dot(v, v))
uv = float(np.dot(u, v))
if uu < 1e-9 or vv < 1e-9:
return None
# Solve exact (a,b) in oblique basis via Gram matrix inverse
wv = P - p0
uw = float(np.dot(u, wv))
vw = float(np.dot(v, wv))
det = uu * vv - uv * uv
if abs(det) < 1e-9:
return None
a = float((vv * uw - uv * vw) / det)
b = float((uu * vw - uv * uw) / det)
# Decouple axes at edges: clamp a first, then recompute b from residual
a_c = float(np.clip(a, 0.0, 1.0))
wv_res = wv - a_c * u
b_c = float(np.clip(np.dot(v, wv_res) / max(vv, 1e-9), 0.0, 1.0))
# Axis-dominance gating across frames to avoid vertical push during horizontal scans
global ab_last_pair, ab_anchor_on, ab_anchor_b, ab_anchor_last, ab_last_stable_b, ab_hist_a, ab_hist_b, ab_ema_a, ab_ema_b
try:
if ab_last_pair is not None:
prev_a, prev_b = ab_last_pair
da = float(a_c - prev_a)
db = float(b_c - prev_b)
# Hard guard: nếu đang quét ngang (da đáng kể) mà b rớt vào biên, giữ b của frame trước
if (0.05 <= prev_b <= 0.95) and (b_c <= 0.005 or b_c >= 0.995) and (abs(da) >= 0.02):
b_c = prev_b
# Dot-based axis dominance from gaze ray vs plane axes
u_len = math.sqrt(max(uu, 1e-9))
v_len = math.sqrt(max(vv, 1e-9))
u_hat = u / u_len
v_hat = v / v_len
h_dot = float(abs(np.dot(u_hat, D)))
v_dot = float(abs(np.dot(v_hat, D)))
dot_horiz = (h_dot > AB_H_MIN_DOT) and (h_dot > AB_H_DOT_RATIO * (v_dot + 1e-6))
# Ratio-based dominance from parameter deltas
dom_h_ratio = (abs(da) > AB_H_MIN_DA) and (abs(da) > AB_H_DOM_RATIO * (abs(db) + 1e-6))
dom_v_ratio = (abs(db) > AB_V_MIN_DB) and (abs(db) > AB_V_DOM_RATIO * (abs(da) + 1e-6))
dom_h = bool(dot_horiz or dom_h_ratio)
dom_v = bool((not dom_h) and dom_v_ratio)
if dom_h:
# Horizontal dominates: limit b change per frame
b_c = float(np.clip(prev_b + np.clip(db, -AB_MAX_B_STEP, AB_MAX_B_STEP), 0.0, 1.0))
elif dom_v:
# Vertical dominates: limit a change per frame
a_c = float(np.clip(prev_a + np.clip(da, -AB_MAX_A_STEP, AB_MAX_A_STEP), 0.0, 1.0))
# Boundary lock: nếu a chạm biên trái/phải, giữ nguyên b để tránh kéo dọc khi quét ngang
if a_c <= 0.01 or a_c >= 0.99:
b_c = prev_b
# Ngược lại: nếu b chạm biên trên/dưới, giữ nguyên a khi quét dọc
if b_c <= 0.01 or b_c >= 0.99:
a_c = prev_a
# Anchor b trong lúc quét ngang mạnh hoặc khi ở gần mép trái/phải
now_t = time.perf_counter()
near_edge = (a_c >= AB_ANCHOR_EDGE_A) or (a_c <= (1.0 - AB_ANCHOR_EDGE_A))
mid_outer = (abs(a_c - 0.5) >= AB_ANCHOR_CENTER_DEV)
if (dom_h or near_edge or mid_outer) and not dom_v:
if not ab_anchor_on or ab_anchor_b is None:
ab_anchor_on = True
ab_anchor_b = prev_b
b_c = ab_anchor_b
ab_anchor_last = now_t
else:
# Thoát anchor nếu hết quét ngang hoặc timeout
if ab_anchor_on and (now_t - (ab_anchor_last or now_t)) > AB_ANCHOR_TIMEOUT_S:
ab_anchor_on = False
ab_anchor_b = None
# Nếu quét ngang mạnh và b chạm biên, giữ b theo khung trước hoặc theo giá trị ổn định gần nhất
if dom_h and (b_c <= 0.005 or b_c >= 0.995):
if ab_last_stable_b is not None:
b_c = ab_last_stable_b
else:
b_c = prev_b
# Cập nhật b ổn định khi ở vùng trong (tránh lưu giá trị sát biên)
if 0.05 <= b_c <= 0.95:
ab_last_stable_b = b_c
except Exception:
pass
# Median-3 + EMA smoothing for (a,b) to giảm jitter high-frequency
try:
# median of last 3 corrected samples
ab_hist_a.append(float(np.clip(a_c, 0.0, 1.0)))
ab_hist_b.append(float(np.clip(b_c, 0.0, 1.0)))
if len(ab_hist_a) >= 3:
a_med = float(np.median(list(ab_hist_a)[-3:]))
b_med = float(np.median(list(ab_hist_b)[-3:]))
else:
a_med, b_med = a_c, b_c
# speed-adaptive EMA
prev_a, prev_b = ab_last_pair if ab_last_pair is not None else (a_med, b_med)
speed_ab = float(math.hypot(a_med - prev_a, b_med - prev_b))
alpha = AB_EMA_ALPHA_FAST if speed_ab > AB_SPEED_THRESH else AB_EMA_ALPHA_BASE
if ab_ema_a is None or ab_ema_b is None:
ab_ema_a, ab_ema_b = a_med, b_med
else:
ab_ema_a = float((1.0 - alpha) * ab_ema_a + alpha * a_med)
ab_ema_b = float((1.0 - alpha) * ab_ema_b + alpha * b_med)