-
Notifications
You must be signed in to change notification settings - Fork 2
/
demo_bottrack_onnx_tflite.py
2203 lines (1941 loc) · 82.9 KB
/
demo_bottrack_onnx_tflite.py
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
"""
runtime: https://github.com/microsoft/onnxruntime
pip install onnxruntime or pip install onnxruntime-gpu
pip install lap==0.4.0 scipy==1.10.1 opencv-contrib-python==4.9.0.80
"""
from __future__ import annotations
import os
import re
import sys
import copy
import cv2
import time
import lap
import requests # type: ignore
import subprocess
import numpy as np
import scipy.linalg
from enum import Enum
from collections import OrderedDict, deque
from argparse import ArgumentParser
from typing import Tuple, Optional, List, Dict
import importlib.util
from abc import ABC, abstractmethod
# https://developer.nvidia.com/cuda-gpus
NVIDIA_GPU_MODELS_CC = [
'RTX 3050', 'RTX 3060', 'RTX 3070', 'RTX 3080', 'RTX 3090',
]
ONNX_TRTENGINE_SETS = {
'yolox_x_body_head_hand_face_0076_0.5228_post_1x3x480x640_score015_iou080_box050.onnx': [
'TensorrtExecutionProvider_TRTKernel_graph_main_graph_14915622583698702352_0_0_fp16_sm86.engine',
'TensorrtExecutionProvider_TRTKernel_graph_main_graph_14915622583698702352_1_1_fp16_sm86.engine',
'TensorrtExecutionProvider_TRTKernel_graph_main_graph_14915622583698702352_1_1_fp16_sm86.profile',
],
'face-reidentification-retail-0095_NMx3x128x128_post_feature_only.onnx': [
'TensorrtExecutionProvider_TRTKernel_graph_tf2onnx_2180071764421166639_0_0_fp16_sm86.engine',
'TensorrtExecutionProvider_TRTKernel_graph_tf2onnx_2180071764421166639_0_0_fp16_sm86.profile',
'TensorrtExecutionProvider_TRTKernel_graph_tf2onnx_2180071764421166639_1_1_fp16_sm86.engine',
'TensorrtExecutionProvider_TRTKernel_graph_tf2onnx_2180071764421166639_1_1_fp16_sm86.profile',
],
'mot17_sbs_S50_NMx3x256x128_post_feature_only.onnx': [
'TensorrtExecutionProvider_TRTKernel_graph_main_graph_377269473329240331_0_0_fp16_sm86.engine',
'TensorrtExecutionProvider_TRTKernel_graph_main_graph_377269473329240331_0_0_fp16_sm86.profile',
'TensorrtExecutionProvider_TRTKernel_graph_main_graph_377269473329240331_1_1_fp16_sm86.engine',
'TensorrtExecutionProvider_TRTKernel_graph_main_graph_377269473329240331_1_1_fp16_sm86.profile',
],
}
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)
class Box(ABC):
def __init__(self, trackid: int, classid: int, score: float, x1: int, y1: int, x2: int, y2: int, cx: int, cy: int, is_used: bool):
self.trackid: int = trackid
self.classid: int = classid
self.score: float = score
self.x1: int = x1
self.y1: int = y1
self.x2: int = x2
self.y2: int = y2
self.cx: int = cx
self.cy: int = cy
self.is_used: bool = is_used
class Body(Box):
def __init__(self, trackid: int, classid: int, score: float, x1: int, y1: int, x2: int, y2: int, cx: int, cy: int, is_used: bool, head: Box, hand1: Box, hand2: Box):
super().__init__(trackid=trackid, classid=classid, score=score, x1=x1, y1=y1, x2=x2, y2=y2, cx=cx, cy=cy, is_used=is_used)
self.head: Head = head
self.hand1: Hand = hand1
self.hand2: Hand = hand2
class Head(Box):
def __init__(self, trackid: int, classid: int, score: float, x1: int, y1: int, x2: int, y2: int, cx: int, cy: int, is_used: bool, face: Box, face_landmarks: np.ndarray):
super().__init__(trackid=trackid, classid=classid, score=score, x1=x1, y1=y1, x2=x2, y2=y2, cx=cx, cy=cy, is_used=is_used)
self.face: Box = face
self.face_landmarks: np.ndarray = face_landmarks
class Face(Box):
def __init__(self, trackid: int, classid: int, score: float, x1: int, y1: int, x2: int, y2: int, cx: int, cy: int, is_used: bool):
super().__init__(trackid=trackid, classid=classid, score=score, x1=x1, y1=y1, x2=x2, y2=y2, cx=cx, cy=cy, is_used=is_used)
class Hand(Box):
def __init__(self, trackid: int, classid: int, score: float, x1: int, y1: int, x2: int, y2: int, cx: int, cy: int, is_used: bool):
super().__init__(trackid=trackid, classid=classid, score=score, x1=x1, y1=y1, x2=x2, y2=y2, cx=cx, cy=cy, is_used=is_used)
class KalmanFilter(object):
"""
A simple Kalman filter for tracking bounding boxes in image space.
The 8-dimensional state space
x, y, w, h, vx, vy, vw, vh
contains the bounding box center position (x, y), width w, height h,
and their respective velocities.
Object motion follows a constant velocity model. The bounding box location
(x, y, w, h) is taken as direct observation of the state space (linear
observation model).
"""
"""
Table for the 0.95 quantile of the chi-square distribution with N degrees of
freedom (contains values for N=1, ..., 9). Taken from MATLAB/Octave's chi2inv
function and used as Mahalanobis gating threshold.
"""
chi2inv95 = {
1: 3.8415,
2: 5.9915,
3: 7.8147,
4: 9.4877,
5: 11.070,
6: 12.592,
7: 14.067,
8: 15.507,
9: 16.919
}
def __init__(self):
ndim, dt = 4, 1.
# Create Kalman filter model matrices.
self._motion_mat = np.eye(2 * ndim, 2 * ndim)
for i in range(ndim):
self._motion_mat[i, ndim + i] = dt
self._update_mat = np.eye(ndim, 2 * ndim)
# Motion and observation uncertainty are chosen relative to the current
# state estimate. These weights control the amount of uncertainty in
# the model. This is a bit hacky.
self._std_weight_position = 1. / 20
self._std_weight_velocity = 1. / 160
def initiate(self, measurement: np.ndarray):
"""Create track from unassociated measurement.
Parameters
----------
measurement : ndarray
Bounding box coordinates (x, y, w, h) with center position (x, y),
width w, and height h.
Returns
-------
(ndarray, ndarray)
Returns the mean vector (8 dimensional) and covariance matrix (8x8
dimensional) of the new track. Unobserved velocities are initialized
to 0 mean.
"""
mean_pos = measurement
mean_vel = np.zeros_like(mean_pos)
mean: np.ndarray = np.r_[mean_pos, mean_vel]
std = [
2 * self._std_weight_position * measurement[2],
2 * self._std_weight_position * measurement[3],
2 * self._std_weight_position * measurement[2],
2 * self._std_weight_position * measurement[3],
10 * self._std_weight_velocity * measurement[2],
10 * self._std_weight_velocity * measurement[3],
10 * self._std_weight_velocity * measurement[2],
10 * self._std_weight_velocity * measurement[3]]
covariance = np.diag(np.square(std))
return mean, covariance
def predict(self, mean: np.ndarray, covariance: np.ndarray):
"""Run Kalman filter prediction step.
Parameters
----------
mean : ndarray
The 8 dimensional mean vector of the object state at the previous
time step.
covariance : ndarray
The 8x8 dimensional covariance matrix of the object state at the
previous time step.
Returns
-------
(ndarray, ndarray)
Returns the mean vector and covariance matrix of the predicted
state. Unobserved velocities are initialized to 0 mean.
"""
std_pos = [
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
self._std_weight_position * mean[2],
self._std_weight_position * mean[3]]
std_vel = [
self._std_weight_velocity * mean[2],
self._std_weight_velocity * mean[3],
self._std_weight_velocity * mean[2],
self._std_weight_velocity * mean[3]]
motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))
mean = np.dot(mean, self._motion_mat.T)
covariance = np.linalg.multi_dot((
self._motion_mat, covariance, self._motion_mat.T)) + motion_cov
return mean, covariance
def project(self, mean: np.ndarray, covariance: np.ndarray):
"""Project state distribution to measurement space.
Parameters
----------
mean : ndarray
The state's mean vector (8 dimensional array).
covariance : ndarray
The state's covariance matrix (8x8 dimensional).
Returns
-------
(ndarray, ndarray)
Returns the projected mean and covariance matrix of the given state
estimate.
"""
std = [
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
self._std_weight_position * mean[2],
self._std_weight_position * mean[3]]
innovation_cov = np.diag(np.square(std))
mean = np.dot(self._update_mat, mean)
covariance = np.linalg.multi_dot((
self._update_mat, covariance, self._update_mat.T))
return mean, covariance + innovation_cov
def multi_predict(self, mean: np.ndarray, covariance: np.ndarray):
"""Run Kalman filter prediction step (Vectorized version).
Parameters
----------
mean : ndarray
The Nx8 dimensional mean matrix of the object states at the previous
time step.
covariance : ndarray
The Nx8x8 dimensional covariance matrics of the object states at the
previous time step.
Returns
-------
(ndarray, ndarray)
Returns the mean vector and covariance matrix of the predicted
state. Unobserved velocities are initialized to 0 mean.
"""
std_pos = [
self._std_weight_position * mean[:, 2],
self._std_weight_position * mean[:, 3],
self._std_weight_position * mean[:, 2],
self._std_weight_position * mean[:, 3]]
std_vel = [
self._std_weight_velocity * mean[:, 2],
self._std_weight_velocity * mean[:, 3],
self._std_weight_velocity * mean[:, 2],
self._std_weight_velocity * mean[:, 3]]
sqr = np.square(np.r_[std_pos, std_vel]).T
motion_cov = []
for i in range(len(mean)):
motion_cov.append(np.diag(sqr[i]))
motion_cov = np.asarray(motion_cov)
mean = np.dot(mean, self._motion_mat.T)
left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))
covariance = np.dot(left, self._motion_mat.T) + motion_cov
return mean, covariance
def update(self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray):
"""Run Kalman filter correction step.
Parameters
----------
mean : ndarray
The predicted state's mean vector (8 dimensional).
covariance : ndarray
The state's covariance matrix (8x8 dimensional).
measurement : ndarray
The 4 dimensional measurement vector (x, y, w, h), where (x, y)
is the center position, w the width, and h the height of the
bounding box.
Returns
-------
(ndarray, ndarray)
Returns the measurement-corrected state distribution.
"""
projected_mean, projected_cov = self.project(mean, covariance)
chol_factor, lower = scipy.linalg.cho_factor(
projected_cov, lower=True, check_finite=False)
kalman_gain: np.ndarray = scipy.linalg.cho_solve(
(chol_factor, lower), np.dot(covariance, self._update_mat.T).T,
check_finite=False).T
innovation = measurement - projected_mean
new_mean: np.ndarray = mean + np.dot(innovation, kalman_gain.T)
new_covariance: np.ndarray = covariance - np.linalg.multi_dot((
kalman_gain, projected_cov, kalman_gain.T))
return new_mean, new_covariance
def gating_distance(self, mean, covariance, measurements,
only_position=False, metric='maha'):
"""Compute gating distance between state distribution and measurements.
A suitable distance threshold can be obtained from `chi2inv95`. If
`only_position` is False, the chi-square distribution has 4 degrees of
freedom, otherwise 2.
Parameters
----------
mean : ndarray
Mean vector over the state distribution (8 dimensional).
covariance : ndarray
Covariance of the state distribution (8x8 dimensional).
measurements : ndarray
An Nx4 dimensional matrix of N measurements, each in
format (x, y, a, h) where (x, y) is the bounding box center
position, a the aspect ratio, and h the height.
only_position : Optional[bool]
If True, distance computation is done with respect to the bounding
box center position only.
Returns
-------
ndarray
Returns an array of length N, where the i-th element contains the
squared Mahalanobis distance between (mean, covariance) and
`measurements[i]`.
"""
mean, covariance = self.project(mean, covariance)
if only_position:
mean, covariance = mean[:2], covariance[:2, :2]
measurements = measurements[:, :2]
d = measurements - mean
if metric == 'gaussian':
return np.sum(d * d, axis=1)
elif metric == 'maha':
cholesky_factor = np.linalg.cholesky(covariance)
z = scipy.linalg.solve_triangular(
cholesky_factor, d.T, lower=True, check_finite=False,
overwrite_b=True)
squared_maha = np.sum(z * z, axis=0)
return squared_maha
else:
raise ValueError('invalid distance metric')
class TrackState(object):
New = 0
Tracked = 1
Lost = 2
LongLost = 3
Removed = 4
class BaseTrack(object):
_count = 0
track_id = 0
is_activated = False
state = TrackState.New
history = OrderedDict()
features = []
body_curr_feature = None
face_curr_feature = None
score = 0
start_frame = 0
frame_id = 0
time_since_update = 0
# multi-camera
location = (np.inf, np.inf)
@property
def end_frame(self):
return self.frame_id
@staticmethod
def next_id():
BaseTrack._count += 1
return BaseTrack._count
def activate(self, *args):
raise NotImplementedError
def predict(self):
raise NotImplementedError
def update(self, *args, **kwargs):
raise NotImplementedError
def mark_lost(self):
self.state = TrackState.Lost
def mark_long_lost(self):
self.state = TrackState.LongLost
def mark_removed(self):
self.state = TrackState.Removed
@staticmethod
def clear_count():
BaseTrack._count = 0
class STrack(BaseTrack):
shared_kalman = KalmanFilter()
def __init__(self, tlwh: np.ndarray, score: float, feature_history: int, body: Body, body_feature: np.ndarray=None, face_feature: np.ndarray=None):
"""STrack
Parameters
----------
tlwh: np.ndarray
Top-left, width, height. [x1, y1, w, h]
score: float
Object detection score.
feature_history: int
Number of features to be retained in history.
body: Body
body_feature: Optional[np.ndarray]
Features obtained from the feature extractor.
face_feature: Optional[np.ndarray]
Features obtained from the feature extractor.
"""
# wait activate
self._tlwh = np.asarray(tlwh, dtype=np.float32)
self.kalman_filter: KalmanFilter = None
self.mean = None
self.covariance = None
self.is_activated = False
self.score = score
self.tracklet_len = 0
self.alpha = 0.9
self.feature_history = feature_history
self.body = body
# Body features
self.body_smooth_feature = None
self.body_curr_feature = None
self.body_features = deque([], maxlen=feature_history)
if body_feature is not None:
self.update_body_features(body_feature)
# Face features
self.face_smooth_feature = None
self.face_curr_feature = None
self.face_features = deque([], maxlen=feature_history)
if face_feature is not None:
self.update_face_features(face_feature)
def update_body_features(self, feature: np.ndarray):
# Skip processing because it has already been
# normalized in the post-processing process of ONNX.
# feature /= np.linalg.norm(feature)
self.body_curr_feature = feature
if self.body_smooth_feature is None:
self.body_smooth_feature = feature
else:
self.body_smooth_feature = self.alpha * self.body_smooth_feature + (1 - self.alpha) * feature
self.body_features.append(feature)
self.body_smooth_feature /= np.linalg.norm(self.body_smooth_feature)
def update_face_features(self, feature: np.ndarray):
# Skip processing because it has already been
# normalized in the post-processing process of ONNX.
# feature /= np.linalg.norm(feature)
self.face_curr_feature = feature
if self.face_smooth_feature is None:
self.face_smooth_feature = feature
else:
self.face_smooth_feature = self.alpha * self.face_smooth_feature + (1 - self.alpha) * feature
self.face_features.append(feature)
self.face_smooth_feature /= np.linalg.norm(self.face_smooth_feature)
def predict(self):
mean_state = self.mean.copy()
if self.state != TrackState.Tracked:
mean_state[6] = 0
mean_state[7] = 0
self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
@staticmethod
def multi_predict(stracks: List[STrack]):
if len(stracks) > 0:
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
for i, st in enumerate(stracks):
if st.state != TrackState.Tracked:
multi_mean[i][6] = 0
multi_mean[i][7] = 0
multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
stracks[i].mean = mean
stracks[i].covariance = cov
@staticmethod
def multi_gmc(stracks: List[STrack], H: np.ndarray=np.eye(2, 3)):
if len(stracks) > 0:
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
R = H[:2, :2]
R8x8 = np.kron(np.eye(4, dtype=float), R)
t = H[:2, 2]
for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
mean = R8x8.dot(mean)
mean[:2] += t
cov = R8x8.dot(cov).dot(R8x8.transpose())
stracks[i].mean = mean
stracks[i].covariance = cov
def activate(self, kalman_filter: KalmanFilter, frame_id: int):
"""Start a new tracklet"""
self.kalman_filter = kalman_filter
self.track_id = self.next_id()
self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xywh(self._tlwh))
self.tracklet_len = 0
self.state = TrackState.Tracked
if frame_id == 1:
self.is_activated = True
self.frame_id = frame_id
self.start_frame = frame_id
def re_activate(self, new_track: STrack, frame_id: int, new_id: bool=False):
self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, self.tlwh_to_xywh(new_track.tlwh))
if new_track.body_curr_feature is not None:
self.update_body_features(new_track.body_curr_feature)
if new_track.face_curr_feature is not None:
self.update_face_features(new_track.face_curr_feature)
self.tracklet_len = 0
self.state = TrackState.Tracked
self.is_activated = True
self.frame_id = frame_id
if new_id:
self.track_id = self.next_id()
self.score = new_track.score
self.body = new_track.body
def update(self, new_track: STrack, frame_id: int):
"""
Update a matched track
:type new_track: STrack
:type frame_id: int
:type update_feature: bool
:return:
"""
self.frame_id = frame_id
self.tracklet_len += 1
new_tlwh = new_track.tlwh
self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, self.tlwh_to_xywh(new_tlwh))
if new_track.body_curr_feature is not None:
self.update_body_features(new_track.body_curr_feature)
if new_track.face_curr_feature is not None:
self.update_face_features(new_track.face_curr_feature)
self.state = TrackState.Tracked
self.is_activated = True
self.score = new_track.score
self.body = new_track.body
def propagate_trackid_to_related_objects(self):
if self.body is not None:
self.body.trackid = self.track_id
if self.body.head is not None:
self.body.head.trackid = self.track_id
if self.body.head.face is not None:
self.body.head.face.trackid = self.track_id
if self.body.hand1 is not None:
self.body.hand1.trackid = self.track_id
if self.body.hand2 is not None:
self.body.hand2.trackid = self.track_id
@property
def tlwh(self):
"""Get current position in bounding box format `(top left x, top left y,
width, height)`.
"""
if self.mean is None:
return self._tlwh.copy()
ret = self.mean[:4].copy()
ret[:2] -= ret[2:] / 2
return ret
@property
def tlbr(self):
"""Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
`(top left, bottom right)`.
"""
ret = self.tlwh.copy()
ret[2:] += ret[:2]
return ret
@property
def xywh(self):
"""Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
`(top left, bottom right)`.
"""
ret = self.tlwh.copy()
ret[:2] += ret[2:] / 2.0
return ret
@staticmethod
def tlwh_to_xyah(tlwh: np.ndarray):
"""Convert bounding box to format `(center x, center y, aspect ratio,
height)`, where the aspect ratio is `width / height`.
"""
ret = np.asarray(tlwh).copy()
ret[:2] += ret[2:] / 2
ret[2] /= ret[3]
return ret
@staticmethod
def tlwh_to_xywh(tlwh: np.ndarray):
"""Convert bounding box to format `(center x, center y, width,
height)`.
"""
ret = np.asarray(tlwh).copy()
ret[:2] += ret[2:] / 2
return ret
def to_xywh(self):
return self.tlwh_to_xywh(self.tlwh)
@staticmethod
def tlbr_to_tlwh(tlbr: np.ndarray):
ret = np.asarray(tlbr).copy()
ret[2:] -= ret[:2]
return ret
@staticmethod
def tlwh_to_tlbr(tlwh: np.ndarray):
ret = np.asarray(tlwh).copy()
ret[2:] += ret[:2]
return ret
def __repr__(self):
return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame)
class AbstractModel(ABC):
"""AbstractModel
Base class of the model.
"""
_runtime: str = 'onnx'
_model_path: str = ''
_input_shapes: List[List[int]] = []
_input_names: List[str] = []
_output_shapes: List[List[int]] = []
_output_names: List[str] = []
_mean: np.ndarray = np.array([0.000, 0.000, 0.000], dtype=np.float32)
_std: np.ndarray = np.array([1.000, 1.000, 1.000], dtype=np.float32)
# onnx/tflite
_interpreter = None
_inference_model = None
_providers = None
_swap: Tuple = (2, 0, 1)
_h_index: int = 2
_w_index: int = 3
_norm_shape: List = [1,3,1,1]
_class_score_th: float
# onnx
_onnx_dtypes_to_np_dtypes = {
"tensor(float)": np.float32,
"tensor(uint8)": np.uint8,
"tensor(int8)": np.int8,
"tensor(int64)": np.int64,
"tensor(int32)": np.int32,
}
# tflite
_input_details = None
_output_details = None
@abstractmethod
def __init__(
self,
*,
runtime: Optional[str] = 'onnx',
model_path: Optional[str] = '',
providers: Optional[List] = [
(
'TensorrtExecutionProvider', {
'trt_engine_cache_enable': True,
'trt_engine_cache_path': '.',
'trt_fp16_enable': True,
}
),
'CUDAExecutionProvider',
'CPUExecutionProvider',
],
mean: Optional[np.ndarray] = np.array([0.000, 0.000, 0.000], dtype=np.float32),
std: Optional[np.ndarray] = np.array([1.000, 1.000, 1.000], dtype=np.float32),
class_score_th: float = 0.35,
):
self._runtime = runtime
self._model_path = model_path
self._providers = providers
# Model loading
if self._runtime == 'onnx':
import onnxruntime # type: ignore
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()
self._input_shapes = [
input.shape for input in self._interpreter.get_inputs()
]
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
self._norm_shape = [1,3,1,1]
elif self._runtime in ['tflite_runtime', 'tensorflow']:
if self._runtime == 'tflite_runtime':
from tflite_runtime.interpreter import Interpreter # type: ignore
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_shapes = [
input.get('shape', None) for input in self._input_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
self._norm_shape = [1,1,1,3]
self._mean = mean.reshape(self._norm_shape)
self._std = std.reshape(self._norm_shape)
self._class_score_th = class_score_th
@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 ['tflite_runtime', '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()
class YOLOX(AbstractModel):
def __init__(
self,
*,
runtime: Optional[str] = 'onnx',
model_path: Optional[str] = 'yolox_x_body_head_hand_face_0076_0.5228_post_1x3x480x640_score015_iou080_box050.onnx',
class_score_th: Optional[float] = 0.35,
providers: Optional[List] = None,
):
"""YOLOX
Parameters
----------
runtime: Optional[str]
Runtime for YOLOX. Default: onnx
model_path: Optional[str]
ONNX/TFLite file path for YOLOX
class_score_th: Optional[float]
Score threshold. Default: 0.35
providers: Optional[List]
Providers for ONNXRuntime.
"""
super().__init__(
runtime=runtime,
model_path=model_path,
class_score_th=class_score_th,
providers=providers,
)
def __call__(
self,
image: np.ndarray,
) -> List[Box]:
"""YOLOX
Parameters
----------
image: np.ndarray
Entire image
Returns
-------
boxes: np.ndarray
Predicted boxes: [N, x1, y1, x2, y2]
scores: np.ndarray
Predicted box scores: [N, score]
"""
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]
# PostProcess
result_boxes = \
self._postprocess(
image=temp_image,
boxes=boxes,
)
return result_boxes
def _preprocess(
self,
image: np.ndarray,
) -> np.ndarray:
"""_preprocess
Parameters
----------
image: np.ndarray
Entire image
swap: tuple
HWC to CHW: (2,0,1)
CHW to HWC: (1,2,0)
HWC to HWC: (0,1,2)
CHW to CHW: (0,1,2)
Returns
-------
resized_image: np.ndarray
Resized and normalized image.
"""
# Resize + Transpose
resized_image = cv2.resize(
image,
(
int(self._input_shapes[0][self._w_index]),
int(self._input_shapes[0][self._h_index]),
)
)
resized_image = resized_image.transpose(self._swap)
resized_image = \
np.ascontiguousarray(
resized_image,
dtype=np.float32,
)
return resized_image
def _postprocess(
self,
image: np.ndarray,
boxes: np.ndarray,
) -> List[Box]:
"""_postprocess
Parameters
----------
image: np.ndarray
Entire image.
boxes: np.ndarray
float32[N, 7]
Returns
-------
result_boxes: List[Box]
Predicted boxes: [classid, score, x1, y1, x2, y2]
"""
"""
Detector is
N -> Number of boxes detected
batchno -> always 0: BatchNo.0
batchno_classid_score_x1y1x2y2: float32[N,7]
"""
image_height = image.shape[0]
image_width = image.shape[1]
result_boxes: List[Box] = []