-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1106_pulse.py
More file actions
1881 lines (1598 loc) · 85.7 KB
/
1106_pulse.py
File metadata and controls
1881 lines (1598 loc) · 85.7 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 threading
import queue
import serial
import serial.tools.list_ports # ⭐ 포트 확인용
import os
import re
import time
import sys
from collections import deque
cv2.setUseOptimized(True)
try:
cv2.ocl.setUseOpenCL(True)
except Exception:
pass
# ====== 한글 텍스트 유지를 위한 PIL 사용 ======
from PIL import ImageFont, ImageDraw, Image
FONT_PATH = r"C:\Windows\Fonts\malgun.ttf"
def draw_text_kr(img, text, org, font_size=26, thickness=2):
if not text:
return img
img_pil = Image.fromarray(img)
try:
font = ImageFont.truetype(FONT_PATH, font_size)
except:
cv2.putText(img, text, org, cv2.FONT_HERSHEY_SIMPLEX, max(0.5, font_size/26.0),
(255,255,255), thickness+2, cv2.LINE_AA)
cv2.putText(img, text, org, cv2.FONT_HERSHEY_SIMPLEX, max(0.5, font_size/26.0),
(0,0,0), thickness, cv2.LINE_AA)
return img
draw = ImageDraw.Draw(img_pil)
x, y = org
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
draw.text((x+dx, y+dy), text, font=font, fill=(255,255,255))
draw.text((x, y), text, font=font, fill=(0,0,0))
return np.array(img_pil)
# ============================================================
# 설정값
# ============================================================
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
CAP_WIDTH, CAP_HEIGHT, CAP_FPS = 1920, 1080, 40
#CAP_WIDTH, CAP_HEIGHT, CAP_FPS = 640, 480, 60
RECORD_USE_STAB = True
# ⭐ 디버깅 설정
DEBUG_MODE = True # False로 변경하면 디버깅 끄기
DEBUG_DETAIL = False # True로 변경하면 상세 디버깅 (매 프레임)
DEBUG_SERIAL_TEST = False # True로 변경하면 시리얼 테스트 모드
# 시리얼 포트 설정 (사용자 환경에 맞게 수정)
SERIAL_PORT = 'COM5' # ⭐ 여기를 수정하세요!
SERIAL_BAUD = 115200
# 시리얼 통신 진단
serial_health = {
"last_success_time": 0,
"consecutive_errors": 0,
"total_sent": 0,
"total_errors": 0,
"connection_lost": False
}
# 오버레이 3프레임마다 그리기
OVERLAY_EVERY = 1 # 3프레임마다만 draw_text_kr 실행
# 검출/추적
DETECT_EVERY = 2 # 1프레임 단위로 검출
LEAD_FACE_SEC = 0.12
CM_PER_PIXEL = 0.050
# 제어(로봇팔) - 방법 A
DESIRED_FACE_AREA = 35000
DEADZONE_XY = 60 # 화질에 따라 조정 필요
DEADZONE_AREA = 12000
move_ready = threading.Event()
move_ready.set()
motor_freeze_time = {"x": 0, "y": 0, "z": 0}
FREEZE_DURATION_S = 0.2 # 모터 프리즈 지속시간
# 중앙고정 & 줌
RATIO_TRANSLATE = 0.3 # 최대 이동 비율, 디지털 짐벌
# 정량지표
reacquire_t0 = None
metric1_times = [] # 재획득 시간 목록
metric1_speeds_px = []
metric1_speeds_cm = []
DT_THRESH_PX = 20.0 # 안정 판정 임계 이동량
STAB_WIN_SEC = 3.0
stab_buf = deque()
metric2_ratios = []
STOP_SPEED_THR = 10.0 #정지 판단 (px/s)
STOP_HOLD_START = 0.5 #정지 시작 후 유예
STOP_HOLD_SEC = 3.0 # 집계시간
icr3_phase = "idle"
icr3_center = None
icr3_t0 = 0.0
icr3_inside = 0
icr3_total = 0
ICR_RATIO = 0.03 # 지표3의 원 반경 화면 대각선 * 3%
CIRCLE_RADIUS_RATIO = 0.02 # 원의 반지름 비율 (화면 가로 기준)
ICR_RADIUS = 0.0
metric3_ratios = []
matric3_text = ""
_prev_cx, _prev_cy = None, None # 이전 프레임 좌표 (지표용)
_prev_t = None
# 디버깅 카운터
debug_counters = {
"frame_count": 0,
"face_detected": 0,
"face_lost": 0,
"serial_sent": 0,
"serial_error": 0,
"motor_frozen": 0
}
# ⭐ 추적 테스트 변수 (평가지표 3용)
test_mode_active = False
test_phase = "idle"
test_start_time = 0
test_stop_start_time = 0
test_coordinates = []
test_reference_point = None
# ⭐ 평가지표 2 테스트 변수
test2_mode_active = False
test2_phase = "idle"
test2_start_time = 0
test2_move_start_time = 0
test2_distances = [] # 이동량 기록
test2_coordinates = [] # 좌표 기록 (gcx, gcy)
test2_prev_cx = None # 이전 프레임 x 좌표 (테스트용)
test2_prev_cy = None # 이전 프레임 y 좌표 (테스트용)
test2_countdown_printed = {}
# ⭐ 평가지표 1 변수 (dh1_code.py 방식)
from collections import deque
FACE_PRESENCE_WINDOW_SEC = 0.5
FACE_PRESENCE_Q = deque()
tracking_test_mode = False
tracking_enabled = False
test_duration = 2.0
DETECTION_TIME = 2.0
def update_face_presence(now, present):
FACE_PRESENCE_Q.append((now, 1 if present else 0))
while FACE_PRESENCE_Q and (now - FACE_PRESENCE_Q[0][0]) > FACE_PRESENCE_WINDOW_SEC:
FACE_PRESENCE_Q.popleft()
def recent_face_ratio():
if not FACE_PRESENCE_Q:
return 0.0
s = sum(v for _, v in FACE_PRESENCE_Q)
return s * 100.0 / len(FACE_PRESENCE_Q)
def reset_test_mode(duration=2.0):
global tracking_test_mode, tracking_enabled, test_duration
tracking_test_mode = True
tracking_enabled = False
test_duration = duration
return {
"test_start_time": time.time(),
"countdown_printed": {
"wait2": False, "wait1": False, "start": False,
"3sec": False, "2sec": False, "1sec": False,
"move": False
},
"movement_start_time": None,
"face_detection_checked": False,
"last_move_second": -1,
"last_printed_time": -1.0
}
# ============================================================
# 디버깅 함수
# ============================================================
def debug_log(message, level="INFO", force=False):
"""
디버깅 메시지 출력
level: INFO, WARN, ERROR, DETAIL
force: True이면 DEBUG_MODE 무시하고 항상 출력
"""
if not DEBUG_MODE and not force:
return
if level == "DETAIL" and not DEBUG_DETAIL:
return
timestamp = time.strftime("%H:%M:%S")
if level == "ERROR":
prefix = "❌ [ERROR]"
elif level == "WARN":
prefix = "⚠️ [WARN]"
elif level == "DETAIL":
prefix = "🔍 [DETAIL]"
else:
prefix = "ℹ️ [INFO]"
print(f"{timestamp} {prefix} {message}")
# ============================================================
# 도우미 함수
# ============================================================
# 영상, 사진 저장
def get_new_filename(base_name="output", ext="avi"):
existing = os.listdir(desktop_path)
pat = re.compile(rf"{re.escape(base_name)}_(\d+)\.{re.escape(ext)}")
nums = [int(m.group(1)) for f in existing if (m := pat.match(f))]
n = max(nums, default=0) + 1
filename = os.path.join(desktop_path, f"{base_name}_{n}.{ext}")
debug_log(f"새 파일명 생성: {os.path.basename(filename)}", "DETAIL")
return filename
def get_new_image_filename(base_name="shot", ext="jpg"):
return get_new_filename(base_name, ext)
def est_speed_px_per_s(cx, cy, prev_cx, prev_cy, dt):
if prev_cx is None or dt <= 0:
return 0.0
dx = float(cx - prev_cx)
if dx < 5:
dx = 0
dy = float(cy - prev_cy)
if dy < 5:
dy = 0
speed = (dx*dx + dy*dy) ** 0.5 / max(dt, 1e-6)
if speed > 100 and DEBUG_DETAIL:
debug_log(f"높은 속도 감지: {speed:.1f} px/s", "DETAIL")
return speed
def should_freeze(axis, now):
frozen = now - motor_freeze_time[axis] < FREEZE_DURATION_S
if frozen:
debug_counters["motor_frozen"] += 1
# if DEBUG_DETAIL:
# debug_log(f"Freeze 활성: {axis}축", "DETAIL")
return frozen
def update_freeze_timer(ddx, ddy, ddz, now):
if ddx == 0:
motor_freeze_time["x"] = now
# debug_log(f"Freeze 타이머 시작: X축", "DETAIL")
if ddy == 0:
motor_freeze_time["y"] = now
# debug_log(f"Freeze 타이머 시작: Y축", "DETAIL")
if ddz == 0:
motor_freeze_time["z"] = now
# debug_log(f"Freeze 타이머 시작: Z축", "DETAIL")
# ============================================================
# 방법 A: 안전하고 빠른 Step 제어
# ============================================================
def compute_motor_angles_safe(center_x, center_y, area, frame_shape):
"""
거리별 차등 스텝 크기로 빠른 추적 + 안정성 확보
"""
frame_h, frame_w = frame_shape[:2]
dx = center_x - (frame_w // 2)
dy = center_y - (frame_h // 2)
step = 2;
# 데드존 처리
ddx = 0 if abs(dx) <= DEADZONE_XY else (-step if dx > 0 else step)
ddy = 0 if abs(dy) <= DEADZONE_XY else (-step if dy > 0 else step)
return {
"motor_1": -ddx,
"motor_2": 0,
"motor_3": -ddy,
"motor_4": 0,
"motor_5": 0,
"motor_6": 0,
"motor_7": 5
}
def clip_motor_angles(motor_cmds, limits=(-80, 80)):
clipped = {}
clipped_flag = False
for k, v_float in motor_cmds.items():
v = int(v_float)
if k == "motor_7":
clipped[k] = int(np.clip(v, 10, 500))
else:
original = v
v = int(np.clip(v, limits[0], limits[1]))
if v != original:
clipped_flag = True
debug_log(f"{k} 클리핑: {original} → {v}", "WARN")
clipped[k] = v
if clipped_flag:
debug_log(f"각도 제한 적용됨", "WARN")
return clipped
# ============================================================
# One Euro 필터
# ============================================================
class OneEuro:
def __init__(self, min_cutoff=0.8, beta=0.04, dcutoff=1.0):
self.min_cutoff = float(min_cutoff)
self.beta = float(beta)
self.dcutoff = float(dcutoff)
self.x_prev = None
self.dx_prev = 0.0
self.t_prev = None
debug_log(f"OneEuro 필터 초기화: cutoff={min_cutoff}, beta={beta}", "DETAIL")
@staticmethod
def alpha(cutoff, dt):
tau = 1.0 / (2.0 * np.pi * cutoff)
return 1.0 / (1.0 + tau / dt)
def filter(self, x, t):
if self.t_prev is None:
self.t_prev, self.x_prev = t, float(x)
return float(x)
dt = max(1e-3, t - self.t_prev)
dx = (x - self.x_prev) / dt
a_d = OneEuro.alpha(self.dcutoff, dt)
dx_hat = a_d * dx + (1 - a_d) * self.dx_prev
cutoff = self.min_cutoff + self.beta * abs(dx_hat)
a = OneEuro.alpha(cutoff, dt)
x_hat = a * x + (1 - a) * self.x_prev
self.t_prev, self.x_prev, self.dx_prev = t, x_hat, dx_hat
return float(x_hat)
# ============================================================
# 캡처 스레드
# ============================================================
class CaptureThread:
def __init__(self, cam_index=1, backend=cv2.CAP_DSHOW):
debug_log(f"카메라 초기화 시작: index={cam_index}", "INFO", force=True)
self.cap = cv2.VideoCapture(cam_index, backend)
# 포맷을 먼저 못박아 두는 게 협상 지연을 줄이는 데 도움됨
self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, CAP_WIDTH)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, CAP_HEIGHT)
self.cap.set(cv2.CAP_PROP_FPS, CAP_FPS)
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
self.cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.0) # 일부 장치는 0.25=auto, 0.0=manual (반대인 경우도 있어 둘 다 시도)
self.cap.set(cv2.CAP_PROP_EXPOSURE, -6) # 장치마다 -5~-8 범위 테스트
if not self.cap.isOpened():
debug_log("카메라 열기 실패!", "ERROR", force=True)
raise RuntimeError("카메라 열기 실패")
# 워밍업: 캡이 실제 스트리밍을 시작하도록 첫 0.5~1초간 프레임 버림
t0 = time.time()
# 워밍업: 초기 자동노출/포커스 안정화용
for _ in range(20): # 약 20프레임 버리기 (0.3~0.5초)
self.cap.grab()
actual_w = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
actual_h = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
actual_fps= self.cap.get(cv2.CAP_PROP_FPS)
debug_log(f"카메라 설정: {actual_w}x{actual_h} @ {actual_fps}fps", "INFO", force=True)
self.lock = threading.Lock()
self.latest = None
self.running = True
self.frame_count = 0
self.th = threading.Thread(target=self.loop, daemon=True)
self.th.start()
debug_log("캡처 스레드 시작됨", "INFO", force=True)
def loop(self):
# 오래된 프레임을 덜어내고, 디코딩 비용을 줄이기 위한 루프
DROP_OLD_FRAMES = True # 필요 없으면 False
while self.running:
if DROP_OLD_FRAMES:
for _ in range(3): # 프레임 3장 버리기
self.cap.grab()
# grab으로 캡처 → retrieve로 디코딩 (read()보다 유연)
ret = self.cap.grab()
if not ret:
debug_log("프레임 grab 실패", "WARN")
continue
ret, f = self.cap.retrieve()
if ret:
with self.lock:
self.latest = f
self.frame_count += 1
else:
debug_log("프레임 retrieve 실패", "WARN")
def read(self):
with self.lock:
if self.latest is None:
return False, None
return True, self.latest.copy()
def release(self):
debug_log(f"캡처 스레드 종료 (총 {self.frame_count} 프레임)", "INFO", force=True)
self.running = False
self.th.join(timeout=0.5)
self.cap.release()
# ============================================================
# 시리얼 워커 스레드 (통신 진단 강화)
# ============================================================
def serial_worker(q, port, baud):
global move_ready, debug_counters, serial_health
debug_log(f"시리얼 연결 시도: {port} @ {baud}bps", "INFO", force=True)
# 연결 시도
try:
ser = serial.Serial(port, baud, timeout=1)
time.sleep(2)
debug_log(f"시리얼 연결 완료: {port}", "INFO", force=True)
# ⭐ 연결 테스트
test_msg = "0,0,0,0,0,0,100\n"
ser.write(test_msg.encode('utf-8'))
debug_log(f"초기 테스트 신호 전송: {test_msg.strip()}", "INFO", force=True)
time.sleep(0.2)
# 아두이노 응답 확인 (옵션)
if ser.in_waiting > 0:
response = ser.readline().decode('utf-8', errors='ignore').strip()
debug_log(f"아두이노 응답: {response}", "INFO", force=True)
else:
debug_log(f"아두이노 응답 없음 (정상일 수 있음)", "WARN")
except serial.SerialException as e:
debug_log(f"시리얼 연결 실패: {e}", "ERROR", force=True)
debug_log(f"", "ERROR", force=True)
debug_log(f"🔧 문제 해결 방법:", "ERROR", force=True)
debug_log(f" 1. 장치 관리자에서 COM 포트 확인", "ERROR", force=True)
debug_log(f" 2. 아두이노 USB 재연결", "ERROR", force=True)
debug_log(f" 3. 아두이노 IDE 시리얼 모니터 닫기", "ERROR", force=True)
debug_log(f" 4. SERIAL_PORT 설정 확인 (현재: {port})", "ERROR", force=True)
serial_health["connection_lost"] = True
return
except Exception as e:
debug_log(f"알 수 없는 오류: {e}", "ERROR", force=True)
serial_health["connection_lost"] = True
return
# ⭐ 시리얼 테스트 모드
if DEBUG_SERIAL_TEST:
debug_log("", "INFO", force=True)
debug_log("=" * 70, "INFO", force=True)
debug_log("🧪 시리얼 테스트 모드 시작", "INFO", force=True)
debug_log("5초마다 테스트 신호를 전송합니다.", "INFO", force=True)
debug_log("아두이노 시리얼 모니터를 열어 데이터를 확인하세요!", "INFO", force=True)
debug_log("=" * 70, "INFO", force=True)
debug_log("", "INFO", force=True)
test_count = 0
try:
while True:
test_count += 1
test_values = [test_count % 10, 0, test_count % 10, 0, 0, 0, 1000]
test_msg = ','.join(map(str, test_values)) + '\n'
debug_log(f"", "INFO", force=True)
debug_log(f"[테스트 #{test_count}] 전송: {test_msg.strip()}", "INFO", force=True)
try:
ser.write(test_msg.encode('utf-8'))
debug_log(f" ✅ 전송 성공", "INFO", force=True)
# 아두이노 응답 확인
time.sleep(0.1)
if ser.in_waiting > 0:
response = ser.readline().decode('utf-8', errors='ignore').strip()
debug_log(f" 📩 아두이노 응답: {response}", "INFO", force=True)
else:
debug_log(f" 📭 아두이노 응답 없음", "WARN", force=True)
except Exception as e:
debug_log(f" ❌ 전송 실패: {e}", "ERROR", force=True)
time.sleep(5)
except KeyboardInterrupt:
debug_log("", "INFO", force=True)
debug_log("테스트 모드 종료", "INFO", force=True)
ser.close()
return
# 정상 동작 모드
serial_health["last_success_time"] = time.time()
try:
while True:
motor_cmds = q.get()
if motor_cmds is None:
debug_log("시리얼 종료 신호 수신", "INFO", force=True)
break
# 최신 명령만 사용 (큐 비우기)
skip_count = 0
while not q.empty():
latest = q.get_nowait()
if latest is not None:
motor_cmds = latest
skip_count += 1
else:
break
if skip_count > 0:
debug_log(f"큐에서 {skip_count}개 명령 건너뜀", "DETAIL")
if motor_cmds is None:
break
try:
# motor_1 ~ motor_7 값 전송
vals = [motor_cmds.get(f"motor_{i}", 0) for i in range(1, 8)]
message = ','.join(map(str, vals)) + '\n'
# ⭐ 전송 시도
ser.write(message.encode('utf-8'))
serial_health["total_sent"] += 1
serial_health["last_success_time"] = time.time()
serial_health["consecutive_errors"] = 0
debug_counters["serial_sent"] += 1
debug_log(f"시리얼 전송 #{debug_counters['serial_sent']}: {message.strip()}", "DETAIL")
# ⭐ 주기적인 통신 상태 체크 (100번마다)
if debug_counters["serial_sent"] % 100 == 0:
elapsed = time.time() - serial_health["last_success_time"]
error_rate = (serial_health["total_errors"] / serial_health["total_sent"] * 100) if serial_health["total_sent"] > 0 else 0
if error_rate > 5:
debug_log(f"⚠️ 시리얼 오류율 높음: {error_rate:.1f}% ({serial_health['total_errors']}/{serial_health['total_sent']})", "WARN")
else:
debug_log(f"✅ 시리얼 통신 양호: 오류율 {error_rate:.1f}%", "INFO")
# delay 대기 (move_ready 플래그)
delay_ms = motor_cmds.get("motor_7", 50)
move_ready.clear()
time.sleep(delay_ms / 1000.0)
move_ready.set()
except serial.SerialException as e:
serial_health["total_errors"] += 1
serial_health["consecutive_errors"] += 1
debug_counters["serial_error"] += 1
debug_log(f"시리얼 쓰기 오류 #{debug_counters['serial_error']}: {e}", "ERROR", force=True)
# ⭐ 연속 오류 감지
if serial_health["consecutive_errors"] >= 5:
debug_log(f"", "ERROR", force=True)
debug_log(f"❌ 심각: 연속 {serial_health['consecutive_errors']}회 오류!", "ERROR", force=True)
debug_log(f"", "ERROR", force=True)
debug_log(f"🔧 가능한 원인:", "ERROR", force=True)
debug_log(f" 1. USB 케이블 불량 또는 연결 불안정", "ERROR", force=True)
debug_log(f" 2. 아두이노 전원 부족", "ERROR", force=True)
debug_log(f" 3. 아두이노 처리 속도 느림 (버퍼 오버플로우)", "ERROR", force=True)
debug_log(f" 4. 아두이노 코드에서 Serial.read() 안 함", "ERROR", force=True)
debug_log(f"", "ERROR", force=True)
debug_log(f"💡 해결 시도:", "ERROR", force=True)
debug_log(f" - USB 재연결", "ERROR", force=True)
debug_log(f" - 아두이노 리셋", "ERROR", force=True)
debug_log(f" - delay 값 증가 (45 → 100)", "ERROR", force=True)
debug_log(f"", "ERROR", force=True)
serial_health["connection_lost"] = True
break
except Exception as e:
serial_health["total_errors"] += 1
debug_counters["serial_error"] += 1
debug_log(f"예상치 못한 오류 #{debug_counters['serial_error']}: {e}", "ERROR", force=True)
finally:
ser.close()
debug_log(f"시리얼 종료 (전송: {serial_health['total_sent']}회, "
f"오류: {serial_health['total_errors']}회)", "INFO", force=True)
# 최종 진단
if serial_health["total_sent"] > 0:
error_rate = (serial_health["total_errors"] / serial_health["total_sent"] * 100)
if error_rate > 10:
debug_log(f"", "WARN", force=True)
debug_log(f"⚠️ 시리얼 통신 품질 나쁨: 오류율 {error_rate:.1f}%", "WARN", force=True)
debug_log(f" 하드웨어 연결 상태를 확인하세요!", "WARN", force=True)
elif error_rate > 0:
debug_log(f"✅ 시리얼 통신 정상 종료: 오류율 {error_rate:.1f}%", "INFO", force=True)
else:
debug_log(f"✅ 시리얼 통신 완벽: 오류 없음!", "INFO", force=True)
# ============================================================
# 얼굴 DNN
# ============================================================
prototxt_path = r"C:\face_models\deploy.prototxt"
model_path = r"C:\face_models\res10_300x300_ssd_iter_140000.caffemodel"
debug_log("DNN 모델 로드 시작", "INFO", force=True)
debug_log(f" prototxt: {prototxt_path}", "DETAIL")
debug_log(f" model: {model_path}", "DETAIL")
try:
net = cv2.dnn.readNetFromCaffe(prototxt_path, model_path)
debug_log("DNN 모델 로드 성공", "INFO", force=True)
except Exception as e:
debug_log(f"DNN 모델 로드 실패: {e}", "ERROR", force=True)
raise
def detect_faces_dnn(frame, conf_thresh=0.5):
frame_h, frame_w = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300,300)), 1.0, (300,300), (104.0,177.0,123.0))
net.setInput(blob)
det = net.forward()
boxes = []
for i in range(det.shape[2]):
conf = float(det[0,0,i,2])
if conf > conf_thresh:
x1,y1,x2,y2 = (det[0,0,i,3:7] * np.array([frame_w,frame_h,frame_w,frame_h])).astype(int)
x1,y1,x2,y2 = max(0,x1),max(0,y1),min(frame_w-1,x2),min(frame_h-1,y2)
boxes.append((x1,y1,x2-x1,y2-y1))
debug_log(f"얼굴 검출: conf={conf:.2f}, bbox=({x1},{y1},{x2-x1},{y2-y1})", "DETAIL")
if boxes:
debug_counters["face_detected"] += 1
return boxes
# ============================================================
# 칼만 필터
# ============================================================
def init_kalman():
debug_log("칼만 필터 초기화", "INFO")
kf = cv2.KalmanFilter(4,2)
kf.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]], np.float32)
kf.processNoiseCov = np.diag([1e-2,1e-2,1e-1,1e-1]).astype(np.float32)
kf.measurementNoiseCov = np.diag([2.0,2.0]).astype(np.float32)
kf.errorCovPost = np.diag([10,10,10,10]).astype(np.float32)
return kf
def kalman_predict(kf, dt):
kf.transitionMatrix = np.array([[1,0,dt,0],[0,1,0,dt],[0,0,1,0],[0,0,0,1]], np.float32)
pred = kf.predict()
px, py = int(pred[0,0]), int(pred[1,0])
debug_log(f"칼만 예측: ({px}, {py})", "DETAIL")
return px, py
def kalman_correct(kf, x, y):
kf.correct(np.array([[np.float32(x)],[np.float32(y)]], np.float32))
cx, cy = int(kf.statePost[0,0]), int(kf.statePost[1,0])
debug_log(f"칼만 보정: 측정=({x},{y}) → 추정=({cx},{cy})", "DETAIL")
# ============================================================
# 메인
# ============================================================
def main():
global icr3_phase, icr3_center, icr3_t0, icr3_inside, icr3_total
global _prev_cx, _prev_cy, _prev_t, reacquire_t0, ICR_RADIUS, matric3_text
global debug_counters
global test_mode_active, test_phase, test_start_time, test_stop_start_time
global test_coordinates, test_reference_point
global test2_mode_active, test2_phase, test2_start_time, test2_move_start_time
global test2_distances, test2_coordinates, test2_prev_cx, test2_prev_cy, test2_countdown_printed
global tracking_test_mode, tracking_enabled, test_duration
print("\n" + "=" * 70)
print("🎥 얼굴 추적 로봇팔 제어 시스템 (방법 A)")
print("=" * 70)
print(f"디버깅 모드: {'🟢 ON' if DEBUG_MODE else '🔴 OFF'}")
if DEBUG_MODE:
print(f"상세 디버깅: {'🟢 ON' if DEBUG_DETAIL else '🔴 OFF'}")
if DEBUG_SERIAL_TEST:
print(f"시리얼 테스트 모드: 🟢 ON")
print(" → 5초마다 테스트 신호를 전송합니다.")
print(" → 아두이노 시리얼 모니터를 열어 확인하세요!")
print("=" * 70)
print("키 조작:")
print(" i : 평가지표 1 테스트 (얼굴 검출 비율)")
print(" p : 평가지표 2 테스트 (이동량 안정성)")
print(" o : 평가지표 3 테스트 (원 내부 비율)")
print(" s : 녹화 시작")
print(" e : 녹화 종료")
print(" 1~9 : 연속 촬영")
print(" q : 종료")
print("=" * 70)
print()
# ⭐ 시리얼 테스트 모드일 때는 카메라 없이 실행
if DEBUG_SERIAL_TEST:
debug_log("시리얼 테스트 전용 모드 시작", "INFO", force=True)
q = queue.Queue()
serial_thread = threading.Thread(target=serial_worker, args=(q, SERIAL_PORT, SERIAL_BAUD), daemon=True)
serial_thread.start()
try:
serial_thread.join() # 시리얼 스레드가 끝날 때까지 대기
except KeyboardInterrupt:
debug_log("KeyboardInterrupt - 종료", "INFO", force=True)
finally:
q.put(None)
return
# 스레드 준비
q = queue.Queue()
threading.Thread(target=serial_worker, args=(q, SERIAL_PORT, SERIAL_BAUD), daemon=True).start()
cap_thread = CaptureThread()
# ⭐ 평가지표 1 테스트 변수
test1_vars = {
"test_start_time": None,
"countdown_printed": {},
"movement_start_time": None,
"face_detection_checked": False,
"last_move_second": -1,
"last_printed_time": -1.0
}
# ⭐ 평가지표 3 테스트 변수
test3_countdown_printed = {}
print("\n" + "=" * 70)
print("🧪 추적 성능 테스트")
print("=" * 70)
print("📌 'i' 키: 평가지표 1 (얼굴 검출 비율 테스트)")
print("📌 'p' 키: 평가지표 2 (이동량 안정성 테스트)")
print("📌 'o' 키: 평가지표 3 (원 내부 비율 테스트)")
print("=" * 70)
print()
# 비디오 저장
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
recording, out = False, None
# 상태
kf = init_kalman()
kalman_inited = False
last_kf_ts = time.time()
# 표시 스무딩
cx_oe = OneEuro(0.9, 0.04, 1.2)
cy_oe = OneEuro(0.9, 0.05, 1.2)
# 모터 제어 스무딩 (더 강한 필터)
motor_cx_oe = OneEuro(0.4, 0.02, 1.0)
motor_cy_oe = OneEuro(0.4, 0.02, 1.0)
ever_locked = False
LOG_INTERVAL, last_log = 0.3, 0.0
# 연속촬영
photo_interval = 3.0
photo_shooting = False
photo_count = 0
photo_taken = 0
next_shot_at = 0.0
MSG_DUR = 1.2
msg_lt_text, msg_lt_until = "", 0.0
msg_lt_display = False
msg_rt_text, msg_rt_until = "", 0.0
msg_rt_display = False
face_boxes_preFrame = []
debug_log("메인 루프 시작", "INFO", force=True)
print()
try:
frame_idx = 0
frame_per_sec = 0
frame_idx_per_sec = 0
sum_time_per_sec = 0
box_l=box_t=box_w=box_h=box_cx=box_cy=0
area = 0
pre_frame_time = 0
##-----------------------------------------------------------------------------------------
## 251025_MJ_떨림 보정을 위한 이전과 현재 Frame의 Data
##-----------------------------------------------------------------------------------------
pre_gray = None # 이전 Frame Image (알고리즘 속도를 위해 Color가 아닌 Gray 영상으로 저장)
cur_gray = None # 현재 Frame Image (알고리즘 속도를 위해 Color가 아닌 Gray 영상으로 저장)
pre_pts = None # 이전 Frame의 Feature Point 위치
cur_pts = None # 현재 Frame의 Feature Point 위치
comp_frame_cx = 0 # 떨림 보정을 위한 Frame Center X
comp_frame_cy = 0 # 떨림 보정을 위한 Frame Center Y
##-----------------------------------------------------------------------------------------
while True:
ok, frame = cap_thread.read()
if not ok:
# debug_log("프레임 읽기 실패", "WARN")
continue
frame_resize = cv2.resize(frame, (100,100))
cur_gray = cv2.cvtColor(frame_resize,cv2.COLOR_BGR2GRAY)
now = time.time()
debug_counters["frame_count"] += 1
# ⭐⭐⭐ 평가지표 1 카운트다운 로직 (dh1_code.py 방식) ⭐⭐⭐
if tracking_test_mode and test1_vars["test_start_time"] is not None:
elapsed = now - test1_vars["test_start_time"]
countdown_printed = test1_vars["countdown_printed"]
movement_start_time = test1_vars["movement_start_time"]
face_detection_checked = test1_vars["face_detection_checked"]
last_move_second = test1_vars["last_move_second"]
last_printed_time = test1_vars["last_printed_time"]
if not countdown_printed.get("wait2") and elapsed >= 0:
print("⏳ 2초 대기 중...")
countdown_printed["wait2"] = True
if not countdown_printed.get("wait1") and elapsed >= 1:
print("⏳ 1초 대기 중...")
countdown_printed["wait1"] = True
if not countdown_printed.get("start") and elapsed >= 2:
print("🔔 카운터 시작")
countdown_printed["start"] = True
if not countdown_printed.get("3sec") and elapsed >= 3:
print("⏱️ 3초")
countdown_printed["3sec"] = True
if not countdown_printed.get("2sec") and elapsed >= 4:
print("⏱️ 2초")
countdown_printed["2sec"] = True
if not countdown_printed.get("1sec") and elapsed >= 5:
print("⏱️ 1초")
countdown_printed["1sec"] = True
if not countdown_printed.get("move") and elapsed >= 6:
print(f"\n🚀 움직임 시작! 지금 좌우로 움직이세요! (테스트 시간: {test_duration}초)\n")
test1_vars["movement_start_time"] = now
movement_start_time = now
tracking_enabled = True
test1_vars["last_move_second"] = -1
test1_vars["last_printed_time"] = -1.0
debug_log("로봇팔 추적 활성화됨", "INFO", force=True)
countdown_printed["move"] = True
# 움직임 경과 시간 출력
if movement_start_time and not face_detection_checked:
elapsed_move = now - movement_start_time
current_second = int(elapsed_move)
if current_second > test1_vars["last_move_second"] and current_second < int(test_duration):
print(f"⏱️ 움직임 경과: {current_second}초")
test1_vars["last_move_second"] = current_second
if elapsed_move >= test_duration and test1_vars["last_printed_time"] < test_duration:
print(f"⏱️ 움직임 경과: {test_duration}초")
test1_vars["last_printed_time"] = test_duration
# 얼굴 검출 체크 (항상 2초 후)
if movement_start_time and not face_detection_checked and (now - movement_start_time) >= DETECTION_TIME:
if (now - movement_start_time) >= (DETECTION_TIME + 0.2):
test1_vars["face_detection_checked"] = True
print(f"⏱️ {DETECTION_TIME + 0.2:.1f}초 경과 - 추적 결과 확인 중...\n")
ratio = recent_face_ratio()
face_detected = (ratio >= 60.0)
print("=" * 70)
print("📊 평가지표 1 - 추적 테스트 결과")
print("=" * 70)
print(f"⏱️ 움직임 시간: {test_duration}초")
print(f"⏱️ 검출 체크 시간: {DETECTION_TIME}초")
print(f"🎯 얼굴 검출 비율: {ratio:.1f}%")
if face_detected:
print("✅ 성공: 로봇팔이 사용자를 성공적으로 추적했습니다!")
print(f" → {DETECTION_TIME}초 후에도 얼굴이 카메라 영역 내에 유지되었습니다.")
else:
print("❌ 실패: 로봇팔이 사용자를 놓쳤습니다!")
print(f" → {DETECTION_TIME}초 후 얼굴이 카메라 영역을 벗어났습니다.")
print("=" * 70)
print("🔄 정상 추적 모드로 전환합니다...")
print("💡 'i' 키를 눌러 다시 테스트할 수 있습니다.\n")
tracking_test_mode = False
# ⭐⭐⭐ 평가지표 2 카운트다운 로직 (이동량 안정성) ⭐⭐⭐
if test2_mode_active:
elapsed_test2 = now - test2_start_time
if test2_phase == "waiting":
if not test2_countdown_printed.get("3sec") and elapsed_test2 >= 1:
print("⏱️ 3초")
test2_countdown_printed["3sec"] = True
if not test2_countdown_printed.get("2sec") and elapsed_test2 >= 2:
print("⏱️ 2초")
test2_countdown_printed["2sec"] = True
if not test2_countdown_printed.get("1sec") and elapsed_test2 >= 3:
print("⏱️ 1초")
test2_countdown_printed["1sec"] = True
if not test2_countdown_printed.get("move_start") and elapsed_test2 >= 4:
print("\n🚀 사용자 움직임 시작! 지금 좌우 또는 상하로 움직이세요! (3초)\n")
test2_phase = "moving"
test2_move_start_time = now
test2_countdown_printed["move_start"] = True
if test2_phase == "moving":
move_elapsed = now - test2_move_start_time
if not test2_countdown_printed.get("moving_2sec") and move_elapsed >= 1:
print("⏱️ 2초")
test2_countdown_printed["moving_2sec"] = True
if not test2_countdown_printed.get("moving_1sec") and move_elapsed >= 2:
print("⏱️ 1초")
test2_countdown_printed["moving_1sec"] = True
if move_elapsed < 3.0: # 3초간 이동량 수집
# ⭐ 화면에 표시되는 좌표(gcx, gcy)를 사용하여 측정
if face_found:
# 좌표 기록
test2_coordinates.append((gcx, gcy))
# 이전 프레임과의 거리 계산 (테스트용 이전 좌표 사용)
if test2_prev_cx is not None:
dist = ((gcx - test2_prev_cx)**2 + (gcy - test2_prev_cy)**2) ** 0.5
test2_distances.append(dist)
# 테스트용 이전 좌표 업데이트
test2_prev_cx = gcx
test2_prev_cy = gcy
elif move_elapsed >= 3.0:
test2_mode_active = False
test2_phase = "done"
if len(test2_distances) > 0:
stable_count = sum(1 for d in test2_distances if d <= DT_THRESH_PX)
total_count = len(test2_distances)
ratio = (stable_count / total_count * 100) if total_count > 0 else 0
# 통계 계산
min_dist = min(test2_distances)
max_dist = max(test2_distances)
avg_dist = sum(test2_distances) / len(test2_distances)
print("=" * 70)
print("📊 평가지표 2 - 이동량 안정성 테스트 결과")
print("=" * 70)
print(f"📍 수집된 프레임 개수: {total_count}개")
print(f"📏 임계값: {DT_THRESH_PX}px")
print(f"📐 이동량 통계: 최소={min_dist:.2f}px, 평균={avg_dist:.2f}px, 최대={max_dist:.2f}px")
print(f"✅ 임계값 이하 프레임: {stable_count}개")
print(f"❌ 임계값 초과 프레임: {total_count - stable_count}개")
print(f"📈 안정성 비율: {ratio:.2f}%")
print("=" * 70)
# ⭐ 목표 80% 달성 여부
if ratio >= 80:
print("✅ 목표 달성! 매우 안정적인 추적!")
elif ratio >= 70:
print("🟢 양호: 목표에 근접한 추적 (70% 이상)")
elif ratio >= 60:
print("🟡 보통: 추적 성능 개선 필요 (60~70%)")
else:
print("🔴 불량: 추적 안정성이 낮음 (60% 미만)")
# ⭐ 수집된 좌표 출력
print("\n" + "=" * 70)
print("📍 수집된 좌표 목록 (gcx, gcy)")
print("=" * 70)
for idx, (cx, cy) in enumerate(test2_coordinates, 1):
# 이동량도 함께 출력 (첫 번째 좌표는 이동량 없음)
if idx == 1:
print(f"{idx:3d}. ({cx:4.0f}, {cy:4.0f})")
else:
# 실제 측정된 이동량 사용 (test2_distances는 좌표보다 1개 적음)
dist = test2_distances[idx-2] # idx-2: 좌표 인덱스와 맞춤
status = "✅" if dist <= DT_THRESH_PX else "❌"
print(f"{idx:3d}. ({cx:4.0f}, {cy:4.0f}) - 이동량: {dist:6.2f}px {status}")
print("=" * 70)
print("\n정상 모드로 전환합니다...")
print("💡 'p' 키를 눌러 다시 테스트할 수 있습니다.\n")
else:
print("⚠️ 테스트 실패: 이동량을 수집하지 못했습니다.")
print(" 얼굴이 검출되지 않았거나 추적이 실패했습니다.\n")