-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresult_gen_vis.py
More file actions
4184 lines (3974 loc) · 333 KB
/
result_gen_vis.py
File metadata and controls
4184 lines (3974 loc) · 333 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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import io
import tempfile
from loguru import logger
import gc
import tracemalloc
import warnings
from pympler import tracker
from fast_reid.fast_reid_interfece import FastReIDInterface
from memory_profiler import profile
import objgraph
import argparse
import os
import platform
import shutil
import time
import pandas as pd
from pathlib import Path
from sklearn.decomposition import PCA
from PIL import Image as Img
from PIL import ImageTk
import cv2
import torch
torch.cuda.empty_cache()
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision
from numpy import random
import numpy as np
import _thread
import tkinter as tk
from tkinter import Tk, Label
import PIL.Image
from tkinter import ttk
from PIL import Image, ImageTk
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import (
check_img_size, non_max_suppression, apply_classifier, scale_coords,
xyxy2xywh, strip_optimizer, set_logging)
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized
from scipy.stats import multivariate_normal
import sys
import time
import math
import ot
# import ot.gpu
from subprocess import *
CTX = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
import multiprocessing
import copy
import sys
import os.path as osp
import torch.nn as nn
from similarity_module import torchreid
from similarity_module.torchreid.utils import (
Logger, check_isfile, set_random_seed, collect_env_info,
resume_from_checkpoint, load_pretrained_weights, compute_model_complexity
)
from similarity_module.scripts.default_config import (
imagedata_kwargs, optimizer_kwargs, videodata_kwargs, engine_run_kwargs,
get_default_config, lr_scheduler_kwargs
)
import json
from sklearn import metrics
# from ab_det_realtime.ab_detect_utils import *
from tkinter import *
from itertools import permutations
#################################################### detector related import start ######################################################################
import torch
import torchvision
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
dump_curr_video_name = '/usr/local/SSP_EM/tracking_for_integration'
dump_switch = 0 # ??
dump_further_switch = 0
dump_further_switch_20211011 = 0
dump_further_switch_optimizer = 0
dump_stitching_tracklets_switch = 0
import codecs
from fix_trajs_v5 import *
from botorch.models import SingleTaskGP
from botorch.fit import fit_gpytorch_model
from botorch.utils import standardize
from gpytorch.mlls import ExactMarginalLogLikelihood
from botorch.acquisition import UpperConfidenceBound
from botorch.optim import optimize_acqf
##### yolox #####
from yolox.data.data_augment import preproc
from yolox.core import launch
from yolox.exp import get_exp
from yolox.utils import configure_nccl, fuse_model, get_local_rank, get_model_info, setup_logger
from yolox.evaluators import MOTEvaluator
from yolox.utils import (
gather,
is_main_process,
postprocess,
synchronize,
time_synchronized,
xyxy2xywh
)
from yolox.tracker import matching
from tracker.tracking_utils.timer import Timer
from tracker.gmc import GMC
#################################################### detector related import end ########################################################################
current_video_segment_predicted_tracks = {}
current_video_segment_predicted_tracks_bboxes = {}
current_video_segment_representative_frames = {}
current_video_segment_all_traj_all_object_features = {}
previous_video_segment_all_traj_all_object_features = {}
previous_video_segment_predicted_tracks = {}
previous_video_segment_predicted_tracks_bboxes = {}
previous_video_segment_representative_frames = {}
current_video_segment_predicted_tracks_backup = {}
current_video_segment_predicted_tracks_bboxes_backup = {}
current_video_segment_representative_frames_backup = {}
current_video_segment_all_traj_all_object_features_backup = {}
stitching_tracklets_dict = {}
tracklet_pose_collection_large_temporal_stride_buffer = []
curr_batch_img_buffer = {}
# result_dict = {}
tracklet_len = 10 # 滑动窗口长度
median_filter_radius = 4
num_samples_around_each_joint = 3
maximum_possible_number = math.exp(10)
average_sampling_density_hori_vert = 7
bbox_confidence_threshold = 0.6 #5 # 0.45
gap = 60 # gap设置太大会把最后一段轨迹给分开来
head_bbox_confidence_threshold = 0.55 # 0.6 # 0.45
temporal_length_thresh_inside_tracklet = 5
tracklet_confidence_threshold = 0.6
update_representative_frames_confidence_threshold = 0.9
spatialconsistency_reidsimilarity_debate_thresh = 0.7
large_temporal_stride_thresh = 100
stitching_tracklets_sure_or_not_last_time = [0]
stepback_adjustment_stride_thresh = 100
maximum_number_people = 3
reid_thresh = 0.98
trajectory_intersection_thresh = 0.9
split_single_trajectory_thresh = 0.01
max_movement_between_adjacent_frames = 27.865749586185547 * 2
image_height = 480
image_width = 856
body_head_width_ratio_factor = 3
num_frames_for_traj_prediction = 10 # Under severe motion, the movements are unpredictable, so use shorter historical trajs
whether_conduct_tracking = False
batch_id = 0
frame_height = 0
frame_width = 0
skeletons = [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 6]]
batch_stride = tracklet_len - 1
batch_stride_write = tracklet_len - 1
foreign_matter_cls_id_dict = {
'bicycle': 1,
'motorcycle': 3,
'skateboard': 36
}
# tracemalloc.start() # 开始跟踪内存分配
# snapshot = tracemalloc.take_snapshot()
# np.warnings.filterwarnings('ignore',category=np.VisibleDeprecationWarning)
warnings.filterwarnings('ignore')
# np.warnings.filterwarnings('ignore',category=np.RankWarning)
IMAGE_EXT = [".jpg", ".jpeg", ".webp", ".bmp", ".png"]
# Global
trackerTimer = Timer()
timer = Timer()
def multi_gmc(dets, H=np.eye(2, 3)):
if len(dets) > 0:
R = H[:2, :2]
R8x8 = np.kron(np.eye(4, dtype=float), R)
t = H[:2, 2] # Translation part
for i,det in enumerate(dets):
det[1] -= det[0]
det = det.flatten()
det = R8x8[:4,:4].dot(det)
det[:2] += t
det[1] += det[0]
dets[i,:] = det[:].reshape(2,2)
return dets
def track_processing(split_each_track,mapping_node_id_to_bbox,mapping_node_id_to_features,split_each_track_valid_mask,statistic = (0.55,0.017)):
iou_thresh,iou_thresh_step = statistic[0],statistic[1]
curr_predicted_tracks = {}
curr_predicted_tracks_bboxes = {}
curr_predicted_tracks_bboxes_test = {} # 测试使用
curr_predicted_tracks_confidence_score = {}
curr_representative_frames = {}
mapping_frameid_to_human_centers = {} # 暂存curr_predicted_tracks的value
mapping_frameid_to_bbox = {}
mapping_frameid_to_confidence_score = {}
trajectory_node_dict = {}
trajectory_idswitch_dict = {}
trajectory_idswitch_reliability_dict = {} # 保存每条轨迹切断的每一段置信度 key:trajectory id value:list eg[1,3,5] the sum of node_valid_mask
trajectory_segment_nodes_dict = {}
for track_id in split_each_track:
# curr_predicted_tracks[track_id] = mapping_frameid_to_human_centers
confidence_score_max = 0
node_id_max = 0
# print(track_id,' started!' )
mapping_track_time_to_bbox = {}
trajectory_node_list = []
trajectory_idswitch_list = []
trajectory_idswitch_reliability_list = []
# trajectory_similarity_list = []
trajectory_idswitch_reliability = 0
trajectory_segment_list = []
trajectory_segment = []
for idx,node_pair in enumerate(split_each_track[track_id]): # node,edge
# if int(node_pair[1]) % 2 == 0:
if idx % 2 == 0: # 偶数位置表示人的node
node_id = int(node_pair[1] )/ 2
trajectory_node_list.append(int(node_id))
# print(node_id)
else:
continue
# mapping_node_id_to_bbox[mapping_node_id_to_bbox.index(int(node_pair[0]))][2] # str:img
frame_id = mapping_node_id_to_bbox[node_id][2] # 转化为int进行加减
bbox = mapping_node_id_to_bbox[node_id][0]
# [bbox_pre[0][1], bbox_pre[1][1], bbox_pre[0][0], bbox_pre[1][0]]
idx_tmp = 1 # initial value
if idx >= 1:
iou_similarity = compute_iou_single_box([bbox[0][1], bbox[1][1], bbox[0][0], bbox[1][0]],[bbox_pre[0][1], bbox_pre[1][1], bbox_pre[0][0], bbox_pre[1][0]])
#print(iou_similarity)
#velocity_x = (bbox[0][0] + bbox[1][0]) / 2 - (bbox_pre[0][0] + bbox_pre[1][0]) / 2 # x-axis
#velocity_y = (bbox[0][1] + bbox[1][1]) / 2 - (bbox_pre[0][1] + bbox_pre[1][1]) / 2 # y-axis
iou_thresh_tmp = iou_thresh + int((idx-idx_tmp)/2)*iou_thresh_step
if iou_similarity < iou_thresh_tmp:
#or (np.sign(velocity_x*velocity_x_pre)+np.sign(velocity_y*velocity_y_pre)) == -2:
#print(track_id,idx,iou_similarity)
trajectory_idswitch_list.append(int(idx/2)) # id从0开始
idx_tmp = int(idx)
# iou_thresh_tmp = copy.deepcopy(iou_thresh)
trajectory_idswitch_reliability_list.append(trajectory_idswitch_reliability)
trajectory_segment_list.append(trajectory_segment[:])
trajectory_idswitch_reliability = 0
trajectory_segment = []
# if idx >= 1:
# iou_similarity = compute_iou_single_box([bbox[0][1], bbox[1][1], bbox[0][0], bbox[1][0]],[bbox_pre[0][1], bbox_pre[1][1], bbox_pre[0][0], bbox_pre[1][0]])
# # print(iou_similarity)
# if idx >= 1 and iou_similarity < iou_thresh:
# # print(track_id,idx,iou_similarity)
# trajectory_idswitch_list.append(int(idx/2))
# trajectory_idswitch_reliability_list.append(trajectory_idswitch_reliability)
# trajectory_idswitch_reliability = 0
#
if split_each_track_valid_mask[track_id][idx] == 1:
trajectory_idswitch_reliability += 1
trajectory_segment.append(int(node_id))
bbox_pre = copy.deepcopy(bbox)
confidence_score = mapping_node_id_to_bbox[node_id][1]
if confidence_score > confidence_score_max:
confidence_score_max = confidence_score
node_id_max = node_id
mapping_frameid_to_human_centers[int(frame_id.split('.')[0])] = [(bbox[0][0] + bbox[1][0]) / 2,
(bbox[0][1] + bbox[1][1]) / 2] # 同一帧中图片相连?
mapping_frameid_to_bbox[frame_id] = bbox
# mapping_frameid_to_bbox[frame_id] = [bbox,confidence_score]
mapping_frameid_to_confidence_score[frame_id] = confidence_score
mapping_track_time_to_bbox[int(node_id)] = [frame_id,bbox,confidence_score]
# current_video_segment_all_traj_all_object_features[track_id] = [[node_id], mapping_node_id_to_features[node_id]] # ???
trajectory_idswitch_reliability_list.append(trajectory_idswitch_reliability)
trajectory_segment_list.append(trajectory_segment)
trajectory_node_dict[track_id] = copy.deepcopy(trajectory_node_list)
trajectory_idswitch_dict[track_id] = copy.deepcopy(trajectory_idswitch_list)
trajectory_idswitch_reliability_dict[track_id] = copy.deepcopy(trajectory_idswitch_reliability_list)
trajectory_segment_nodes_dict[track_id] = copy.deepcopy(trajectory_segment_list)
curr_predicted_tracks[track_id] = copy.deepcopy(mapping_frameid_to_human_centers) # 直接等于之后操作会影响到curr_predicted_tracks
curr_predicted_tracks_bboxes[track_id] = copy.deepcopy(mapping_frameid_to_bbox)
curr_predicted_tracks_bboxes_test[track_id] = copy.deepcopy(mapping_track_time_to_bbox)
curr_predicted_tracks_confidence_score[track_id] = copy.deepcopy(mapping_frameid_to_confidence_score)
# 可能刚好在第一个
if node_id_max == 0:
node_id_max = list(mapping_track_time_to_bbox.keys())[0]
curr_representative_frames[track_id] = [node_id_max,(bbox[1][1] - bbox[0][1], bbox[1][0] - bbox[0][0]),mapping_node_id_to_features[node_id_max]] # 高度,宽度
mapping_frameid_to_human_centers.clear()
mapping_frameid_to_bbox.clear()
mapping_frameid_to_confidence_score.clear()
return curr_predicted_tracks_bboxes_test,trajectory_node_dict,trajectory_idswitch_dict,trajectory_idswitch_reliability_dict,trajectory_segment_nodes_dict
def make_parser():
# python tools/demo_track.py -h 查看帮助信息/--help
# 使用时顺序无关紧要
parser = argparse.ArgumentParser("ByteTrack Demo!") # 创建解析对象
# -- 表示可选参数,其余表示必选参数
parser.add_argument(
"--demo", default="image", help="demo type, eg. image, video and webcam"
)
# exp file
parser.add_argument("-f", "--exp_file", type=str, default='exps/example/mot/yolox_x_mix_mot20_ch.py') # # 短选项,使用-f/--exp_file均可
parser.add_argument("-n", "--name", type=str, default=None, help="model name")
parser.add_argument(
"--path", default="/media/allenyljiang/564AFA804AFA5BE5/Dataset/MOT20", help="path to images or video"
) #
# /home/allenyljiang/Documents/Dataset/MOT20
parser.add_argument("--camid", type=int, default=0, help="webcam demo camera id")
parser.add_argument("--benchmark", dest="benchmark", type=str, default='MOT20', help="benchmark to evaluate: MOT17 | MOT20")
parser.add_argument("--eval", dest="split_to_eval", type=str, default='train', help="split to evaluate: train | val | test")
parser.add_argument("-c", "--ckpt", default='pretrained/bytetrack_x_mot20.tar', type=str, help="ckpt for eval")
parser.add_argument("--default-parameters", dest="default_parameters", default=True, action="store_true", help="use the default parameters as in the paper")
#parser.add_argument("--save-frames", dest="save_frames", default=True, action="store_true", help="save sequences with tracks.")
# action表示--save_result标志存在时赋值为"store_true"
#### reid parameters ####
parser.add_argument("--with-reid", dest="with_reid", default=True, action="store_true", help="use Re-ID flag.")
parser.add_argument("--fast-reid-config", dest="fast_reid_config", default=r"/home/allenyljiang/Documents/SSP_EM/fast_reid/configs/MOT20/sbs_S50.yml", type=str, help="reid config file path")
parser.add_argument("--fast-reid-weights", dest="fast_reid_weights", default=r"/home/allenyljiang/Documents/SSP_EM/pretrained/mot20_sbs_S50.pth", type=str, help="reid config file path")
parser.add_argument('--proximity_thresh', type=float, default=0.5, help='threshold for rejecting low overlap reid matches')
parser.add_argument('--appearance_thresh', type=float, default=0.25, help='threshold for rejecting low appearance similarity reid matches')
#### osnet reid parameters ####
parser.add_argument("--torch-reid-config", dest="torch_reid_config", default=r"similarity_module/configs/im_osnet_x0_25_softmax_256x128_amsgrad.yaml", type=str, help="reid config file path")
parser.add_argument("--torch-reid-weights", dest="torch_reid_weights", default=r'similarity_module/model/osnet_x0_25_market_256x128_amsgrad_ep180_stp80_lr0.003_b128_fb10_softmax_labelsmooth_flip.pth', type=str, help="reid config file path")
# CMC
parser.add_argument("--cmc-method", default="file", type=str, help="cmc method: files (Vidstab GMC) | sparseOptFlow | orb | ecc | none")
# 设备
parser.add_argument(
"--device",
default="gpu",
type=str,
help="device to run our model, can either be cpu or gpu",
)
parser.add_argument(
"--local_rank", default=0, type=int, help="local rank for dist training"
)
parser.add_argument(
"--num_machines", default=1, type=int, help="num of node for training"
)
parser.add_argument(
"--machine_rank", default=0, type=int, help="node rank for multi-node training"
)
parser.add_argument("--conf", default=None, type=float, help="test conf")
parser.add_argument("--nms", default=None, type=float, help="test nms threshold")
parser.add_argument("--tsize", default=None, type=int, help="test img size")
parser.add_argument("--fps", default=30, type=int, help="frame rate (fps)")
parser.add_argument(
"--fp16",
dest="fp16",
default= True,
# action="store_true",
help="Adopting mix precision evaluating.",
)
parser.add_argument(
"--fuse",
dest="fuse",
default= True,
# action="store_true",
help="Fuse conv and bn for testing.",
)
parser.add_argument(
"--test",
dest="test",
default=False,
action="store_true",
help="Evaluating on test-dev set.",
)
parser.add_argument(
"--trt",
dest="trt",
default=False,
action="store_true",
help="Using TensorRT model for testing.",
)
parser.add_argument(
"--speed",
dest="speed",
default=False,
action="store_true",
help="speed test only.",
)
# tracking args
parser.add_argument("--track_high_thresh", type=float, default=0.6, help="tracking confidence threshold")
parser.add_argument("--track_low_thresh", default=0.1, type=float, help="lowest detection threshold valid for tracks")
parser.add_argument("--new_track_thresh", default=0.7, type=float, help="new track thresh")
# parser.add_argument("--track_thresh", type=float, default=0.5, help="tracking confidence threshold")
parser.add_argument("--track_buffer", type=int, default=30, help="the frames for keep lost tracks")
parser.add_argument("--match_thresh", type=float, default=0.8, help="matching threshold for tracking")
parser.add_argument(
"--aspect_ratio_thresh", type=float, default=1.6,help="threshold for filtering out boxes of which aspect ratio are above the given value."
)
parser.add_argument('--min_box_area', type=float, default=10, help='filter out tiny boxes')
parser.add_argument("--mot20", dest="mot20", default=False, action="store_true", help="test mot20.")
# statistic information
parser.add_argument("--initial_iou_thresh", type=float, default=0.55,help="initial iou thresh to filter ssp result.")
parser.add_argument("--iou_thresh_step", type=float, default=0.017,help="iou thresh step to filter ssp result.")
# sliding window parameters
parser.add_argument("--tracklet_len", type=int, default= 10 ,help="tracklet length")
parser.add_argument("--batch_stride", type=int, default= 9 ,help="batch stride")
parser.add_argument("--batch_stride_write", type=int, default= 9 ,help="batch stride write")
parser.add_argument("--tracklet_inner_cnt", type=int, default= 9 ,help="tracklet_inner_cnt")
# 结果可视化
parser.add_argument('--save-result', dest="save_result",default=False,
help='whether save the visualizition result') # python demo.py --save-result 启用该参数
parser.set_defaults(save_result = True)
return parser
def get_image_list(path):
image_names = []
for maindir, subdir, file_name_list in os.walk(path):
for filename in file_name_list:
apath = osp.join(maindir, filename)
ext = osp.splitext(apath)[1]
if ext in IMAGE_EXT:
image_names.append(apath)
return image_names
def write_results(filename, results):
save_format = '{frame},{id},{x1},{y1},{w},{h},{s},-1,-1,-1\n'
with open(filename, 'w') as f:
for frame_id, tlwhs, track_ids, scores in results:
for tlwh, track_id, score in zip(tlwhs, track_ids, scores):
if track_id < 0:
continue
x1, y1, w, h = tlwh
line = save_format.format(frame=frame_id, id=track_id, x1=round(x1, 1), y1=round(y1, 1), w=round(w, 1), h=round(h, 1), s=round(score, 2))
f.write(line)
logger.info('save results to {}'.format(filename))
class Predictor(object):
def __init__(
self,
model,
exp,
device=torch.device("cpu"),
fp16=False
):
self.model = model
self.num_classes = exp.num_classes # 1
self.confthre = exp.test_conf # 0.09
self.nmsthre = exp.nmsthre # 0.7
self.test_size = exp.test_size
self.device = device
self.fp16 = fp16
# ImageNet均值和方差
self.rgb_means = (0.485, 0.456, 0.406)
self.std = (0.229, 0.224, 0.225)
def inference(self, img, timer):
img_info = {"id": 0}
if isinstance(img, str):
img_info["file_name"] = osp.basename(img) # '000003.jpg'
img = cv2.imread(img)
else:
img_info["file_name"] = None
if img is None:
raise ValueError("Empty image: ", img_info["file_name"])
height, width = img.shape[:2]
img_info["height"] = height
img_info["width"] = width
img_info["raw_img"] = img
img, ratio = preproc(img, self.test_size, self.rgb_means, self.std) # img:(1080,1920,3)--(3,896,1600)
# imagenet 数据集均值和方差 mean = [0.485,0.456,0.406]
img_info["ratio"] = ratio
img = torch.from_numpy(img).unsqueeze(0).float().to(self.device)
if self.fp16:
img = img.half() # to FP16
with torch.no_grad():
timer.tic()
outputs = self.model(img) # (1,29400,6)
outputs = postprocess(outputs, self.num_classes, self.confthre, self.nmsthre) # (40,7),self.confthre = 0.09
return outputs, img_info
def image_demo(predictor, vis_folder, current_time, args):
if osp.isdir(args.path):
files = get_image_list(args.path)
else:
files = [args.path]
files.sort()
tracker = BYTETracker(args, frame_rate=args.fps)
timer = Timer()
results = []
for frame_id, img_path in enumerate(files, 1):
outputs, img_info = predictor.inference(img_path, timer)
if outputs[0] is not None:
online_targets = tracker.update(outputs[0], [img_info['height'], img_info['width']], exp.test_size)
online_tlwhs = []
online_ids = []
online_scores = []
for t in online_targets:
tlwh = t.tlwh
tid = t.track_id
vertical = tlwh[2] / tlwh[3] > args.aspect_ratio_thresh
if tlwh[2] * tlwh[3] > args.min_box_area and not vertical:
online_tlwhs.append(tlwh)
online_ids.append(tid)
online_scores.append(t.score)
# save results
results.append(
f"{frame_id},{tid},{tlwh[0]:.2f},{tlwh[1]:.2f},{tlwh[2]:.2f},{tlwh[3]:.2f},{t.score:.2f},-1,-1,-1\n"
)
timer.toc()
online_im = plot_tracking(
img_info['raw_img'], online_tlwhs, online_ids, frame_id=frame_id, fps=1. / timer.average_time
)
else:
timer.toc()
online_im = img_info['raw_img']
# result_image = predictor.visual(outputs[0], img_info, predictor.confthre)
if args.save_result:
timestamp = time.strftime("%Y_%m_%d_%H_%M_%S", current_time)
save_folder = osp.join(vis_folder, timestamp)
os.makedirs(save_folder, exist_ok=True)
cv2.imwrite(osp.join(save_folder, osp.basename(img_path)), online_im)
if frame_id % 20 == 0:
logger.info('Processing frame {} ({:.2f} fps)'.format(frame_id, 1. / max(1e-5, timer.average_time)))
ch = cv2.waitKey(0)
if ch == 27 or ch == ord("q") or ch == ord("Q"):
break
if args.save_result:
res_file = osp.join(vis_folder, f"{timestamp}.txt")
with open(res_file, 'w') as f:
f.writelines(results)
logger.info(f"save results to {res_file}")
def tracemalloc_snapshot(snapshot1):
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot1, 'lineno')
print('top 10 differences')
for stat in top_stats[:10]:
print(stat)
def single_snapshot():
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:15]:
print(stat)
def box_to_center_scale(box, model_image_width, model_image_height):
"""convert a box to center,scale information required for pose transformation
Parameters
----------
box : list of tuple
list of length 2 with two tuples of floats representing
bottom left and top right corner of a box
model_image_width : int
model_image_height : int
Returns
-------
(numpy array, numpy array)
Two numpy arrays, coordinates for the center of the box and the scale of the box
"""
center = np.zeros((2), dtype=np.float32)
bottom_left_corner = box[0]
top_right_corner = box[1]
box_width = top_right_corner[0]-bottom_left_corner[0]
box_height = top_right_corner[1]-bottom_left_corner[1]
bottom_left_x = bottom_left_corner[0]
bottom_left_y = bottom_left_corner[1]
center[0] = bottom_left_x + box_width * 0.5
center[1] = bottom_left_y + box_height * 0.5
aspect_ratio = model_image_width * 1.0 / model_image_height
pixel_std = 200
if box_width > aspect_ratio * box_height:
box_height = box_width * 1.0 / aspect_ratio
elif box_width < aspect_ratio * box_height:
box_width = box_height * aspect_ratio
scale = np.array(
[box_width * 1.0 / pixel_std, box_height * 1.0 / pixel_std],
dtype=np.float32)
if center[0] != -1:
scale = scale * 1.25
return center, scale
def compute_iou_single_box(curr_img_boxes, next_img_boxes):# Order: top, bottom, left, right
intersect_vert = min([curr_img_boxes[1], next_img_boxes[1]]) - max([curr_img_boxes[0], next_img_boxes[0]])
intersect_hori = min([curr_img_boxes[3], next_img_boxes[3]]) - max([curr_img_boxes[2], next_img_boxes[2]])
union_vert = max([curr_img_boxes[1], next_img_boxes[1]]) - min([curr_img_boxes[0], next_img_boxes[0]])
union_hori = max([curr_img_boxes[3], next_img_boxes[3]]) - min([curr_img_boxes[2], next_img_boxes[2]])
if intersect_vert > 0 and intersect_hori > 0 and union_vert > 0 and union_hori > 0:
corresponding_coefficient = float(intersect_vert) * float(intersect_hori) / (float(curr_img_boxes[1] - curr_img_boxes[0]) * float(curr_img_boxes[3] - curr_img_boxes[2]) + float(next_img_boxes[1] - next_img_boxes[0]) * float(next_img_boxes[3] - next_img_boxes[2]) - float(intersect_vert) * float(intersect_hori))
else:
corresponding_coefficient = 0.0
return corresponding_coefficient
def convert_node_ids(mapping_node_id_to_bbox, mapping_edge_id_to_cost):
src_id = 1
dst_id = 2 * max(mapping_node_id_to_bbox) + 2 # 其余node变成了2×node,2×node+1
result_mapping_node_id_to_bbox = {}
result_mapping_node_id_to_bbox_str = ''
# Allen: make sure that even a traj with only 2 nodes and one edge can be involved
most_unreliable_edge_cost = max([mapping_edge_id_to_cost[x] for x in mapping_edge_id_to_cost])
even_node_cost = math.log(1.0 / 2 / 1.0)
src_dst_node_cost = math.log(maximum_possible_number)
# even_node_cost_add = -abs(2 * src_dst_node_cost + even_node_cost) - 0.1 # -abs(2 * src_dst_node_cost + most_unreliable_edge_cost + 2 * even_node_cost) / 2 - 0.1
even_node_cost_add = -abs(2 * src_dst_node_cost + even_node_cost) # -abs(2 * src_dst_node_cost + most_unreliable_edge_cost + 2 * even_node_cost) / 2 - 0.1
for mapping_node_id_to_bbox_key in mapping_node_id_to_bbox:
result_mapping_node_id_to_bbox[str(src_id)+'_'+str(int(mapping_node_id_to_bbox_key) * 2)] = math.log(maximum_possible_number) # 源到该节点
result_mapping_node_id_to_bbox[str(int(mapping_node_id_to_bbox_key) * 2)+'_'+str(int(mapping_node_id_to_bbox_key) * 2 + 1)] = math.log(1.0 / 2 / 1.0)+even_node_cost_add # 该节点自身cost math.log(1.0 / 2 / mapping_node_id_to_bbox[mapping_node_id_to_bbox_key][1])
result_mapping_node_id_to_bbox[str(int(mapping_node_id_to_bbox_key) * 2 + 1)+'_'+str(dst_id)] = math.log(maximum_possible_number) # 该节点到汇节点的cost
result_mapping_node_id_to_bbox_str += ('a*' + str(src_id)+'*'+str(int(mapping_node_id_to_bbox_key) * 2) + '*' + str(math.log(maximum_possible_number)) + '~')
result_mapping_node_id_to_bbox_str += ('a*' + str(int(mapping_node_id_to_bbox_key) * 2)+'*'+str(int(mapping_node_id_to_bbox_key) * 2 + 1) + '*' + str(math.log(1.0 / 2 / 1.0)+even_node_cost_add) + '~') # str(math.log(1.0 / 2 / mapping_node_id_to_bbox[mapping_node_id_to_bbox_key][1])) + '~')
result_mapping_node_id_to_bbox_str += ('a*' + str(int(mapping_node_id_to_bbox_key) * 2 + 1)+'*'+str(dst_id) + '*' + str(math.log(maximum_possible_number)) + '~')
return result_mapping_node_id_to_bbox, result_mapping_node_id_to_bbox_str
def convert_edge_ids(mapping_edge_id_to_cost):
result_mapping_edge_id_to_cost = {}
result_mapping_edge_id_to_cost_str = ''
for mapping_edge_id_to_cost_key in mapping_edge_id_to_cost:
curr_edge_former_id = int(mapping_edge_id_to_cost_key.split('_')[0]) * 2 + 1
curr_edge_latter_id = int(mapping_edge_id_to_cost_key.split('_')[1]) * 2
result_mapping_edge_id_to_cost[str(curr_edge_former_id)+'_'+str(curr_edge_latter_id)] = mapping_edge_id_to_cost[mapping_edge_id_to_cost_key]
result_mapping_edge_id_to_cost_str += ('a*' + str(curr_edge_former_id)+'*'+str(curr_edge_latter_id)+'*'+str(mapping_edge_id_to_cost[mapping_edge_id_to_cost_key])+'~')
return result_mapping_edge_id_to_cost, result_mapping_edge_id_to_cost_str
# input
# idx_stride_between_frame_pair: temporal stride between current frame pair
# curr_frame_dict: a dict storing 'bbox_list', 'head_bbox_list', 'box_confidence_scores', 'target_body_box_coord' and 'img_dir' of former frame in current frame pair
# tracklet_pose_collection: dicts of all frames
# next_frame_dict: a dict storing 'bbox_list', 'head_bbox_list', 'box_confidence_scores', 'target_body_box_coord' and 'img_dir' of latter frame in current frame pair
# person_to_person_matching_matrix_normalized: output of the last function
# node_id_cnt: starting node id of nodes in former frame in current frame pair
# tracklet_inner_idx: frame id of the former frame
# mapping_node_id_to_bbox: an empty dict
# mapping_node_id_to_features: an empty dict
# mapping_edge_id_to_cost: an empty dict
# mapping_frameid_bbox_to_features: a dict mapping string 'frameid_bbox coordinates' to a 512-D feature vector, the string 'frameid_bbox coordinates' has length 36, an example is '0930[(467.0, 313.0), (508.0, 424.0)]' where 0930 is frame id, the coordinates are in the format [(left, top), (right, bottom)]
# output
# mapping_node_id_to_bbox: a dict, each key is an interger node id, each node is the index of one bbox in a batch of frames, each value is a list with three elements:
# bbox coordinates [(left coordinate, top coordinate), (right coordinate, bottom coordinate)]
# bbox confidence a floating number
# a string indicating frame name, example '0000.jpg'
# mapping_node_id_to_features: a dict, each key is same as the keys in mapping_node_id_to_bbox, the value is a 512-D floating feature vector of the person in the bbox
# mapping_edge_id_to_cost: a dict, each key is a string, example '12_13' describes the matching error between node '12' and node '13', each value is a floating number
def prepare_costs_for_tracking_alg(idx_stride_between_frame_pair, curr_frame_dict, tracklet_pose_collection, next_frame_dict, person_to_person_matching_matrix_normalized, node_id_cnt, tracklet_inner_idx, mapping_node_id_to_bbox, mapping_node_id_to_features, mapping_edge_id_to_cost, mapping_frameid_bbox_to_features):
if idx_stride_between_frame_pair == 1:
for idx_bbox in range(len(curr_frame_dict['bbox_list'])):
if node_id_cnt + idx_bbox not in mapping_node_id_to_bbox:
mapping_node_id_to_bbox[node_id_cnt + idx_bbox] = [curr_frame_dict['bbox_list'][idx_bbox], curr_frame_dict['box_confidence_scores'][idx_bbox], tracklet_pose_collection[tracklet_inner_idx]['img_dir'].split('/')[-1]]
mapping_node_id_to_features[node_id_cnt + idx_bbox] = mapping_frameid_bbox_to_features[curr_frame_dict['img_dir'].split('/')[-1][:-4] + str(curr_frame_dict['bbox_list'][idx_bbox])]
for idx_bbox in range(len(next_frame_dict['bbox_list'])):
if node_id_cnt + len(curr_frame_dict['bbox_list']) + idx_bbox not in mapping_node_id_to_bbox:
mapping_node_id_to_bbox[node_id_cnt + len(curr_frame_dict['bbox_list']) + idx_bbox] = [next_frame_dict['bbox_list'][idx_bbox], next_frame_dict['box_confidence_scores'][idx_bbox],
tracklet_pose_collection[tracklet_inner_idx + idx_stride_between_frame_pair]['img_dir'].split('/')[-1]]
mapping_node_id_to_features[node_id_cnt + len(curr_frame_dict['bbox_list']) + idx_bbox] = \
mapping_frameid_bbox_to_features[next_frame_dict['img_dir'].split('/')[-1][:-4] + str(next_frame_dict['bbox_list'][idx_bbox])]
for idx_bbox_row in range(len(curr_frame_dict['bbox_list'])):
for idx_bbox_col in range(len(next_frame_dict['bbox_list'])):
if person_to_person_matching_matrix_normalized[idx_bbox_row, idx_bbox_col] != 0.0:
mapping_edge_id_to_cost[str(node_id_cnt + idx_bbox_row) + '_' + str(node_id_cnt + len(curr_frame_dict['bbox_list']) + idx_bbox_col)] = math.log(
1.0 / person_to_person_matching_matrix_normalized[idx_bbox_row, idx_bbox_col] / 2.0)
elif idx_stride_between_frame_pair == 2:
middle_frame_dict = tracklet_pose_collection[tracklet_inner_idx + idx_stride_between_frame_pair - 1]
for idx_bbox in range(len(next_frame_dict['bbox_list'])):
if node_id_cnt + len(curr_frame_dict['bbox_list']) + len(middle_frame_dict['bbox_list']) + idx_bbox not in mapping_node_id_to_bbox:
mapping_node_id_to_bbox[node_id_cnt + len(curr_frame_dict['bbox_list']) + len(middle_frame_dict['bbox_list']) + idx_bbox] = [next_frame_dict['bbox_list'][idx_bbox], next_frame_dict['box_confidence_scores'][idx_bbox],
tracklet_pose_collection[tracklet_inner_idx + idx_stride_between_frame_pair]['img_dir'].split('/')[-1]]
mapping_node_id_to_features[node_id_cnt + len(curr_frame_dict['bbox_list']) + len(middle_frame_dict['bbox_list']) + idx_bbox] = \
mapping_frameid_bbox_to_features[next_frame_dict['img_dir'].split('/')[-1][:-4] + str(next_frame_dict['bbox_list'][idx_bbox])]
for idx_bbox_row in range(len(curr_frame_dict['bbox_list'])):
for idx_bbox_col in range(len(next_frame_dict['bbox_list'])):
if person_to_person_matching_matrix_normalized[idx_bbox_row, idx_bbox_col] != 0.0:
mapping_edge_id_to_cost[str(node_id_cnt + idx_bbox_row) + '_' + str(node_id_cnt + len(curr_frame_dict['bbox_list']) + len(middle_frame_dict['bbox_list']) + idx_bbox_col)] = math.log(
1.0 / person_to_person_matching_matrix_normalized[idx_bbox_row, idx_bbox_col] / 2.0)
elif idx_stride_between_frame_pair > 2:
raise Exception('Not implemented yet!')
return mapping_node_id_to_bbox, mapping_node_id_to_features, mapping_edge_id_to_cost
def tracking(mapping_node_id_to_bbox, mapping_edge_id_to_cost, tracklet_inner_cnt):
# result_mapping_node_id_to_bbox:每个节点与source\sink\初始化
result_mapping_node_id_to_bbox, result_mapping_node_id_to_bbox_str = convert_node_ids(mapping_node_id_to_bbox, mapping_edge_id_to_cost)
result_mapping_edge_id_to_cost, result_mapping_edge_id_to_cost_str = convert_edge_ids(mapping_edge_id_to_cost)
transfer_data_to_tracker = str(2 * len(mapping_node_id_to_bbox) + 2) + '*' + str(
len((result_mapping_node_id_to_bbox_str + result_mapping_edge_id_to_cost_str).split('~')) - 1) + '~' \
+ result_mapping_node_id_to_bbox_str + result_mapping_edge_id_to_cost_str
transfer_data_to_tracker = transfer_data_to_tracker[:-1] # 转化为ssp算法需要的格式
if dump_further_switch_optimizer == 1:
out_file = open(os.path.join(dump_curr_video_name, 'mapping_node_id_to_bbox' + str(tracklet_inner_cnt + 1 - tracklet_len) + 'to' + str(tracklet_inner_cnt) + '.json'), "w")
json.dump(mapping_node_id_to_bbox, out_file)
out_file.close()
out_file = open(os.path.join(dump_curr_video_name, 'mapping_edge_id_to_cost' + str(tracklet_inner_cnt + 1 - tracklet_len) + 'to' + str(tracklet_inner_cnt) + '.json'), "w")
json.dump(mapping_edge_id_to_cost, out_file)
out_file.close()
out_file = os.path.join(dump_curr_video_name, 'result_mapping_node_id_to_bbox_str' + str(tracklet_inner_cnt + 1 - tracklet_len) + 'to' + str(tracklet_inner_cnt) + '.json')
json.dump(result_mapping_node_id_to_bbox_str, codecs.open(out_file, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True)
out_file = os.path.join(dump_curr_video_name, 'result_mapping_edge_id_to_cost_str' + str(tracklet_inner_cnt + 1 - tracklet_len) + 'to' + str(tracklet_inner_cnt) + '.json')
json.dump(result_mapping_edge_id_to_cost_str, codecs.open(out_file, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True)
out_file = os.path.join(dump_curr_video_name, 'transfer_data_to_tracker' + str(tracklet_inner_cnt + 1 - tracklet_len) + 'to' + str(tracklet_inner_cnt) + '.json')
json.dump(transfer_data_to_tracker, codecs.open(out_file, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True)
tracking_start_time = time.time()
gc.collect()
p = Popen('call/call', stdin=PIPE, stdout=PIPE, encoding='gbk')
result = p.communicate(input=transfer_data_to_tracker)
p.terminate()
p.wait()
result = [result[0], result[1]]
if dump_further_switch_optimizer == 1:
out_file = open(os.path.join(dump_curr_video_name, 'result0_' + str(tracklet_inner_cnt + 1 - tracklet_len) + 'to' + str(tracklet_inner_cnt) + '.json'), "w")
json.dump(result[0], out_file)
out_file.close()
tracking_end_time = time.time()
print(str(tracking_end_time - tracking_start_time))
return result
def compute_iou_between_body_and_head(head_box_detected, box_detected):#[(left, top), (right, bottom)]
corresponding_coefficient_matrix = np.zeros((len(head_box_detected), len(box_detected)))
for idx_row in range(len(head_box_detected)):
for idx_col in range(len(box_detected)):
intersect_vert = min([head_box_detected[idx_row][1][1], box_detected[idx_col][1][1]]) - max([head_box_detected[idx_row][0][1], box_detected[idx_col][0][1]])
intersect_hori = min([head_box_detected[idx_row][1][0], box_detected[idx_col][1][0]]) - max([head_box_detected[idx_row][0][0], box_detected[idx_col][0][0]])
union_vert = head_box_detected[idx_row][1][1] - head_box_detected[idx_row][0][1]
union_hori = head_box_detected[idx_row][1][0] - head_box_detected[idx_row][0][0]
if intersect_vert > 0 and intersect_hori > 0 and union_vert > 0 and union_hori > 0:
corresponding_coefficient_matrix[idx_row, idx_col] = float(intersect_vert) * float(intersect_hori) / float(union_vert) / float(union_hori)
else:
corresponding_coefficient_matrix[idx_row, idx_col] = 0.0
return corresponding_coefficient_matrix
def compute_iou_between_bbox_list(head_box_detected, box_detected):#[(left, top), (right, bottom)]
corresponding_coefficient_matrix = np.zeros((len(head_box_detected), len(box_detected)))
for idx_row in range(len(head_box_detected)):
for idx_col in range(len(box_detected)):
corresponding_coefficient_matrix[idx_row, idx_col] = compute_iou_single_box([head_box_detected[idx_row][0][1], head_box_detected[idx_row][1][1], head_box_detected[idx_row][0][0], head_box_detected[idx_row][1][0]], \
[box_detected[idx_col][0][1], box_detected[idx_col][1][1], box_detected[idx_col][0][0], box_detected[idx_col][1][0]])
return corresponding_coefficient_matrix
def evaluate_prediction(dataloader, data_dict):
if not is_main_process():
return 0, 0, None
logger.info("Evaluate in main process...")
annType = ["segm", "bbox", "keypoints"]
# inference_time = statistics[0].item()
# track_time = statistics[1].item()
# n_samples = statistics[2].item()
# a_infer_time = 1000 * inference_time / (n_samples * self.dataloader.batch_size)
# a_track_time = 1000 * track_time / (n_samples * self.dataloader.batch_size)
# time_info = ", ".join(
# [
# "Average {} time: {:.2f} ms".format(k, v)
# for k, v in zip(
# ["forward", "track", "inference"],
# [a_infer_time, a_track_time, (a_infer_time + a_track_time)],
# )
# ]
# )
# info = time_info + "\n"
# Evaluate the Dt (detection) json comparing with the ground truth
if len(data_dict) > 0:
cocoGt = dataloader.dataset.coco
_, tmp = tempfile.mkstemp()
json.dump(data_dict, open(tmp, "w"))
cocoDt = cocoGt.loadRes(tmp)
'''
try:
from yolox.layers import COCOeval_opt as COCOeval
except ImportError:
from pycocotools import cocoeval as COCOeval
logger.warning("Use standard COCOeval.")
'''
#from pycocotools.cocoeval import COCOeval
from yolox.layers import COCOeval_opt as COCOeval
cocoEval = COCOeval(cocoGt, cocoDt, annType[1])
cocoEval.evaluate()
cocoEval.accumulate()
redirect_string = io.StringIO()
with contextlib.redirect_stdout(redirect_string):
cocoEval.summarize()
# info += redirect_string.getvalue()
return cocoEval.stats[0], cocoEval.stats[1]
else:
return 0, 0
def convert_to_coco_format(dataloader, outputs, info_imgs, ids):
data_list = []
for (output, img_h, img_w, img_id) in zip(
outputs, info_imgs[0], info_imgs[1], ids
):
if output is None:
continue
output = output.cpu()
bboxes = output[:, 0:4]
# preprocessing: resize
scale = min(
dataloader.dataset.img_size[0] / float(img_h), dataloader.dataset.img_size[1] / float(img_w)
)
bboxes /= scale
bboxes = xyxy2xywh(bboxes)
cls = output[:, 6] # 0
scores = output[:, 4] * output[:, 5]
for ind in range(bboxes.shape[0]):
label = dataloader.dataset.class_ids[int(cls[ind])]
pred_data = {
"image_id": int(img_id),
"category_id": label,
"bbox": bboxes[ind].numpy().tolist(),
"score": scores[ind].numpy().item(),
"segmentation": [],
} # COCO json format
data_list.append(pred_data)
return data_list
def tracklet_collection(gmc,img_path,img_size,outputs, img_info, box_detected, box_confidence_scores, tracklet_pose_collection,tracklet_pose_collection_second,bbox_confidence_threshold = (0.6,0.1)):
# img_info["ratio"] = img
img_h,img_w = img_info["height"], img_info["width"]
output = outputs[0]
output = output.cpu()
bboxes = output[:, 0:4]
# preprocessing: resize
scale = min(
img_size[0] / float(img_h), img_size[1] / float(img_w)
)
bboxes /= scale # xyxy
#bboxes_wh = xyxy2xywh(bboxes)
cls = output[:, 6] # 0
scores = output[:, 4] * output[:, 5]
for ind in range(bboxes.shape[0]):
width = abs(float(bboxes[ind][2].data.cpu().numpy()) - float(bboxes[ind][0].data.cpu().numpy()))
heigth = abs(float(bboxes[ind][1].data.cpu().numpy()) - float(bboxes[ind][3].data.cpu().numpy()))
aspect_ratio = width / heigth
if aspect_ratio > 1.6 or width*heigth < 100:
continue
box_detected.append([(float(bboxes[ind][0].data.cpu().numpy()), float(bboxes[ind][1].data.cpu().numpy())), (float(bboxes[ind][2].data.cpu().numpy()), float(bboxes[ind][3].data.cpu().numpy()))])
box_confidence_scores.append(float(scores[ind].data.cpu().numpy()) + 1e-4*random.random())
# warp = gmc.apply(img_info["raw_img"], box_detected)
# box_detected = multi_gmc(box_detected,warp)
box_detected_high = [box_detected[box_confidence_scores.index(x)] for x in box_confidence_scores if x >= bbox_confidence_threshold[0]] # 0.4
box_confidence_scores_high = [box_confidence_scores[box_confidence_scores.index(x)] for x in box_confidence_scores if x >= bbox_confidence_threshold[0]]
box_detected_second = [box_detected[box_confidence_scores.index(x)] for x in box_confidence_scores if x < bbox_confidence_threshold[0] and x > bbox_confidence_threshold[1]]
box_confidence_scores_second = [box_confidence_scores[box_confidence_scores.index(x)] for x in box_confidence_scores if x < bbox_confidence_threshold[0] and x > bbox_confidence_threshold[1]]
if len(box_detected) == 0:
tracklet_pose_collection.append([])
return tracklet_pose_collection
tracklet_pose_collection_tmp = {}
tracklet_pose_collection_tmp['bbox_list'] = box_detected_high
tracklet_pose_collection_tmp['box_confidence_scores'] = box_confidence_scores_high
tracklet_pose_collection_tmp['img_dir'] = img_path
tracklet_pose_collection_tmp['foreignmatter_bbox_list'] = []
tracklet_pose_collection_tmp['foreignmatter_box_confidence_scores'] = []
tracklet_pose_collection.append(tracklet_pose_collection_tmp)
## second thresh ##
# if len(box_detected_second) > 0: # 只有大于0的时候才加入
tracklet_pose_collection_second_tmp = {}
tracklet_pose_collection_second_tmp['bbox_list'] = box_detected_second
tracklet_pose_collection_second_tmp['box_confidence_scores'] = box_confidence_scores_second
tracklet_pose_collection_second_tmp['img_dir'] = img_path
tracklet_pose_collection_second.append(tracklet_pose_collection_second_tmp)
# img = cv2.imread(img_path)
# dstpath = os.path.dirname(img_path.replace('img1','detect'))
# imgpath = img_path.split('/')[-1]
# if not os.path.exists(dstpath):
# os.makedirs(dstpath,exist_ok=True)
# for idx,bbox in enumerate(box_detected):
# # if round(box_confidence_scores[idx],2) > 0.6:
# # continue
# cv2.rectangle(img,(int(bbox[0][0]),int(bbox[0][1])),(int(bbox[1][0]),int(bbox[1][1])),(0,255,0),2)
# cv2.putText(img,str(round(box_confidence_scores[idx],2)),(int((int(bbox[0][0])+int(bbox[1][0]))/2),int((int(bbox[0][1])+int(bbox[1][1]))/2)),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)
# cv2.imwrite(os.path.join(dstpath,imgpath),img)
return tracklet_pose_collection,tracklet_pose_collection_second
def compute_inter_person_similarity_worker(input_list, whether_use_iou_similarity_or_not,whether_use_reid_similarity_or_not):
# tracklet_inner_idx: 帧索引 tracklet_inner_base_idx:当前batch开始的帧 node_id_cnt
tracklet_inner_idx, tracklet_inner_base_idx, node_id_cnt, tracklet_pose_collection, idx_stride_between_frame_pair, maximum_possible_number, max_row_num_of_person_to_person_matching_matrix_normalized, \
max_col_num_of_person_to_person_matching_matrix_normalized, num_of_person_to_person_matching_matrix_normalized_copies, node_id_cnt_list, all_people_features = \
input_list[0], input_list[1], input_list[2], input_list[3], input_list[4], input_list[5], input_list[6], input_list[7], input_list[8], input_list[9], input_list[10]
# collect all bounding boxes in frame pairs
curr_frame_dict = tracklet_pose_collection[tracklet_inner_idx] # 当前帧tracklet信息
next_frame_dict = tracklet_pose_collection[tracklet_inner_idx + idx_stride_between_frame_pair] # 下一个桢tracklet信息
# matrix storing the iou similarity between each box from previous frame and each box from next frame, each row corresponds to one box in prev, each col - one box in next
person_to_person_matching_matrix = np.ones((len(curr_frame_dict['bbox_list']), len(next_frame_dict['bbox_list']))) * maximum_possible_number # 乘以max_number的含义?
# matrix storing the appearance similarity between ...
person_to_person_matching_matrix_iou = np.zeros((len(curr_frame_dict['bbox_list']), len(next_frame_dict['bbox_list'])))
# ????
person_to_person_depth_matching_matrix_iou = np.ones((len(curr_frame_dict['bbox_list']), len(next_frame_dict['bbox_list']))) * 0.5
person_to_person_matching_matrix_confidence = np.zeros((len(curr_frame_dict['bbox_list']), len(next_frame_dict['bbox_list'])))
person_to_person_matching_matrix_offset = np.zeros((len(curr_frame_dict['bbox_list']), len(next_frame_dict['bbox_list'])))
# person_to_person_matching_matrix_confidence: 每个元素表示两个人的置信度之和
# evaluate_time_start = time.time()
for curr_person_bbox_coord in curr_frame_dict['bbox_list']:
for next_person_bbox_coord in next_frame_dict['bbox_list']:
# to find the index of each bounding box in all people in current batch of frames
# if curr_frame_dict['box_confidence_scores'][curr_frame_dict['bbox_list'].index(curr_person_bbox_coord)] > 1.0 or next_frame_dict['box_confidence_scores'][next_frame_dict['bbox_list'].index(next_person_bbox_coord)] > 1.0:
# person_to_person_matching_matrix[curr_frame_dict['bbox_list'].index(curr_person_bbox_coord), next_frame_dict['bbox_list'].index(next_person_bbox_coord)] = 1.0
# else:
vector1 = all_people_features[int(np.sum([len(x['bbox_list']) for x in tracklet_pose_collection[0:tracklet_inner_idx]]) + curr_frame_dict['bbox_list'].index(curr_person_bbox_coord))] # 当前帧bbox的特征向量
vector2 = all_people_features[int(np.sum([len(x['bbox_list']) for x in tracklet_pose_collection[0:(tracklet_inner_idx + idx_stride_between_frame_pair)]]) + next_frame_dict['bbox_list'].index(next_person_bbox_coord))] # 下一帧bbox的特征向量
person_to_person_matching_matrix[curr_frame_dict['bbox_list'].index(curr_person_bbox_coord), next_frame_dict['bbox_list'].index(next_person_bbox_coord)] = \
1.0 - min([np.dot(vector1, vector2)/(np.linalg.norm(vector1)*np.linalg.norm(vector2)), 1.0])
person_to_person_matching_matrix_iou[
curr_frame_dict['bbox_list'].index(curr_person_bbox_coord), next_frame_dict['bbox_list'].index(next_person_bbox_coord)] = \
min([max([compute_iou_single_box([curr_person_bbox_coord[0][1], curr_person_bbox_coord[1][1], curr_person_bbox_coord[0][0], curr_person_bbox_coord[1][0]], \
[next_person_bbox_coord[0][1], next_person_bbox_coord[1][1], next_person_bbox_coord[0][0], next_person_bbox_coord[1][0]]), 0.0]), 1.0])
person_to_person_depth_matching_matrix_iou[
curr_frame_dict['bbox_list'].index(curr_person_bbox_coord), next_frame_dict['bbox_list'].index(next_person_bbox_coord)] = \
1.0 / max([abs(curr_person_bbox_coord[1][1] - next_person_bbox_coord[1][1]), \
person_to_person_depth_matching_matrix_iou[curr_frame_dict['bbox_list'].index(curr_person_bbox_coord), next_frame_dict['bbox_list'].index(next_person_bbox_coord)]])
person_to_person_matching_matrix_confidence[
curr_frame_dict['bbox_list'].index(curr_person_bbox_coord), next_frame_dict['bbox_list'].index(next_person_bbox_coord)] = \
(curr_frame_dict['box_confidence_scores'][curr_frame_dict['bbox_list'].index(curr_person_bbox_coord)] + next_frame_dict['box_confidence_scores'][next_frame_dict['bbox_list'].index(next_person_bbox_coord)])/2
cons_curr = ((curr_person_bbox_coord[1][0] - curr_person_bbox_coord[0][0]) + (curr_person_bbox_coord[1][1]-curr_person_bbox_coord[0][1])) / 2.
cons_next = ((next_person_bbox_coord[1][0] - next_person_bbox_coord[0][0]) + (next_person_bbox_coord[1][1]-next_person_bbox_coord[0][1])) / 2.
person_to_person_matching_matrix_offset[
curr_frame_dict['bbox_list'].index(curr_person_bbox_coord), next_frame_dict['bbox_list'].index(next_person_bbox_coord)] = \
(abs((curr_person_bbox_coord[0][0]+curr_person_bbox_coord[1][0])/2.-(next_person_bbox_coord[0][0]+next_person_bbox_coord[1][0])/2.) + \
abs((curr_person_bbox_coord[0][1]+curr_person_bbox_coord[1][1])/2.-(next_person_bbox_coord[0][1]+next_person_bbox_coord[1][1])/2.)) / ((cons_curr+cons_next) /2.)
#person_to_person_matching_matrix_offset[person_to_person_matching_matrix_offset > 0.05] = 0.05
# person_to_person_matching_matrix_offset[person_to_person_matching_matrix_offset > 0.5] = 1
#person_to_person_matching_matrix_offset[np.where(person_to_person_matching_matrix_offset > 1.)] = 1.0
#denominator[np.where(denominator == 0)] = 1.0
#evaluate_time_end = time.time()
# corner case: only one person
if person_to_person_matching_matrix.shape[0] == 1 and person_to_person_matching_matrix.shape[1] == 1 and person_to_person_matching_matrix[0][0] == 0.0:
person_to_person_matching_matrix[0][0] = 1.0
else:
# replace zero entries in the matrix "person_to_person_matching_matrix" with half minimum value to facilitate division
person_to_person_matching_matrix[np.where(person_to_person_matching_matrix==0)] = np.min(person_to_person_matching_matrix[np.where(person_to_person_matching_matrix>0)]) / 2.0
# similarity is inversely proportional to matching error
person_to_person_matching_matrix = 1.0 / person_to_person_matching_matrix / np.max(
1.0 / person_to_person_matching_matrix) # similarity
person_to_person_matching_matrix_offset = 1.0 /person_to_person_matching_matrix_offset / np.max(1.0 / person_to_person_matching_matrix_offset)
# similarity is the summation of appearance and iou similarity
if whether_use_iou_similarity_or_not and whether_use_reid_similarity_or_not:
person_to_person_matching_matrix = person_to_person_matching_matrix * person_to_person_matching_matrix_iou #*person_to_person_matching_matrix_offset# +person_to_person_matching_matrix_offset # *person_to_person_matching_matrix_confidence # * person_to_person_depth_matching_matrix_iou
elif whether_use_iou_similarity_or_not and not whether_use_reid_similarity_or_not:# 只使用iou信息
person_to_person_matching_matrix = person_to_person_matching_matrix_iou #* person_to_person_matching_matrix_offset # +person_to_person_matching_matrix_offset
# 默认情况下为只是用reid信息
person_to_person_matching_matrix_copy = copy.deepcopy(person_to_person_matching_matrix)
denominator = person_to_person_matching_matrix_copy.max(axis=1).reshape(person_to_person_matching_matrix_copy.max(axis=1).shape[0], 1)
denominator[np.where(denominator==0)] = 1.0 # 每一列最大值
person_to_person_matching_matrix_copy_normalized = person_to_person_matching_matrix_copy / denominator
for idx_col in range(person_to_person_matching_matrix_copy_normalized.shape[1]):
if len(np.where(person_to_person_matching_matrix_copy_normalized[:, idx_col]==1.0)[0].tolist()) > 1:
list_idx_compete = np.where(person_to_person_matching_matrix_copy_normalized[:, idx_col] == 1.0)[0].tolist()
list_idx_compete_ori = np.argsort(person_to_person_matching_matrix_copy[:, idx_col][list_idx_compete]).tolist()
list_idx_compete_ordered = np.array(list_idx_compete)[list_idx_compete_ori].tolist()
for list_idx_compete_ordered_ele in list_idx_compete_ordered:
person_to_person_matching_matrix_copy_normalized[list_idx_compete_ordered_ele, :] *= 0.99**(len(list_idx_compete_ordered)-1-list_idx_compete_ordered.index(list_idx_compete_ordered_ele))
person_to_person_matching_matrix_copy_normalized *= 200
return person_to_person_matching_matrix_copy_normalized, idx_stride_between_frame_pair, node_id_cnt
# input:
# current_video_segment_representative_frames_current_tracklet_id: a floating vector describing the reid features of an identity in current batch of frames
# previous_video_segment_all_traj_all_object_features: a dict, each key is an ID in previous batch of frames, each value is corresponding feature vector in representative frame
def information_gain(current_video_segment_representative_frames_current_tracklet_id, previous_video_segment_all_traj_all_object_features):
# time_steps_shared_by_previous_traj = [y for y in previous_video_segment_all_traj_all_object_features[[x for x in previous_video_segment_all_traj_all_object_features][0]]]
# for previous_video_segment_ID in [x for x in previous_video_segment_all_traj_all_object_features][1:]:
# time_steps_shared_by_previous_traj = list(set(time_steps_shared_by_previous_traj).intersection(set([y for y in previous_video_segment_all_traj_all_object_features[previous_video_segment_ID]])))
# consider the case one person disappears for a long time, his appearance time may not overlap with other people's time steps, so this function exits
time_steps_shared_by_previous_traj = min([len(previous_video_segment_all_traj_all_object_features[x]) for x in previous_video_segment_all_traj_all_object_features])