-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path02_real_data_size_hist.py
More file actions
executable file
·1951 lines (1780 loc) · 73.4 KB
/
02_real_data_size_hist.py
File metadata and controls
executable file
·1951 lines (1780 loc) · 73.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
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
#!/usr/bin/env python
from __future__ import annotations
import warnings
warnings.filterwarnings('ignore')
import os
import sys
import copy
import cv2
import math
import time
from pprint import pprint
import numpy as np
from enum import Enum
from pathlib import Path
from dataclasses import dataclass, field
from argparse import ArgumentParser, ArgumentTypeError
from typing import Tuple, Optional, List, Dict, Any
import importlib.util
from collections import Counter
from abc import ABC, abstractmethod
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
AVERAGE_HEAD_WIDTH: float = 0.16 + 0.10 # 16cm + Margin Compensation
BOX_COLORS = [
[(216, 67, 21),"Front"],
[(255, 87, 34),"Right-Front"],
[(123, 31, 162),"Right-Side"],
[(255, 193, 7),"Right-Back"],
[(76, 175, 80),"Back"],
[(33, 150, 243),"Left-Back"],
[(156, 39, 176),"Left-Side"],
[(0, 188, 212),"Left-Front"],
]
# The pairs of classes you want to join
# (there is some overlap because there are left and right classes)
EDGES = [
(21, 22), (21, 22), # collarbone -> shoulder (left and right)
(21, 23), # collarbone -> solar_plexus
(22, 24), (22, 24), # shoulder -> elbow (left and right)
(22, 30), (22, 30), # shoulder -> hip_joint (left and right)
(24, 25), (24, 25), # elbow -> wrist (left and right)
(23, 29), # solar_plexus -> abdomen
(29, 30), (29, 30), # abdomen -> hip_joint (left and right)
(30, 31), (30, 31), # hip_joint -> knee (left and right)
(31, 32), (31, 32), # knee -> ankle (left and right)
]
class Color(Enum):
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
COLOR_DEFAULT = '\033[39m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
INVISIBLE = '\033[08m'
REVERSE = '\033[07m'
BG_BLACK = '\033[40m'
BG_RED = '\033[41m'
BG_GREEN = '\033[42m'
BG_YELLOW = '\033[43m'
BG_BLUE = '\033[44m'
BG_MAGENTA = '\033[45m'
BG_CYAN = '\033[46m'
BG_WHITE = '\033[47m'
BG_DEFAULT = '\033[49m'
RESET = '\033[0m'
def __str__(self):
return self.value
def __call__(self, s):
return str(self) + str(s) + str(Color.RESET)
@dataclass(frozen=False)
class Box():
classid: int
score: float
x1: int
y1: int
x2: int
y2: int
cx: int
cy: int
generation: int = -1 # -1: Unknown, 0: Adult, 1: Child
gender: int = -1 # -1: Unknown, 0: Male, 1: Female
handedness: int = -1 # -1: Unknown, 0: Left, 1: Right
head_pose: int = -1 # -1: Unknown, 0: Front, 1: Right-Front, 2: Right-Side, 3: Right-Back, 4: Back, 5: Left-Back, 6: Left-Side, 7: Left-Front
is_used: bool = False
person_id: int = -1
track_id: int = -1
class SimpleSortTracker:
"""Minimal SORT-style tracker based on IoU matching."""
def __init__(self, iou_threshold: float = 0.3, max_age: int = 30) -> None:
self.iou_threshold = iou_threshold
self.max_age = max_age
self.next_track_id = 1
self.tracks: List[Dict[str, Any]] = []
self.frame_index = 0
@staticmethod
def _iou(bbox_a: Tuple[int, int, int, int], bbox_b: Tuple[int, int, int, int]) -> float:
ax1, ay1, ax2, ay2 = bbox_a
bx1, by1, bx2, by2 = bbox_b
inter_x1 = max(ax1, bx1)
inter_y1 = max(ay1, by1)
inter_x2 = min(ax2, bx2)
inter_y2 = min(ay2, by2)
inter_w = max(0, inter_x2 - inter_x1)
inter_h = max(0, inter_y2 - inter_y1)
if inter_w == 0 or inter_h == 0:
return 0.0
inter_area = inter_w * inter_h
area_a = max(0, ax2 - ax1) * max(0, ay2 - ay1)
area_b = max(0, bx2 - bx1) * max(0, by2 - by1)
union = area_a + area_b - inter_area
if union <= 0:
return 0.0
return float(inter_area / union)
def update(self, boxes: List[Box]) -> None:
self.frame_index += 1
for box in boxes:
box.track_id = -1
if not boxes and not self.tracks:
return
iou_matrix = None
if self.tracks and boxes:
iou_matrix = np.zeros((len(self.tracks), len(boxes)), dtype=np.float32)
for t_idx, track in enumerate(self.tracks):
track_bbox = track['bbox']
for d_idx, box in enumerate(boxes):
det_bbox = (box.x1, box.y1, box.x2, box.y2)
iou_matrix[t_idx, d_idx] = self._iou(track_bbox, det_bbox)
matched_tracks: set[int] = set()
matched_detections: set[int] = set()
matches: List[Tuple[int, int]] = []
if iou_matrix is not None and iou_matrix.size > 0:
while True:
best_track = -1
best_det = -1
best_iou = self.iou_threshold
for t_idx in range(len(self.tracks)):
if t_idx in matched_tracks:
continue
for d_idx in range(len(boxes)):
if d_idx in matched_detections:
continue
iou = float(iou_matrix[t_idx, d_idx])
if iou > best_iou:
best_iou = iou
best_track = t_idx
best_det = d_idx
if best_track == -1:
break
matched_tracks.add(best_track)
matched_detections.add(best_det)
matches.append((best_track, best_det))
for t_idx, d_idx in matches:
track = self.tracks[t_idx]
det_box = boxes[d_idx]
track['bbox'] = (det_box.x1, det_box.y1, det_box.x2, det_box.y2)
track['missed'] = 0
track['last_seen'] = self.frame_index
det_box.track_id = track['id']
surviving_tracks: List[Dict[str, Any]] = []
for idx, track in enumerate(self.tracks):
if idx in matched_tracks:
surviving_tracks.append(track)
continue
track['missed'] += 1
if track['missed'] <= self.max_age:
surviving_tracks.append(track)
self.tracks = surviving_tracks
for d_idx, det_box in enumerate(boxes):
if d_idx in matched_detections:
continue
track_id = self.next_track_id
self.next_track_id += 1
det_box.track_id = track_id
self.tracks.append(
{
'id': track_id,
'bbox': (det_box.x1, det_box.y1, det_box.x2, det_box.y2),
'missed': 0,
'last_seen': self.frame_index,
}
)
if not boxes:
return
@dataclass
class EyeAnalysisStats:
total_frames: int = 0
frames_with_eye: int = 0
frames_without_eye: int = 0
frames_over_detect: int = 0
widths: List[int] = field(default_factory=list)
heights: List[int] = field(default_factory=list)
def register_frame(self, eye_boxes: List[Box]) -> None:
self.total_frames += 1
if eye_boxes:
self.frames_with_eye += 1
else:
self.frames_without_eye += 1
if len(eye_boxes) >= 3:
self.frames_over_detect += 1
for eye_box in eye_boxes:
width = max(0, eye_box.x2 - eye_box.x1)
height = max(0, eye_box.y2 - eye_box.y1)
if width > 0 and height > 0:
self.widths.append(width)
self.heights.append(height)
@property
def has_measurements(self) -> bool:
return bool(self.widths and self.heights)
def sanitize_label(label: str) -> str:
if not label:
return 'dataset'
sanitized = ''.join(ch if ch.isalnum() or ch in ('-', '_') else '_' for ch in label)
return sanitized or 'dataset'
def plot_eye_histograms(
widths: List[int],
heights: List[int],
*,
dataset_label: str,
output_path: Path,
) -> Dict[str, Dict[str, float]]:
if not widths and not heights:
return {}
output_path.parent.mkdir(parents=True, exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
stats: Dict[str, Dict[str, float]] = {}
def _plot_axis(
ax,
values: List[int],
title: str,
xlabel: str,
) -> Dict[str, float]:
if not values:
ax.set_title(f'{title} (no data)')
ax.set_xlabel(xlabel)
ax.set_ylabel('Frequency')
ax.text(0.5, 0.5, 'No detections', transform=ax.transAxes, ha='center', va='center', fontsize=11)
return {}
values_array = np.asarray(values, dtype=np.float32)
mean_val = float(np.mean(values_array))
median_val = float(np.median(values_array))
unique_value_count = len(np.unique(values_array))
bins = min(50, max(10, unique_value_count))
ax.hist(values_array, bins=bins, color='#1f77b4', alpha=0.75, edgecolor='black')
ax.axvline(mean_val, color='#ff7f0e', linestyle='--', linewidth=2, label=f'Mean: {mean_val:.2f}')
ax.axvline(median_val, color='#2ca02c', linestyle='-.', linewidth=2, label=f'Median: {median_val:.2f}')
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel('Frequency')
ax.legend()
return {
'mean': mean_val,
'median': median_val,
}
stats['width'] = _plot_axis(
axes[0],
widths,
title='Eye Bounding Box Width',
xlabel='Width (pixels)',
)
stats['height'] = _plot_axis(
axes[1],
heights,
title='Eye Bounding Box Height',
xlabel='Height (pixels)',
)
fig.suptitle(f'Eye Bounding Box Size Distribution ({dataset_label})', fontsize=14)
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
fig.savefig(str(output_path))
plt.close(fig)
return stats
class AbstractModel(ABC):
"""AbstractModel
Base class of the model.
"""
_runtime: str = 'onnx'
_model_path: str = ''
_obj_class_score_th: float = 0.35
_attr_class_score_th: float = 0.70
_input_shapes: List[List[int]] = []
_input_names: List[str] = []
_output_shapes: List[List[int]] = []
_output_names: List[str] = []
# onnx/tflite
_interpreter = None
_inference_model = None
_providers = None
_swap = (2, 0, 1)
_h_index = 2
_w_index = 3
# onnx
_onnx_dtypes_to_np_dtypes = {
"tensor(float)": np.float32,
"tensor(uint8)": np.uint8,
"tensor(int8)": np.int8,
}
# tflite
_input_details = None
_output_details = None
@abstractmethod
def __init__(
self,
*,
runtime: Optional[str] = 'onnx',
model_path: Optional[str] = '',
obj_class_score_th: Optional[float] = 0.35,
attr_class_score_th: Optional[float] = 0.70,
keypoint_th: Optional[float] = 0.25,
providers: Optional[List] = [
(
'TensorrtExecutionProvider', {
'trt_engine_cache_enable': True,
'trt_engine_cache_path': '.',
'trt_fp16_enable': True,
# onnxruntime>=1.21.0 breaking changes
# https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#data-dependant-shape-dds-ops
# https://github.com/microsoft/onnxruntime/pull/22681/files
# https://github.com/microsoft/onnxruntime/pull/23893/files
'trt_op_types_to_exclude': 'NonMaxSuppression,NonZero,RoiAlign',
}
),
'CUDAExecutionProvider',
'CPUExecutionProvider',
],
):
self._runtime = runtime
self._model_path = model_path
self._obj_class_score_th = obj_class_score_th
self._attr_class_score_th = attr_class_score_th
self._keypoint_th = keypoint_th
self._providers = providers
# Model loading
if self._runtime == 'onnx':
import onnxruntime # type: ignore
onnxruntime.set_default_logger_severity(3) # ERROR
session_option = onnxruntime.SessionOptions()
session_option.log_severity_level = 3
self._interpreter = \
onnxruntime.InferenceSession(
model_path,
sess_options=session_option,
providers=providers,
)
self._providers = self._interpreter.get_providers()
print(f'{Color.GREEN("Enabled ONNX ExecutionProviders:")}')
pprint(f'{self._providers}')
self._input_names = [
input.name for input in self._interpreter.get_inputs()
]
self._input_dtypes = [
self._onnx_dtypes_to_np_dtypes[input.type] for input in self._interpreter.get_inputs()
]
self._output_shapes = [
output.shape for output in self._interpreter.get_outputs()
]
self._output_names = [
output.name for output in self._interpreter.get_outputs()
]
self._model = self._interpreter.run
self._swap = (2, 0, 1)
self._h_index = 2
self._w_index = 3
elif self._runtime in ['ai_edge_litert', 'tensorflow']:
if self._runtime == 'ai_edge_litert':
from ai_edge_litert.interpreter import Interpreter
self._interpreter = Interpreter(model_path=model_path)
elif self._runtime == 'tensorflow':
import tensorflow as tf # type: ignore
self._interpreter = tf.lite.Interpreter(model_path=model_path)
self._input_details = self._interpreter.get_input_details()
self._output_details = self._interpreter.get_output_details()
self._input_names = [
input.get('name', None) for input in self._input_details
]
self._input_dtypes = [
input.get('dtype', None) for input in self._input_details
]
self._output_shapes = [
output.get('shape', None) for output in self._output_details
]
self._output_names = [
output.get('name', None) for output in self._output_details
]
self._model = self._interpreter.get_signature_runner()
self._swap = (0, 1, 2)
self._h_index = 1
self._w_index = 2
@abstractmethod
def __call__(
self,
*,
input_datas: List[np.ndarray],
) -> List[np.ndarray]:
datas = {
f'{input_name}': input_data \
for input_name, input_data in zip(self._input_names, input_datas)
}
if self._runtime == 'onnx':
outputs = [
output for output in \
self._model(
output_names=self._output_names,
input_feed=datas,
)
]
return outputs
elif self._runtime in ['ai_edge_litert', 'tensorflow']:
outputs = [
output for output in \
self._model(
**datas
).values()
]
return outputs
@abstractmethod
def _preprocess(
self,
*,
image: np.ndarray,
swap: Optional[Tuple[int,int,int]] = (2, 0, 1),
) -> np.ndarray:
raise NotImplementedError()
@abstractmethod
def _postprocess(
self,
*,
image: np.ndarray,
boxes: np.ndarray,
) -> List[Box]:
raise NotImplementedError()
class DEIMv2(AbstractModel):
def __init__(
self,
*,
runtime: Optional[str] = 'onnx',
model_path: Optional[str] = 'deimv2_dinov3_x_wholebody34_1750query_n_batch.onnx',
obj_class_score_th: Optional[float] = 0.35,
attr_class_score_th: Optional[float] = 0.70,
keypoint_th: Optional[float] = 0.35,
providers: Optional[List] = None,
):
"""
Parameters
----------
runtime: Optional[str]
Runtime for DEIMv2. Default: onnx
model_path: Optional[str]
ONNX/TFLite file path for DEIMv2
obj_class_score_th: Optional[float]
Object score threshold. Default: 0.35
attr_class_score_th: Optional[float]
Attributes score threshold. Default: 0.70
keypoint_th: Optional[float]
Keypoints score threshold. Default: 0.35
providers: Optional[List]
Providers for ONNXRuntime.
"""
super().__init__(
runtime=runtime,
model_path=model_path,
obj_class_score_th=obj_class_score_th,
attr_class_score_th=attr_class_score_th,
keypoint_th=keypoint_th,
providers=providers,
)
self.mean: np.ndarray = np.asarray([0.485, 0.456, 0.406], dtype=np.float32).reshape([3,1,1]) # Not used in DEIMv2
self.std: np.ndarray = np.asarray([0.229, 0.224, 0.225], dtype=np.float32).reshape([3,1,1]) # Not used in DEIMv2
def __call__(
self,
image: np.ndarray,
disable_generation_identification_mode: bool,
disable_gender_identification_mode: bool,
disable_left_and_right_hand_identification_mode: bool,
disable_headpose_identification_mode: bool,
) -> List[Box]:
"""
Parameters
----------
image: np.ndarray
Entire image
disable_generation_identification_mode: bool
disable_gender_identification_mode: bool
disable_left_and_right_hand_identification_mode: bool
disable_headpose_identification_mode: bool
Returns
-------
result_boxes: List[Box]
Predicted boxes: [classid, score, x1, y1, x2, y2, cx, cy, atrributes, is_used=False]
"""
temp_image = copy.deepcopy(image)
# PreProcess
resized_image = \
self._preprocess(
temp_image,
)
# Inference
inferece_image = np.asarray([resized_image], dtype=self._input_dtypes[0])
outputs = super().__call__(input_datas=[inferece_image])
boxes = outputs[0][0]
# PostProcess
result_boxes = \
self._postprocess(
image=temp_image,
boxes=boxes,
disable_generation_identification_mode=disable_generation_identification_mode,
disable_gender_identification_mode=disable_gender_identification_mode,
disable_left_and_right_hand_identification_mode=disable_left_and_right_hand_identification_mode,
disable_headpose_identification_mode=disable_headpose_identification_mode,
)
return result_boxes
def _preprocess(
self,
image: np.ndarray,
) -> np.ndarray:
"""_preprocess
Parameters
----------
image: np.ndarray
Entire image
Returns
-------
resized_image: np.ndarray
Resized and normalized image.
"""
image = image.transpose(self._swap)
image = \
np.ascontiguousarray(
image,
dtype=np.float32,
)
return image
def _postprocess(
self,
image: np.ndarray,
boxes: np.ndarray,
disable_generation_identification_mode: bool,
disable_gender_identification_mode: bool,
disable_left_and_right_hand_identification_mode: bool,
disable_headpose_identification_mode: bool,
) -> List[Box]:
"""_postprocess
Parameters
----------
image: np.ndarray
Entire image.
boxes: np.ndarray
float32[N, 7]. [instances, [batchno, classid, score, x1, y1, x2, y2]].
disable_generation_identification_mode: bool
disable_gender_identification_mode: bool
disable_left_and_right_hand_identification_mode: bool
disable_headpose_identification_mode: bool
Returns
-------
result_boxes: List[Box]
Predicted boxes: [classid, score, x1, y1, x2, y2, cx, cy, attributes, is_used=False]
"""
image_height = image.shape[0]
image_width = image.shape[1]
result_boxes: List[Box] = []
box_score_threshold: float = min([self._obj_class_score_th, self._attr_class_score_th, self._keypoint_th])
if len(boxes) > 0:
scores = boxes[:, 5:6]
keep_idxs = scores[:, 0] > box_score_threshold
scores_keep = scores[keep_idxs, :]
boxes_keep = boxes[keep_idxs, :]
if len(boxes_keep) > 0:
# Object filter
for box, score in zip(boxes_keep, scores_keep):
classid = int(box[0])
x_min = int(max(0, box[1]) * image_width)
y_min = int(max(0, box[2]) * image_height)
x_max = int(min(box[3], 1.0) * image_width)
y_max = int(min(box[4], 1.0) * image_height)
cx = (x_min + x_max) // 2
cy = (y_min + y_max) // 2
result_boxes.append(
Box(
classid=classid,
score=float(score),
x1=x_min,
y1=y_min,
x2=x_max,
y2=y_max,
cx=cx,
cy=cy,
generation=-1, # -1: Unknown, 0: Adult, 1: Child
gender=-1, # -1: Unknown, 0: Male, 1: Female
handedness=-1, # -1: Unknown, 0: Left, 1: Right
head_pose=-1, # -1: Unknown, 0: Front, 1: Right-Front, 2: Right-Side, 3: Right-Back, 4: Back, 5: Left-Back, 6: Left-Side, 7: Left-Front
)
)
# Object filter
result_boxes = [
box for box in result_boxes \
if (box.classid in [0,5,6,7,16,17,18,19,20,26,27,28,33] and box.score >= self._obj_class_score_th) or box.classid not in [0,5,6,7,16,17,18,19,20,26,27,28,33]
]
# Attribute filter
result_boxes = [
box for box in result_boxes \
if (box.classid in [1,2,3,4,8,9,10,11,12,13,14,15] and box.score >= self._attr_class_score_th) or box.classid not in [1,2,3,4,8,9,10,11,12,13,14,15]
]
# Keypoint filter
result_boxes = [
box for box in result_boxes \
if (box.classid in [21,22,23,24,25,29,30,31,32] and box.score >= self._keypoint_th) or box.classid not in [21,22,23,24,25,29,30,31,32]
]
# Adult, Child merge
# classid: 0 -> Body
# classid: 1 -> Adult
# classid: 2 -> Child
# 1. Calculate Adult and Child IoUs for Body detection results
# 2. Connect either the Adult or the Child with the highest score and the highest IoU with the Body.
# 3. Exclude Adult and Child from detection results
if not disable_generation_identification_mode:
body_boxes = [box for box in result_boxes if box.classid == 0]
generation_boxes = [box for box in result_boxes if box.classid in [1, 2]]
self._find_most_relevant_obj(base_objs=body_boxes, target_objs=generation_boxes)
result_boxes = [box for box in result_boxes if box.classid not in [1, 2]]
# Male, Female merge
# classid: 0 -> Body
# classid: 3 -> Male
# classid: 4 -> Female
# 1. Calculate Male and Female IoUs for Body detection results
# 2. Connect either the Male or the Female with the highest score and the highest IoU with the Body.
# 3. Exclude Male and Female from detection results
if not disable_gender_identification_mode:
body_boxes = [box for box in result_boxes if box.classid == 0]
gender_boxes = [box for box in result_boxes if box.classid in [3, 4]]
self._find_most_relevant_obj(base_objs=body_boxes, target_objs=gender_boxes)
result_boxes = [box for box in result_boxes if box.classid not in [3, 4]]
# HeadPose merge
# classid: 7 -> Head
# classid: 8 -> Front
# classid: 9 -> Right-Front
# classid: 10 -> Right-Side
# classid: 11 -> Right-Back
# classid: 12 -> Back
# classid: 13 -> Left-Back
# classid: 14 -> Left-Side
# classid: 15 -> Left-Front
# 1. Calculate HeadPose IoUs for Head detection results
# 2. Connect either the HeadPose with the highest score and the highest IoU with the Head.
# 3. Exclude HeadPose from detection results
if not disable_headpose_identification_mode:
head_boxes = [box for box in result_boxes if box.classid == 7]
headpose_boxes = [box for box in result_boxes if box.classid in [8,9,10,11,12,13,14,15]]
self._find_most_relevant_obj(base_objs=head_boxes, target_objs=headpose_boxes)
result_boxes = [box for box in result_boxes if box.classid not in [8,9,10,11,12,13,14,15]]
# Left and right hand merge
# classid: 23 -> Hand
# classid: 24 -> Left-Hand
# classid: 25 -> Right-Hand
# 1. Calculate Left-Hand and Right-Hand IoUs for Hand detection results
# 2. Connect either the Left-Hand or the Right-Hand with the highest score and the highest IoU with the Hand.
# 3. Exclude Left-Hand and Right-Hand from detection results
if not disable_left_and_right_hand_identification_mode:
hand_boxes = [box for box in result_boxes if box.classid == 26]
left_right_hand_boxes = [box for box in result_boxes if box.classid in [27, 28]]
self._find_most_relevant_obj(base_objs=hand_boxes, target_objs=left_right_hand_boxes)
result_boxes = [box for box in result_boxes if box.classid not in [27, 28]]
# Keypoints NMS
# Suppression of overdetection
# classid: 21 -> collarbone
# classid: 22 -> shoulder
# classid: 23 -> solar_plexus
# classid: 24 -> elbow
# classid: 25 -> wrist
# classid: 29 -> abdomen
# classid: 30 -> hip_joint
# classid: 31 -> knee
# classid: 32 -> ankle
for target_classid in [21,22,23,24,25,29,30,31,32]:
keypoints_boxes = [box for box in result_boxes if box.classid == target_classid]
filtered_keypoints_boxes = self._nms(target_objs=keypoints_boxes, iou_threshold=0.20)
result_boxes = [box for box in result_boxes if box.classid != target_classid]
result_boxes = result_boxes + filtered_keypoints_boxes
return result_boxes
def _find_most_relevant_obj(
self,
*,
base_objs: List[Box],
target_objs: List[Box],
):
for base_obj in base_objs:
most_relevant_obj: Box = None
best_score = 0.0
best_iou = 0.0
best_distance = float('inf')
for target_obj in target_objs:
distance = ((base_obj.cx - target_obj.cx)**2 + (base_obj.cy - target_obj.cy)**2)**0.5
# Process only unused objects with center Euclidean distance less than or equal to 10.0
if not target_obj.is_used and distance <= 10.0:
# Prioritize high-score objects
if target_obj.score >= best_score:
# IoU Calculation
iou: float = \
self._calculate_iou(
base_obj=base_obj,
target_obj=target_obj,
)
# Adopt object with highest IoU
if iou > best_iou:
most_relevant_obj = target_obj
best_iou = iou
# Calculate the Euclidean distance between the center coordinates
# of the base and the center coordinates of the target
best_distance = distance
best_score = target_obj.score
elif iou > 0.0 and iou == best_iou:
# Calculate the Euclidean distance between the center coordinates
# of the base and the center coordinates of the target
if distance < best_distance:
most_relevant_obj = target_obj
best_distance = distance
best_score = target_obj.score
if most_relevant_obj:
if most_relevant_obj.classid == 1:
base_obj.generation = 0
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 2:
base_obj.generation = 1
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 3:
base_obj.gender = 0
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 4:
base_obj.gender = 1
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 8:
base_obj.head_pose = 0
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 9:
base_obj.head_pose = 1
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 10:
base_obj.head_pose = 2
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 11:
base_obj.head_pose = 3
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 12:
base_obj.head_pose = 4
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 13:
base_obj.head_pose = 5
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 14:
base_obj.head_pose = 6
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 15:
base_obj.head_pose = 7
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 27:
base_obj.handedness = 0
most_relevant_obj.is_used = True
elif most_relevant_obj.classid == 28:
base_obj.handedness = 1
most_relevant_obj.is_used = True
def _nms(
self,
*,
target_objs: List[Box],
iou_threshold: float,
):
filtered_objs: List[Box] = []
# 1. Sorted in order of highest score
# key=lambda box: box.score to get the score, and reverse=True to sort in descending order
sorted_objs = sorted(target_objs, key=lambda box: box.score, reverse=True)
# 2. Scan the box list after sorting
while sorted_objs:
# Extract the first (highest score)
current_box = sorted_objs.pop(0)
# If you have already used it, skip it
if current_box.is_used:
continue
# Add to filtered_objs and set the use flag
filtered_objs.append(current_box)
current_box.is_used = True
# 3. Mark the boxes where the current_box and IOU are above the threshold as used or exclude them
remaining_boxes = []
for box in sorted_objs:
if not box.is_used:
# Calculating IoU
iou_value = self._calculate_iou(base_obj=current_box, target_obj=box)
# If the IOU threshold is exceeded, it is considered to be the same object and is removed as a duplicate
if iou_value >= iou_threshold:
# Leave as used (exclude later)
box.is_used = True
else:
# If the IOU threshold is not met, the candidate is still retained
remaining_boxes.append(box)
# Only the remaining_boxes will be handled in the next loop
sorted_objs = remaining_boxes
# 4. Return the box that is left over in the end
return filtered_objs
def _calculate_iou(
self,
*,
base_obj: Box,
target_obj: Box,
) -> float:
# Calculate areas of overlap
inter_xmin = max(base_obj.x1, target_obj.x1)
inter_ymin = max(base_obj.y1, target_obj.y1)
inter_xmax = min(base_obj.x2, target_obj.x2)
inter_ymax = min(base_obj.y2, target_obj.y2)
# If there is no overlap
if inter_xmax <= inter_xmin or inter_ymax <= inter_ymin:
return 0.0
# Calculate area of overlap and area of each bounding box
inter_area = (inter_xmax - inter_xmin) * (inter_ymax - inter_ymin)
area1 = (base_obj.x2 - base_obj.x1) * (base_obj.y2 - base_obj.y1)
area2 = (target_obj.x2 - target_obj.x1) * (target_obj.y2 - target_obj.y1)
# Calculate IoU
iou = inter_area / float(area1 + area2 - inter_area)
return iou
def list_image_files(dir_path: str) -> List[str]:
path = Path(dir_path)
image_files = []
for extension in ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']:
image_files.extend(path.rglob(extension))
return sorted([str(file) for file in image_files])
def is_parsable_to_int(s):
try:
int(s)
return True
except ValueError:
return False
def is_package_installed(package_name: str):
"""Checks if the specified package is installed.
Parameters
----------
package_name: str
Name of the package to be checked.
Returns
-------
result: bool
True if the package is installed, false otherwise.
"""
return importlib.util.find_spec(package_name) is not None
def draw_dashed_line(
image: np.ndarray,
pt1: Tuple[int, int],
pt2: Tuple[int, int],
color: Tuple[int, int, int],
thickness: int = 1,
dash_length: int = 10,
):
"""Function to draw a dashed line"""
dist = ((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2) ** 0.5
dashes = int(dist / dash_length)
for i in range(dashes):
start = [int(pt1[0] + (pt2[0] - pt1[0]) * i / dashes), int(pt1[1] + (pt2[1] - pt1[1]) * i / dashes)]
end = [int(pt1[0] + (pt2[0] - pt1[0]) * (i + 0.5) / dashes), int(pt1[1] + (pt2[1] - pt1[1]) * (i + 0.5) / dashes)]
cv2.line(image, tuple(start), tuple(end), color, thickness)
def draw_dashed_rectangle(
image: np.ndarray,
top_left: Tuple[int, int],
bottom_right: Tuple[int, int],
color: Tuple[int, int, int],
thickness: int = 1,
dash_length: int = 10
):
"""Function to draw a dashed rectangle"""
tl_tr = (bottom_right[0], top_left[1])
bl_br = (top_left[0], bottom_right[1])
draw_dashed_line(image, top_left, tl_tr, color, thickness, dash_length)
draw_dashed_line(image, tl_tr, bottom_right, color, thickness, dash_length)
draw_dashed_line(image, bottom_right, bl_br, color, thickness, dash_length)
draw_dashed_line(image, bl_br, top_left, color, thickness, dash_length)
def distance_euclid(p1: Tuple[int,int], p2: Tuple[int,int]) -> float:
"""2点 (x1, y1), (x2, y2) のユークリッド距離を返す"""
return math.hypot(p1[0]-p2[0], p1[1]-p2[1])
def draw_skeleton(
image: np.ndarray,
boxes: List[Box],
color=(0,255,255),
max_dist_threshold=500.0
):
"""
与えられた boxes (各クラスIDの関節候補) を基に、EDGESで定義された親子を
「もっとも近い距離のペアから順番に」接合していく。ただし、
classid=0 (人物) のバウンディングボックス内にあるキーポイント同士のみを
接続対象とする。
"""
# -------------------------
# 1) 人物ボックスに ID を付与する
# -------------------------
person_boxes = [b for b in boxes if b.classid == 0]
for i, pbox in enumerate(person_boxes):
# 便宜上、Boxクラスに person_id 属性がないので動的に付与する例
pbox.person_id = i