-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval_det.py
More file actions
4396 lines (3490 loc) · 181 KB
/
Copy patheval_det.py
File metadata and controls
4396 lines (3490 loc) · 181 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import functools
import glob
import shutil
import sys
import pickle
import copy
import time
import multiprocessing
from multiprocessing.pool import ThreadPool
import json
import lzma
import functools
from datetime import datetime
from contextlib import closing
import imagesize
import paramparse
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pprint import pformat
from tqdm import tqdm
from prettytable import PrettyTable
from tabulate import tabulate
from collections import OrderedDict
import itertools
import eval_utils as utils
sys.path.append(utils.linux_path(os.path.expanduser('~'), '617', 'plotting'))
import concat_metrics
class Params(paramparse.CFG):
"""
:ivar check_seq_name: 'iou_thresh',
:ivar delete_tmp_files: 'None',
:ivar det_paths: 'file containing list of detection folders',
:ivar draw_plot: 'None',
:ivar gt_paths: 'file containing list of GT folders',
:ivar gt_root_dir: 'folder to save the animation result in',
:ivar img_ext: 'image extension',
:ivar img_paths: 'file containing list of image folders',
:ivar img_root_dir: 'folder to save the animation result in',
:ivar iou_thresh: 'iou_thresh',
:ivar labels_path: 'text file containing class labels',
:ivar no_animation: 'no animation is shown.',
:ivar no_plot: 'no plot is shown.',
:ivar out_root_dir: 'out_fname',
:ivar quiet: 'minimalistic console output.',
:ivar save_vis: 'None',
:ivar save_file_res: 'resolution of the saved video',
:ivar score_thresholds: 'iou_thresh',
:ivar set_class_iou: 'set IoU for a specific class.',
:ivar show_vis: 'None',
:ivar show_gt: 'None',
:ivar show_tp: 'None',
:ivar show_stats: 'None',
:ivar show_text: 'None',
:ivar vid_fmt: 'comma separated triple to specify the output video format: codec, FPS, extension',
:ivar a: 'no animation is shown.',
:ivar p: 'no plot is shown.',
:ivar eval_sim: evaluate already created simulated detections,
:ivar filter_ignored: remove GT and det objects with IOA > ignore_ioa_thresh with any of the ignored regions
supplied as
objects with class name "ignored"; mainly for the DETRAC dataset
:ivar assoc_method:
'0: new method with det-to-GT and GT-to-det symmetrical associations;'
'1: old method with only det-to-GT associations',
"""
def __init__(self):
paramparse.CFG.__init__(self, cfg_prefix='eval_det')
self.check_seq_name = 1
self.delete_tmp_files = 0
self.verbose = 1
self.save_dets = 0
self.save_as_imagenet_vid = 0
self.imagenet_vid_map_path = ''
self.concat = 1
self.sleep = 30
self.det_root_dir = ''
self.det_paths = ''
self.allow_missing_dets = 0
self.combine_dets = 0
self.normalized_dets = 0
"""remove patch ID suffix from det filenames"""
self.patch_dets = 0
"""alternative class names are used in some p2s-seg created csv files
e.g. ips instead of ipsc and dif instead of diff
"""
self.labels_remap = 0
self.draw_plot = 0
self.gt_paths = ''
self.gt_root_dir = ''
self.img_ext = ''
self.img_paths = ''
self.img_paths_suffix = []
self.img_root_dir = ''
self.all_img_dirs = 1
self.load_samples = []
self.load_samples_root = ''
self.load_samples_suffix = ''
self.iou_thresh = 0.25
self.labels_root = 'lists/classes/'
self.labels_path = ''
self.out_root_dir = '/data/mAP'
self.out_root_suffix = []
self.no_animation = False
self.no_plot = False
self.gt_pkl_dir = 'log/pkl'
self.det_pkl_dir = ''
self.load_gt = 0
self.gt_pkl = ''
self.gt_pkl_suffix = []
self.load_det = 0
self.save_det_pkl = 0
self.del_det_pkl = 0
self.save_lzma = 0
self.det_pkl = ''
self.quiet = False
self.score_thresholds = [0, ]
self.set_class_iou = [None, ]
self.show_vis = 0
self.show_each = 0
self.show_gt = 1
self.show_tp = 0
self.show_stats = 1
self.gt_check = 1
self.assoc_method = 1
self.fix_csv_cols = -1
self.fix_gt_cols = 0
self.fix_det_cols = 1
self.ignore_invalid_class = 0
self.enable_mask = 0
self.seq = []
self.start_id = 0
self.end_id = -1
self.img_start_id = 0
self.img_end_id = -1
self.write_summary = 1
self.compute_opt = 0
self.rec_ratios = ()
self.wt_avg = 0
self.n_threads = 1
"""allow_missing_gt=2 skips detections for files without GT"""
self.allow_missing_gt = 1
"""
allow entire sequences without any gt
usually happens only when sparsely sampling a sequence with many empty frames,
thereby ending up with all empty frames in the samples
"""
self.allow_empty_gt = 0
self.show_text = 1
self.gt_csv_name = 'annotations.csv'
self.gt_csv_suffix = ''
self.a = False
self.p = False
self.detection_names = []
self.vis_alpha = 0.5
self.save_sim_dets = 0
self.show_sim = 0
self.eval_sim = 0
self.sim_precs = (0.5, 0.60, 0.70, 0.80, 0.90, 1,)
self.sim_recs = (0.5, 0.60, 0.70, 0.80, 0.90, 1,)
"""imagewise"""
self.iw = 0
self.compute_rec_prec = 1
self.img_dir_name = ''
self.vid_det = 0
self.n_proc = 1
self.save_vis = 0
self.save_classes = []
self.save_cats = ['fn_det', 'fn_cls', 'fp_nex-whole', 'fp_nex-part', 'fp_cls', 'fp_dup']
self.auto_suffix = 0
self.batch_name = ''
self.save_suffix = ''
self.save_file_res = '1920x1080'
# self.save_file_res = '1600x900'
# self.save_file_res = '1280x720'
self.vid_fmt = 'mp4v,10,mp4'
self.check_det = 0
self.fps_to_gt = 0
self.ignore_exceptions = 0
self.ignore_inference_flag = 0
self.ignore_eval_flag = 0
self.show_pbar = True
self.monitor_scale = 1.5
self.fast_nms = 0
self.dup_nms = 0
self.debug = 0
self.ckpt_iter = ''
self.filter_ignored = 0
self.ignore_ioa_thresh = 0.25
self.conf_thresh = 0
self.seq_wise = 0
self.vid_stride = 0
self.class_agnostic = 0
self.det_nms = 0
self.batch_nms = 0
self.nms_thresh = 0
self.vid_nms_thresh = 0
self.sweep = Params.Sweep()
"""force sweep mode for the purpose of setting the output directory"""
self.force_sweep = 0
# self.sweep.nms_thresh = [0, ]
# self.sweep.vid_nms_thresh = [0, ]
# self.det_nms_all = [0, ]
# self._sweep_params = [
# 'det_nms',
# 'nms_thresh_',
# 'vid_nms_thresh_',
# ]
# @property
# def sweep_params(self):
# return self._sweep_params
class Sweep:
def __init__(self):
self.nms_thresh = [0, ]
self.vid_nms_thresh = [0, ]
self.det_nms = [0, ]
def evaluate(
params: Params,
seq_paths: list[str],
gt_classes: list[str],
gt_path_list: list[str],
all_seq_det_paths: list[str],
out_root_dir: str,
class_name_to_col: dict,
img_start_id=-1,
img_end_id=-1,
seq_to_samples=None,
_gt_data_dict=None,
raw_det_data_dict=None,
eval_result_dict=None,
fps_to_gt=1,
json_out_dir=None,
show_pbar=False,
vid_info=None,
):
if not params.verbose:
print_ = dummy_print
# tqdm = dummy_tqdm
else:
print_ = print
"""general init"""
if True:
assert out_root_dir, "out_root_dir must be provided"
compute_rec_prec = params.compute_rec_prec
assoc_method = params.assoc_method
det_pkl_dir = params.det_pkl_dir
gt_pkl_dir = params.gt_pkl_dir
save_file_res = params.save_file_res
vid_fmt = params.vid_fmt
iou_thresh = params.iou_thresh
save_vis = params.save_vis
save_classes = params.save_classes
save_cats = params.save_cats
show_vis = params.show_vis
show_each = params.show_each
show_text = params.show_text
show_stats = params.show_stats
show_gt = params.show_gt
show_tp = params.show_tp
draw_plot = params.draw_plot
# delete_tmp_files = params.delete_tmp_files
score_thresholds = params.score_thresholds
check_seq_name = params.check_seq_name
gt_check = params.gt_check
save_sim_dets = params.save_sim_dets
show_sim = params.show_sim
sim_precs = params.sim_precs
sim_recs = params.sim_recs
enable_mask = params.enable_mask
fix_csv_cols = params.fix_csv_cols
if fix_csv_cols >= 0:
params.fix_gt_cols = params.fix_det_cols = fix_csv_cols
fix_gt_cols = params.fix_gt_cols
fix_det_cols = params.fix_det_cols
ignore_invalid_class = params.ignore_invalid_class
write_summary = params.write_summary
compute_opt = params.compute_opt
rec_ratios = params.rec_ratios
wt_avg = params.wt_avg
n_threads = params.n_threads
allow_missing_gt = params.allow_missing_gt
img_dir_name = params.img_dir_name
n_score_thresholds = len(score_thresholds)
score_thresh = score_thresholds[0]
score_thresholds = np.asarray(score_thresholds).squeeze()
img_exts = ['jpg', 'png', 'bmp', 'jpeg']
save_w, save_h = [int(x) for x in save_file_res.split('x')]
video_h, video_w = save_h, save_w
codec, fps, vid_ext = vid_fmt.split(',')
fps = int(fps)
fourcc = cv2.VideoWriter_fourcc(*codec)
# fourcc = -1
# show_pbar = not show_vis
cls_cat_types = [
"raw",
"cls",
"tp",
"fp_dup",
"fp_cls",
"fp_nex-part",
"fp_nex-whole",
"fn_det",
"fn_cls",
]
cls_cat_to_col = {
"tp": "green",
"fp_nex": "red",
"fp_cls": "magenta",
"fp_dup": "yellow",
"fn_det": "red",
"fn_cls": "magenta",
}
if save_vis:
if not save_classes:
"""save all classes"""
save_classes = gt_classes[:]
if not save_cats:
"""save all status types"""
if show_tp == 2:
"""
show_tp=0: don't show TP
show_tp=2: show only TP
"""
save_cats = ['tp', ]
else:
save_cats = cls_cat_types[:]
n_seq = len(seq_paths)
if _gt_data_dict is None:
if n_seq != len(seq_paths):
raise AssertionError(
'Mismatch between the no. of image ({}) and GT ({}) sequences'.format(n_seq, len(seq_paths)))
n_seq_det_paths = len(all_seq_det_paths)
if raw_det_data_dict is None:
if n_seq < n_seq_det_paths:
print_(f'Mismatch between n_seq ({n_seq}) and n_seq_det_paths ({n_seq_det_paths})')
all_seq_det_paths = all_seq_det_paths[:n_seq]
seq_root_dirs = [os.path.dirname(x) for x in seq_paths]
seq_name_list = [os.path.basename(x) for x in seq_paths]
if json_out_dir is None:
json_out_dir = seq_root_dirs[0]
# if not os.path.exists(pkl_files_path):
# os.makedirs(pkl_files_path)
out_root_name = os.path.basename(out_root_dir)
plots_out_dir = utils.linux_path(out_root_dir, 'plots')
if draw_plot:
print_('Saving plots to: {}'.format(plots_out_dir))
os.makedirs(plots_out_dir, exist_ok=True)
if not det_pkl_dir:
det_pkl_dir = out_root_dir
# if params.seq >= 0:
# det_pkl_dir = os.path.dirname(out_root_dir)
if not gt_pkl_dir:
gt_pkl_dir = out_root_dir
det_pkl = params.det_pkl
if params.save_lzma:
pkl_ext = 'xz'
else:
pkl_ext = 'pkl'
if not det_pkl:
det_pkl = f"raw_det_data_dict.{pkl_ext}"
det_pkl = utils.linux_path(det_pkl_dir, det_pkl)
gt_pkl = params.gt_pkl
gt_pkl_suffix = params.gt_pkl_suffix
if not gt_pkl:
gt_pkl = f"{out_root_name}.{pkl_ext}"
if gt_pkl_suffix:
gt_pkl_suffix = '-'.join(gt_pkl_suffix)
gt_pkl = utils.add_suffix(gt_pkl, gt_pkl_suffix, sep='-')
gt_pkl = utils.linux_path(gt_pkl_dir, gt_pkl)
if img_start_id >= 0 and img_end_id >= 0:
assert img_end_id >= img_start_id, "img_end_id must be >= img_start_id"
img_suffix = f'img_{img_start_id}'
if img_start_id != img_end_id:
img_suffix = f'{img_suffix}_{img_end_id}'
gt_pkl = utils.add_suffix(gt_pkl, img_suffix)
det_pkl = utils.add_suffix(det_pkl, img_suffix)
pkl_suffixes = []
if params.enable_mask:
pkl_suffixes.append('mask')
if params.filter_ignored:
pkl_suffixes.append('ign')
if params.class_agnostic:
pkl_suffixes.append('agn')
if pkl_suffixes:
pkl_out_suffix = '-'.join(pkl_suffixes)
gt_pkl = utils.add_suffix(gt_pkl, pkl_out_suffix, sep='-')
"""detection specific pkl_suffixes"""
"""added in out_root_dir instead"""
# if params.vid_nms_thresh_ > 0:
# pkl_suffixes.append(f'vnms_{params.vid_nms_thresh_:02d}')
# if params.nms_thresh_ > 0:
# pkl_suffixes.append(f'nms_{params.nms_thresh_:02d}')
# if pkl_suffixes:
# pkl_out_suffix = '-'.join(pkl_suffixes)
# det_pkl = utils.add_suffix(det_pkl, pkl_out_suffix, sep='-')
gt_class_data_dict = {
gt_class: {} for gt_class in gt_classes
}
if _gt_data_dict is not None:
gt_loaded = 1
# if params.class_agnostic:
# _gt_data_dict = _gt_data_dict['agn']
# else:
# _gt_data_dict = _gt_data_dict['mc']
gt_data_dict = copy.deepcopy(_gt_data_dict)
elif params.load_gt:
"""load GT data only if gt_pkl is explicitly provided"""
if not os.path.exists(gt_pkl):
msg = f"gt_pkl does not exist: {gt_pkl}"
if params.iw:
print_('\n' + msg + '\n')
return None
raise AssertionError(msg)
print_(f'loading GT data from {gt_pkl}')
if params.save_lzma:
with lzma.open(gt_pkl, 'rb') as f:
gt_data_dict = pickle.load(f)
else:
with open(gt_pkl, 'rb') as f:
gt_data_dict = pickle.load(f)
gt_loaded = 1
else:
gt_data_dict = {}
if params.filter_ignored:
gt_data_dict['ignored'] = {}
gt_loaded = 0
print_('Generating GT data')
if gt_loaded:
for _seq_path, _seq_gt_data_dict in gt_data_dict.items():
if _seq_path in ["counter_per_class", 'ignored']:
continue
for gt_class in gt_classes:
gt_class_data_dict[gt_class][_seq_path] = []
for _img_path, _img_objs in _seq_gt_data_dict.items():
for obj in _img_objs:
# if params.class_agnostic:
# obj['class'] = 'agnostic'
gt_class_data_dict[obj['class']][_seq_path].append(obj)
if raw_det_data_dict is not None:
if params.class_agnostic:
raw_det_data_dict = raw_det_data_dict['agn']
else:
raw_det_data_dict = raw_det_data_dict['mc']
# if params.vid_nms_thresh > 0 or params.nms_thresh > 0:
raw_det_data_dict = raw_det_data_dict[(params.vid_nms_thresh, params.nms_thresh)]
det_loaded = 1
else:
"""det data pkl must exist if it is explicitly provided but it is loaded if it exists
even if not explicitly provided"""
if params.det_pkl:
assert os.path.exists(det_pkl), f"det_pkl does not exist: {det_pkl}"
if params.load_det:
assert os.path.isfile(det_pkl), f"nonexistent det_pkl: {det_pkl}"
print_(f'loading detection data from {det_pkl}')
if params.save_lzma:
with lzma.open(det_pkl, 'rb') as f:
raw_det_data_dict = pickle.load(f)
else:
with open(det_pkl, 'rb') as f:
raw_det_data_dict = pickle.load(f)
det_loaded = 1
if params.del_det_pkl:
print_(f'deleting detection pkl: {det_pkl}')
os.remove(det_pkl)
else:
raw_det_data_dict = {}
nms_raw_det_data_dict = {}
det_loaded = 0
if not det_loaded:
print_('Generating detection data')
if params.save_det_pkl:
os.makedirs(det_pkl_dir, exist_ok=True)
_pause = 1
gt_counter_per_class = {}
gt_start_t = time.time()
gt_seq_names = [os.path.basename(_gt_path) for _gt_path in gt_path_list]
# unique_gt_seq_names = list(set(gt_seq_names))
if len(gt_seq_names) > 0 and gt_seq_names[0].endswith('.csv'):
gt_seq_names = [os.path.basename(os.path.dirname(_gt_path)) for _gt_path in gt_path_list]
# unique_gt_seq_names = list(set(gt_seq_names))
# assert len(gt_seq_names) == len(unique_gt_seq_names), "unable to find gt_seq_names"
csv_rename_dict = {
'VideoID': 'video_id',
'ImageID': 'filename',
'XMin': 'xmin',
'YMin': 'ymin',
'XMax': 'xmax',
'YMax': 'ymax',
'LabelName': 'class',
'MaskXY': 'mask',
'Confidence': 'confidence',
}
all_img_paths = []
img_path_to_size = {}
if isinstance(params.seq, int) and params.seq >= 0:
"""restrict processing to a single sequence"""
assert params.seq <= len(gt_path_list), f"invalid seq_wise id: {params.seq}"
gt_path_list = [gt_path_list[params.seq], ]
gt_seq_names = [gt_seq_names[params.seq], ]
seq_name_list = [seq_name_list[params.seq], ]
seq_paths = [seq_paths[params.seq], ]
all_seq_det_paths = [all_seq_det_paths[params.seq], ]
n_seq = 1
seq_path_ = seq_paths[0]
# if gt_loaded:
# gt_data_dict_ = {
# seq_path_: gt_data_dict[seq_path_]
# }
# if 'ignored' in gt_data_dict:
# gt_data_dict_['ignored'] = {
# seq_path_: gt_data_dict['ignored'][seq_path_]
# }
# gt_data_dict = gt_data_dict_
#
# if det_loaded:
# det_data_dict = {
# seq_name_list[0]: det_data_dict[seq_name_list[0]]
# }
enable_nms = False
if params.batch_nms:
assert params.vid_nms_thresh == 0 and params.nms_thresh == 0, \
"vid_nms_thresh and nms_thresh must be 0 in batch_nms mode"
enable_nms = True
if params.sweep.nms_thresh:
print_(f'performing batch NMS with thresholds {params.sweep.nms_thresh}')
if params.sweep.vid_nms_thresh:
print_(f'performing batch video NMS with thresholds {params.sweep.vid_nms_thresh}')
elif params.nms_thresh > 0 or params.vid_nms_thresh > 0:
enable_nms = True
if params.nms_thresh > 0:
print_(f'performing NMS with threshold {params.nms_thresh:d}%')
if params.vid_nms_thresh > 0:
print_(f'performing video NMS with threshold {params.vid_nms_thresh:d}%')
if params.save_as_imagenet_vid:
imagenet_vid_out_path = utils.linux_path(out_root_dir, 'imagenet_vid.txt')
print(f'\nimagenet_vid_out_path: {imagenet_vid_out_path}\n')
"""overwrite existing file if it exists with an empty file"""
open(imagenet_vid_out_path, "w").close()
assert params.imagenet_vid_map_path, "imagenet_vid_map_path must be provided"
class_name_map_file = utils.linux_path(params.imagenet_vid_map_path, "map_vid.txt")
filename_to_frame_map_file = utils.linux_path(params.imagenet_vid_map_path, "val.txt")
class_name_map = open(class_name_map_file, "r").readlines()
filename_to_frame_map = open(filename_to_frame_map_file, "r").readlines()
class_name_map = [k.strip().split(' ') for k in class_name_map]
class_name_to_id = {k[2]: int(k[1]) for k in class_name_map}
filename_to_frame_map = [k.strip().split(' ') for k in filename_to_frame_map]
filename_to_frame_index = {k[0]: int(k[1]) for k in filename_to_frame_map}
"""read gt and det including filtering and NMS"""
read_iter = enumerate(zip(gt_path_list, gt_seq_names, strict=True))
if params.batch_nms and not params.verbose:
read_iter = tqdm(read_iter, total=len(gt_path_list))
for seq_idx, (_gt_path, gt_seq_name) in read_iter:
# if gt_loaded and det_loaded:
# break
seq_name = seq_name_list[seq_idx]
seq_path = seq_paths[seq_idx]
if img_dir_name:
seq_img_dir = utils.linux_path(seq_path, img_dir_name)
else:
seq_img_dir = seq_path
if seq_to_samples is not None:
seq_img_paths = seq_to_samples[seq_path]
else:
is_valid_img = lambda x: os.path.splitext(x.lower())[1][1:] in img_exts if not params.img_ext else \
os.path.splitext(x)[1][1:] == params.img_ext
seq_img_gen = [[utils.linux_path(dirpath, f) for f in filenames if is_valid_img(f)]
for (dirpath, dirnames, filenames) in os.walk(seq_img_dir, followlinks=True)]
seq_img_paths = [item for sublist in seq_img_gen for item in sublist]
assert seq_img_paths, "empty seq_img_paths"
seq_img_name_to_path = {
os.path.basename(seq_img_path): seq_img_path for seq_img_path in seq_img_paths
}
seq_gt_ignored_dict = None
if gt_loaded:
gt_img_paths = sorted(list(gt_data_dict[seq_path].keys()))
gt_filenames = gt_img_paths[:]
if params.filter_ignored:
seq_gt_ignored_dict = gt_data_dict['ignored'][seq_path]
all_img_paths += gt_img_paths
if gt_loaded and det_loaded:
continue
print_(f'\n\nProcessing sequence {seq_idx + 1:d}/{n_seq:d}')
print_(f'seq_path: {seq_path:s}')
"""read GT from csv"""
if not gt_loaded:
gt_path = _gt_path
if not os.path.isfile(gt_path):
# os.system('ls /data/ipsc')
# os.system(f'ls {gt_path}')
# os.system(f'ls {os.path.dirname(gt_path)}')
print_(os.listdir('/'))
print_(os.listdir(os.path.dirname(gt_path)))
raise AssertionError(f'GT file: {gt_path} does not exist')
print_(f'\ngt_path: {gt_path:s}')
seq_gt_data_dict = {}
seq_gt_ignored_dict = {}
for gt_class in gt_classes:
gt_class_data_dict[gt_class][seq_path] = []
df_gt = pd.read_csv(gt_path)
assert not df_gt.empty, f"empty gt_path: {gt_path}"
if seq_to_samples is not None:
sampled_filenames = [os.path.basename(seq_img_path) for seq_img_path in seq_img_paths]
df_gt = df_gt.loc[df_gt['filename'].isin(sampled_filenames)]
if params.class_agnostic:
df_gt['class'] = 'agnostic'
df_gt = df_gt.dropna(axis=0)
if fix_gt_cols:
df_gt = df_gt.rename(columns=csv_rename_dict)
df_gt["filename"] = df_gt["filename"].apply(lambda x: seq_img_name_to_path[os.path.basename(x)])
grouped_gt = df_gt.groupby("filename")
n_gt = len(df_gt)
gt_filenames = sorted(list(grouped_gt.groups.keys()))
n_gt_filenames = len(gt_filenames)
print_(f'{gt_path} --> {n_gt} labels for {n_gt_filenames} images')
n_gt_filenames = len(gt_filenames)
if img_start_id >= 0 and img_end_id >= 0:
if img_end_id >= n_gt_filenames:
if params.iw:
print_('img_end_id exceeds n_gt_filenames')
return None
raise AssertionError('img_end_id exceeds n_gt_filenames')
gt_filenames = gt_filenames[img_start_id:img_end_id + 1]
n_gt_filenames = len(gt_filenames)
print_(f'selecting {n_gt_filenames} image(s) from ID {img_start_id} to {img_end_id}')
# gt_file_paths = [utils.linux_path(seq_path, gt_filename) for gt_filename in gt_filenames]
gt_iter = gt_filenames
if show_pbar:
gt_iter = tqdm(gt_iter, total=n_gt_filenames, ncols=100, position=0, leave=True)
else:
print_('reading GT')
valid_gts = 0
total_rows = 0
for gt_filename in gt_iter:
assert os.path.isfile(gt_filename), f"gt_filename does not exist: {gt_filename}"
row_ids = grouped_gt.groups[gt_filename]
img_df = df_gt.loc[row_ids]
file_path = gt_filename
ignored_df = img_df.loc[img_df['class'] == 'ignored']
real_df = img_df.loc[img_df['class'] != 'ignored']
if params.filter_ignored and ignored_df.size > 0 and real_df.size > 0:
real_bboxes = np.asarray([[float(row['xmin']), float(row['ymin']),
float(row['xmax']), float(row['ymax'])]
for _, row in real_df.iterrows()
])
ignored_bboxes = np.asarray([[float(row['xmin']), float(row['ymin']),
float(row['xmax']), float(row['ymax'])]
for _, row in ignored_df.iterrows()
])
seq_gt_ignored_dict[file_path] = ignored_bboxes
ioa_1 = np.empty((real_df.shape[0], ignored_df.shape[0]))
utils.compute_overlaps_multi(None, ioa_1, None, real_bboxes, ignored_bboxes)
valid_idx = np.flatnonzero(np.apply_along_axis(
lambda x: np.all(np.less_equal(x, params.ignore_ioa_thresh)),
axis=1, arr=ioa_1))
img_df = real_df.iloc[valid_idx]
# seq_gt_data_dict[file_path] = []
curr_frame_gt_data = []
if show_pbar:
gt_iter.set_description(f'seq {seq_idx + 1} / {n_seq}: '
f'valid_gts: {valid_gts} / {total_rows}')
for _, row in img_df.iterrows():
total_rows += 1
xmin = float(row['xmin'])
ymin = float(row['ymin'])
xmax = float(row['xmax'])
ymax = float(row['ymax'])
gt_class = str(row['class'])
try:
gt_img_w = int(row['width'])
gt_img_h = int(row['height'])
except KeyError:
try:
gt_img_w, gt_img_h = img_path_to_size[file_path]
except KeyError:
gt_img_w, gt_img_h = imagesize.get(file_path)
else:
img_path_to_size[file_path] = (gt_img_w, gt_img_h)
try:
target_id = int(row['target_id'])
except KeyError:
target_id = -1
if gt_class not in gt_classes:
msg = f'{seq_name}: {gt_filename} :: invalid gt_class: {gt_class}'
if ignore_invalid_class:
# print(msg)
continue
raise AssertionError(msg)
valid_gts += 1
bbox = [xmin, ymin, xmax, ymax]
curr_obj_gt_data = {
'file_id': gt_filename,
'class': gt_class,
'bbox': bbox,
'width': gt_img_w,
'height': gt_img_h,
'target_id': target_id,
'confidence': 1.0,
'filename': gt_filename,
'used': False,
'used_fp': False,
'matched': False,
'mask': None
}
if enable_mask:
try:
mask_rle = utils.mask_str_to_img(
row["mask"], gt_img_h, gt_img_w, to_rle=1)
except KeyError:
mask_w = int(row["mask_w"])
mask_h = int(row["mask_h"])
mask_counts = str(row["mask_counts"])
mask_rle = dict(
size=(mask_h, mask_w),
counts=mask_counts
)
curr_obj_gt_data['mask'] = mask_rle
curr_frame_gt_data.append(curr_obj_gt_data)
gt_class_data_dict[gt_class][seq_path].append(curr_obj_gt_data)
try:
gt_counter_per_class[gt_class] += 1
except KeyError:
gt_counter_per_class[gt_class] = 1
if curr_frame_gt_data:
seq_gt_data_dict[file_path] = curr_frame_gt_data
if not valid_gts:
if params.allow_empty_gt:
pass
# print(f"no valid_gts found in {seq_name}")
else:
raise AssertionError(f"no valid_gts found in {seq_name}")
if params.filter_ignored:
gt_data_dict['ignored'][seq_path] = seq_gt_ignored_dict
gt_data_dict[seq_path] = seq_gt_data_dict
gt_img_paths = sorted(list(seq_gt_data_dict.keys()))
all_img_paths += gt_img_paths
"""read det from csv"""
if not det_loaded:
det_paths = all_seq_det_paths[seq_idx]
if isinstance(det_paths, str):
det_paths = [det_paths, ]
n_det_paths = len(det_paths)
# if n_seq == 1:
# print(f'\ndet_paths: {det_paths}')
seq_det_bboxes_list = []
# seq_det_bboxes_dict = {}
from collections import defaultdict
seq_det_file_to_bboxes = defaultdict(list)
det_pbar = None
if show_pbar and n_det_paths > 1:
det_pbar = det_paths_iter = tqdm(det_paths, position=0, leave=True)
else:
det_paths_iter = det_paths
print_(f'reading dets: {det_paths}')
n_invalid_dets = 0
n_total_dets = 0
"""load and consolidate all sets of detections for one sequence"""
for _det_path_id, _det_path in enumerate(det_paths_iter):
det_seq_name = os.path.splitext(os.path.basename(_det_path))[0]
if check_seq_name and (det_seq_name != seq_name or gt_seq_name != seq_name):
raise AssertionError(f'Mismatch between GT, detection and image sequences: '
f'{gt_seq_name}, {det_seq_name}, {seq_name}')
_det_name = os.path.basename(_det_path)
try:
df_det = pd.read_csv(_det_path)
except pd.errors.EmptyDataError:
continue
# df_det_orig = df_det.copy(deep=True)
# df_det_orig_copy = df_det.copy(deep=True)
# df_dets.append(_df_det)
# df_det = pd.concat(df_dets, axis=0)
if fix_det_cols:
df_det = df_det.rename(columns=csv_rename_dict)
if params.labels_remap:
labels_remap_path = params.labels_remap
if params.labels_root:
labels_remap_path = utils.linux_path(params.labels_root, labels_remap_path)
assert os.path.isfile(labels_remap_path), f"nonexistent labels_remap_path: {labels_remap_path}"
labels_remap_lines = open(labels_remap_path, 'r').read().splitlines()
labels_remap_dict = dict([labels_remap_line.split('\t')
for labels_remap_line in labels_remap_lines])
df_det["class"] = df_det["class"].apply(lambda x: labels_remap_dict[x])
if vid_info is not None:
seq_to_video_ids, seq_to_filenames = vid_info
try:
video_ids = seq_to_video_ids[seq_name]
except KeyError:
"""possibly some annoying imagenet-vid like dataset with multi-part sequence names"""
seq_to_video_ids.update({
os.path.basename(k__): v__ for k__, v__ in seq_to_video_ids.items()
})
seq_to_filenames.update({
os.path.basename(k__): v__ for k__, v__ in seq_to_filenames.items()
})
video_ids = seq_to_video_ids[seq_name]
video_ids = list(map(int, video_ids.split(',')))
df_det = df_det.loc[df_det['video_id'].isin(video_ids)]
# video_filenames = seq_to_filenames[seq_name]
# video_filenames = [video_filenames_.split(',') for video_filenames_ in video_filenames]
# vid_filtered_csv = utils.add_suffix(_det_path, 'vid_filtered')
# print(f'vid_filtered_csv: {vid_filtered_csv}')
# df_det.to_csv(vid_filtered_csv, index=False, sep=',')
# df_det_copy = df_det.copy(deep=True)