-
Notifications
You must be signed in to change notification settings - Fork 607
/
Copy pathprocessing.py
2031 lines (1639 loc) · 104 KB
/
processing.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
import torch
import math
import numpy as np
import cv2 as cv
import torchvision.transforms as transforms
from pytracking import TensorDict
import ltr.data.processing_utils as prutils
def stack_tensors(x):
if isinstance(x, (list, tuple)) and isinstance(x[0], torch.Tensor):
return torch.stack(x)
return x
class BaseProcessing:
""" Base class for Processing. Processing class is used to process the data returned by a dataset, before passing it
through the network. For example, it can be used to crop a search region around the object, apply various data
augmentations, etc."""
def __init__(self, transform=transforms.ToTensor(), train_transform=None, test_transform=None, joint_transform=None):
"""
args:
transform - The set of transformations to be applied on the images. Used only if train_transform or
test_transform is None.
train_transform - The set of transformations to be applied on the train images. If None, the 'transform'
argument is used instead.
test_transform - The set of transformations to be applied on the test images. If None, the 'transform'
argument is used instead.
joint_transform - The set of transformations to be applied 'jointly' on the train and test images. For
example, it can be used to convert both test and train images to grayscale.
"""
self.transform = {'train': transform if train_transform is None else train_transform,
'test': transform if test_transform is None else test_transform,
'joint': joint_transform}
def __call__(self, data: TensorDict):
raise NotImplementedError
class ATOMProcessing(BaseProcessing):
""" The processing class used for training ATOM. The images are processed in the following way.
First, the target bounding box is jittered by adding some noise. Next, a square region (called search region )
centered at the jittered target center, and of area search_area_factor^2 times the area of the jittered box is
cropped from the image. The reason for jittering the target box is to avoid learning the bias that the target is
always at the center of the search region. The search region is then resized to a fixed size given by the
argument output_sz. A set of proposals are then generated for the test images by jittering the ground truth box.
"""
def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, proposal_params,
mode='pair', *args, **kwargs):
"""
args:
search_area_factor - The size of the search region relative to the target size.
output_sz - An integer, denoting the size to which the search region is resized. The search region is always
square.
center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
extracting the search region. See _get_jittered_box for how the jittering is done.
scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
extracting the search region. See _get_jittered_box for how the jittering is done.
proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
"""
super().__init__(*args, **kwargs)
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_factor = center_jitter_factor
self.scale_jitter_factor = scale_jitter_factor
self.proposal_params = proposal_params
self.mode = mode
def _get_jittered_box(self, box, mode):
""" Jitter the input box
args:
box - input bounding box
mode - string 'train' or 'test' indicating train or test data
returns:
torch.Tensor - jittered box
"""
jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
def _generate_proposals(self, box):
""" Generates proposals by adding noise to the input box
args:
box - input box
returns:
torch.Tensor - Array of shape (num_proposals, 4) containing proposals
torch.Tensor - Array of shape (num_proposals,) containing IoU overlap of each proposal with the input box. The
IoU is mapped to [-1, 1]
"""
# Generate proposals
num_proposals = self.proposal_params['boxes_per_frame']
proposal_method = self.proposal_params.get('proposal_method', 'default')
if proposal_method == 'default':
proposals = torch.zeros((num_proposals, 4))
gt_iou = torch.zeros(num_proposals)
for i in range(num_proposals):
proposals[i, :], gt_iou[i] = prutils.perturb_box(box, min_iou=self.proposal_params['min_iou'],
sigma_factor=self.proposal_params['sigma_factor'])
elif proposal_method == 'gmm':
proposals, _, _ = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
num_samples=num_proposals)
gt_iou = prutils.iou(box.view(1,4), proposals.view(-1,4))
# Map to [-1, 1]
gt_iou = gt_iou * 2 - 1
return proposals, gt_iou
def __call__(self, data: TensorDict):
"""
args:
data - The input data, should contain the following fields:
'train_images', test_images', 'train_anno', 'test_anno'
returns:
TensorDict - output data block with following fields:
'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_iou'
"""
# Apply joint transforms
if self.transform['joint'] is not None:
data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
for s in ['train', 'test']:
assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
"In pair mode, num train/test frames must be 1"
# Add a uniform noise to the center pos
jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
# Crop image region centered at jittered_anno box
crops, boxes, _ = prutils.jittered_center_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
self.search_area_factor, self.output_sz)
# Apply transforms
data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
# Generate proposals
frame2_proposals, gt_iou = zip(*[self._generate_proposals(a) for a in data['test_anno']])
data['test_proposals'] = list(frame2_proposals)
data['proposal_iou'] = list(gt_iou)
# Prepare output
if self.mode == 'sequence':
data = data.apply(stack_tensors)
else:
data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
return data
class KLBBregProcessing(BaseProcessing):
""" Based on ATOMProcessing. It supports training ATOM using the Maximum Likelihood or KL-divergence based learning
introduced in [https://arxiv.org/abs/1909.12297] and in PrDiMP [https://arxiv.org/abs/2003.12565].
"""
def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, proposal_params,
mode='pair', *args, **kwargs):
"""
args:
search_area_factor - The size of the search region relative to the target size.
output_sz - An integer, denoting the size to which the search region is resized. The search region is always
square.
center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
extracting the search region. See _get_jittered_box for how the jittering is done.
scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
extracting the search region. See _get_jittered_box for how the jittering is done.
proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
"""
super().__init__(*args, **kwargs)
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_factor = center_jitter_factor
self.scale_jitter_factor = scale_jitter_factor
self.proposal_params = proposal_params
self.mode = mode
def _get_jittered_box(self, box, mode):
""" Jitter the input box
args:
box - input bounding box
mode - string 'train' or 'test' indicating train or test data
returns:
torch.Tensor - jittered box
"""
jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
def _generate_proposals(self, box):
"""
"""
# Generate proposals
proposals, proposal_density, gt_density = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
gt_sigma=self.proposal_params['gt_sigma'],
num_samples=self.proposal_params[
'boxes_per_frame'],
add_mean_box=self.proposal_params.get(
'add_mean_box', False))
return proposals, proposal_density, gt_density
def __call__(self, data: TensorDict):
"""
args:
data - The input data, should contain the following fields:
'train_images', test_images', 'train_anno', 'test_anno'
returns:
TensorDict - output data block with following fields:
'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_density', 'gt_density'
"""
# Apply joint transforms
if self.transform['joint'] is not None:
data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
for s in ['train', 'test']:
assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
"In pair mode, num train/test frames must be 1"
# Add a uniform noise to the center pos
jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
# Crop image region centered at jittered_anno box
crops, boxes, _ = prutils.jittered_center_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
self.search_area_factor, self.output_sz)
# Apply transforms
data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
# Generate proposals
proposals, proposal_density, gt_density = zip(*[self._generate_proposals(a) for a in data['test_anno']])
data['test_proposals'] = proposals
data['proposal_density'] = proposal_density
data['gt_density'] = gt_density
# Prepare output
if self.mode == 'sequence':
data = data.apply(stack_tensors)
else:
data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
return data
class ATOMwKLProcessing(BaseProcessing):
"""Same as ATOMProcessing but using the GMM-based sampling of proposal boxes used in KLBBregProcessing."""
def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, proposal_params,
mode='pair', *args, **kwargs):
super().__init__(*args, **kwargs)
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_factor = center_jitter_factor
self.scale_jitter_factor = scale_jitter_factor
self.proposal_params = proposal_params
self.mode = mode
def _get_jittered_box(self, box, mode):
""" Jitter the input box
args:
box - input bounding box
mode - string 'train' or 'test' indicating train or test data
returns:
torch.Tensor - jittered box
"""
jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
def _generate_proposals(self, box):
"""
"""
# Generate proposals
proposals, proposal_density, gt_density = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
self.proposal_params['gt_sigma'],
self.proposal_params['boxes_per_frame'])
iou = prutils.iou_gen(proposals, box.view(1, 4))
return proposals, proposal_density, gt_density, iou
def __call__(self, data: TensorDict):
# Apply joint transforms
if self.transform['joint'] is not None:
data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
for s in ['train', 'test']:
assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
"In pair mode, num train/test frames must be 1"
# Add a uniform noise to the center pos
jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
# Crop image region centered at jittered_anno box
crops, boxes, _ = prutils.jittered_center_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
self.search_area_factor, self.output_sz)
# Apply transforms
data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
# Generate proposals
proposals, proposal_density, gt_density, proposal_iou = zip(
*[self._generate_proposals(a) for a in data['test_anno']])
data['test_proposals'] = proposals
data['proposal_density'] = proposal_density
data['gt_density'] = gt_density
data['proposal_iou'] = proposal_iou
# Prepare output
if self.mode == 'sequence':
data = data.apply(stack_tensors)
else:
data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
return data
class DiMPProcessing(BaseProcessing):
""" The processing class used for training DiMP. The images are processed in the following way.
First, the target bounding box is jittered by adding some noise. Next, a square region (called search region )
centered at the jittered target center, and of area search_area_factor^2 times the area of the jittered box is
cropped from the image. The reason for jittering the target box is to avoid learning the bias that the target is
always at the center of the search region. The search region is then resized to a fixed size given by the
argument output_sz. A Gaussian label centered at the target is generated for each image. These label functions are
used for computing the loss of the predicted classification model on the test images. A set of proposals are
also generated for the test images by jittering the ground truth box. These proposals are used to train the
bounding box estimating branch.
"""
def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, crop_type='replicate',
max_scale_change=None, mode='pair', proposal_params=None, label_function_params=None, *args, **kwargs):
"""
args:
search_area_factor - The size of the search region relative to the target size.
output_sz - An integer, denoting the size to which the search region is resized. The search region is always
square.
center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
extracting the search region. See _get_jittered_box for how the jittering is done.
scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
extracting the search region. See _get_jittered_box for how the jittering is done.
crop_type - If 'replicate', the boundary pixels are replicated in case the search region crop goes out of image.
If 'inside', the search region crop is shifted/shrunk to fit completely inside the image.
If 'inside_major', the search region crop is shifted/shrunk to fit completely inside one axis of the image.
max_scale_change - Maximum allowed scale change when performing the crop (only applicable for 'inside' and 'inside_major')
mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
label_function_params - Arguments for the label generation process. See _generate_label_function for details.
"""
super().__init__(*args, **kwargs)
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_factor = center_jitter_factor
self.scale_jitter_factor = scale_jitter_factor
self.crop_type = crop_type
self.mode = mode
self.max_scale_change = max_scale_change
self.proposal_params = proposal_params
self.label_function_params = label_function_params
def _get_jittered_box(self, box, mode):
""" Jitter the input box
args:
box - input bounding box
mode - string 'train' or 'test' indicating train or test data
returns:
torch.Tensor - jittered box
"""
jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
def _generate_proposals(self, box):
""" Generates proposals by adding noise to the input box
args:
box - input box
returns:
torch.Tensor - Array of shape (num_proposals, 4) containing proposals
torch.Tensor - Array of shape (num_proposals,) containing IoU overlap of each proposal with the input box. The
IoU is mapped to [-1, 1]
"""
# Generate proposals
num_proposals = self.proposal_params['boxes_per_frame']
proposal_method = self.proposal_params.get('proposal_method', 'default')
if proposal_method == 'default':
proposals = torch.zeros((num_proposals, 4))
gt_iou = torch.zeros(num_proposals)
for i in range(num_proposals):
proposals[i, :], gt_iou[i] = prutils.perturb_box(box, min_iou=self.proposal_params['min_iou'],
sigma_factor=self.proposal_params['sigma_factor'])
elif proposal_method == 'gmm':
proposals, _, _ = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
num_samples=num_proposals)
gt_iou = prutils.iou(box.view(1, 4), proposals.view(-1, 4))
else:
raise ValueError('Unknown proposal method.')
# Map to [-1, 1]
gt_iou = gt_iou * 2 - 1
return proposals, gt_iou
def _generate_label_function(self, target_bb):
""" Generates the gaussian label function centered at target_bb
args:
target_bb - target bounding box (num_images, 4)
returns:
torch.Tensor - Tensor of shape (num_images, label_sz, label_sz) containing the label for each sample
"""
gauss_label = prutils.gaussian_label_function(target_bb.view(-1, 4), self.label_function_params['sigma_factor'],
self.label_function_params['kernel_sz'],
self.label_function_params['feature_sz'], self.output_sz,
end_pad_if_even=self.label_function_params.get('end_pad_if_even', True))
return gauss_label
def __call__(self, data: TensorDict):
"""
args:
data - The input data, should contain the following fields:
'train_images', test_images', 'train_anno', 'test_anno'
returns:
TensorDict - output data block with following fields:
'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_iou',
'test_label' (optional), 'train_label' (optional), 'test_label_density' (optional), 'train_label_density' (optional)
"""
if self.transform['joint'] is not None:
data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
for s in ['train', 'test']:
assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
"In pair mode, num train/test frames must be 1"
# Add a uniform noise to the center pos
jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
crops, boxes = prutils.target_image_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
self.search_area_factor, self.output_sz, mode=self.crop_type,
max_scale_change=self.max_scale_change)
data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
# Generate proposals
if self.proposal_params:
frame2_proposals, gt_iou = zip(*[self._generate_proposals(a) for a in data['test_anno']])
data['test_proposals'] = list(frame2_proposals)
data['proposal_iou'] = list(gt_iou)
# Prepare output
if self.mode == 'sequence':
data = data.apply(stack_tensors)
else:
data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
# Generate label functions
if self.label_function_params is not None:
data['train_label'] = self._generate_label_function(data['train_anno'])
data['test_label'] = self._generate_label_function(data['test_anno'])
return data
class KLDiMPProcessing(BaseProcessing):
""" The processing class used for training PrDiMP that additionally supports the probabilistic classifier and
bounding box regressor. See DiMPProcessing for details.
"""
def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, crop_type='replicate',
max_scale_change=None, mode='pair', proposal_params=None,
label_function_params=None, label_density_params=None, *args, **kwargs):
"""
args:
search_area_factor - The size of the search region relative to the target size.
output_sz - An integer, denoting the size to which the search region is resized. The search region is always
square.
center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
extracting the search region. See _get_jittered_box for how the jittering is done.
scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
extracting the search region. See _get_jittered_box for how the jittering is done.
crop_type - If 'replicate', the boundary pixels are replicated in case the search region crop goes out of image.
If 'inside', the search region crop is shifted/shrunk to fit completely inside the image.
If 'inside_major', the search region crop is shifted/shrunk to fit completely inside one axis of the image.
max_scale_change - Maximum allowed scale change when performing the crop (only applicable for 'inside' and 'inside_major')
mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
label_function_params - Arguments for the label generation process. See _generate_label_function for details.
label_density_params - Arguments for the label density generation process. See _generate_label_function for details.
"""
super().__init__(*args, **kwargs)
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_factor = center_jitter_factor
self.scale_jitter_factor = scale_jitter_factor
self.crop_type = crop_type
self.mode = mode
self.max_scale_change = max_scale_change
self.proposal_params = proposal_params
self.label_function_params = label_function_params
self.label_density_params = label_density_params
def _get_jittered_box(self, box, mode):
""" Jitter the input box
args:
box - input bounding box
mode - string 'train' or 'test' indicating train or test data
returns:
torch.Tensor - jittered box
"""
jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
def _generate_proposals(self, box):
""" Generate proposal sample boxes from a GMM proposal distribution and compute their ground-truth density.
This is used for ML and KL based regression learning of the bounding box regressor.
args:
box - input bounding box
"""
# Generate proposals
proposals, proposal_density, gt_density = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
gt_sigma=self.proposal_params['gt_sigma'],
num_samples=self.proposal_params['boxes_per_frame'],
add_mean_box=self.proposal_params.get('add_mean_box', False))
return proposals, proposal_density, gt_density
def _generate_label_function(self, target_bb):
""" Generates the gaussian label function centered at target_bb
args:
target_bb - target bounding box (num_images, 4)
returns:
torch.Tensor - Tensor of shape (num_images, label_sz, label_sz) containing the label for each sample
"""
gauss_label = prutils.gaussian_label_function(target_bb.view(-1, 4), self.label_function_params['sigma_factor'],
self.label_function_params['kernel_sz'],
self.label_function_params['feature_sz'], self.output_sz,
end_pad_if_even=self.label_function_params.get('end_pad_if_even', True))
return gauss_label
def _generate_label_density(self, target_bb):
""" Generates the gaussian label density centered at target_bb
args:
target_bb - target bounding box (num_images, 4)
returns:
torch.Tensor - Tensor of shape (num_images, label_sz, label_sz) containing the label for each sample
"""
feat_sz = self.label_density_params['feature_sz'] * self.label_density_params.get('interp_factor', 1)
gauss_label = prutils.gaussian_label_function(target_bb.view(-1, 4), self.label_density_params['sigma_factor'],
self.label_density_params['kernel_sz'],
feat_sz, self.output_sz,
end_pad_if_even=self.label_density_params.get('end_pad_if_even', True),
density=True,
uni_bias=self.label_density_params.get('uni_weight', 0.0))
gauss_label *= (gauss_label > self.label_density_params.get('threshold', 0.0)).float()
if self.label_density_params.get('normalize', False):
g_sum = gauss_label.sum(dim=(-2,-1))
valid = g_sum>0.01
gauss_label[valid, :, :] /= g_sum[valid].view(-1, 1, 1)
gauss_label[~valid, :, :] = 1.0 / (gauss_label.shape[-2] * gauss_label.shape[-1])
gauss_label *= 1.0 - self.label_density_params.get('shrink', 0.0)
return gauss_label
def __call__(self, data: TensorDict):
"""
args:
data - The input data, should contain the following fields:
'train_images', test_images', 'train_anno', 'test_anno'
returns:
TensorDict - output data block with following fields:
'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_density', 'gt_density',
'test_label' (optional), 'train_label' (optional), 'test_label_density' (optional), 'train_label_density' (optional)
"""
if self.transform['joint'] is not None:
data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
for s in ['train', 'test']:
assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
"In pair mode, num train/test frames must be 1"
# Add a uniform noise to the center pos
jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
crops, boxes = prutils.target_image_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
self.search_area_factor, self.output_sz, mode=self.crop_type,
max_scale_change=self.max_scale_change)
data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
# Generate proposals
proposals, proposal_density, gt_density = zip(*[self._generate_proposals(a) for a in data['test_anno']])
data['test_proposals'] = proposals
data['proposal_density'] = proposal_density
data['gt_density'] = gt_density
for s in ['train', 'test']:
is_distractor = data.get('is_distractor_{}_frame'.format(s), None)
if is_distractor is not None:
for is_dist, box in zip(is_distractor, data[s+'_anno']):
if is_dist:
box[0] = 99999999.9
box[1] = 99999999.9
# Prepare output
if self.mode == 'sequence':
data = data.apply(stack_tensors)
else:
data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
# Generate label functions
if self.label_function_params is not None:
data['train_label'] = self._generate_label_function(data['train_anno'])
data['test_label'] = self._generate_label_function(data['test_anno'])
if self.label_density_params is not None:
data['train_label_density'] = self._generate_label_density(data['train_anno'])
data['test_label_density'] = self._generate_label_density(data['test_anno'])
return data
class LWLProcessing(BaseProcessing):
""" The processing class used for training LWL. The images are processed in the following way.
First, the target bounding box (computed using the segmentation mask)is jittered by adding some noise.
Next, a rectangular region (called search region ) centered at the jittered target center, and of area
search_area_factor^2 times the area of the jittered box is cropped from the image.
The reason for jittering the target box is to avoid learning the bias that the target is
always at the center of the search region. The search region is then resized to a fixed size given by the
argument output_sz. The argument 'crop_type' determines how out-of-frame regions are handled when cropping the
search region. For instance, if crop_type == 'replicate', the boundary pixels are replicated in case the search
region crop goes out of frame. If crop_type == 'inside_major', the search region crop is shifted/shrunk to fit
completely inside one axis of the image.
"""
def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, crop_type='replicate',
max_scale_change=None, mode='pair', new_roll=False, *args, **kwargs):
"""
args:
search_area_factor - The size of the search region relative to the target size.
output_sz - The size (width, height) to which the search region is resized. The aspect ratio is always
preserved when resizing the search region
center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
extracting the search region. See _get_jittered_box for how the jittering is done.
scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
extracting the search region. See _get_jittered_box for how the jittering is done.
crop_type - Determines how out-of-frame regions are handled when cropping the search region.
If 'replicate', the boundary pixels are replicated in case the search region crop goes out of
image.
If 'inside', the search region crop is shifted/shrunk to fit completely inside the image.
If 'inside_major', the search region crop is shifted/shrunk to fit completely inside one axis
of the image.
max_scale_change - Maximum allowed scale change when shrinking the search region to fit the image
(only applicable to 'inside' and 'inside_major' cropping modes). In case the desired
shrink factor exceeds the max_scale_change, the search region is only shrunk to the
factor max_scale_change. Out-of-frame regions are then handled by replicating the
boundary pixels. If max_scale_change is set to None, unbounded shrinking is allowed.
mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
new_roll - Whether to use the same random roll values for train and test frames when applying the joint
transformation. If True, a new random roll is performed for the test frame transformations. Thus,
if performing random flips, the set of train frames and the set of test frames will be flipped
independently.
"""
super().__init__(*args, **kwargs)
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_factor = center_jitter_factor
self.scale_jitter_factor = scale_jitter_factor
self.crop_type = crop_type
self.mode = mode
self.max_scale_change = max_scale_change
self.new_roll = new_roll
def _get_jittered_box(self, box, mode):
""" Jitter the input box
args:
box - input bounding box
mode - string 'train' or 'test' indicating train or test data
returns:
torch.Tensor - jittered box
"""
if self.scale_jitter_factor.get('mode', 'gauss') == 'gauss':
jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
elif self.scale_jitter_factor.get('mode', 'gauss') == 'uniform':
jittered_size = box[2:4] * torch.exp(torch.FloatTensor(2).uniform_(-self.scale_jitter_factor[mode],
self.scale_jitter_factor[mode]))
else:
raise Exception
max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode])).float()
jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
def __call__(self, data: TensorDict):
# Apply joint transformations. i.e. All train/test frames in a sequence are applied the transformation with the
# same parameters
if self.transform['joint'] is not None:
data['train_images'], data['train_anno'], data['train_masks'] = self.transform['joint'](
image=data['train_images'], bbox=data['train_anno'], mask=data['train_masks'])
data['test_images'], data['test_anno'], data['test_masks'] = self.transform['joint'](
image=data['test_images'], bbox=data['test_anno'], mask=data['test_masks'], new_roll=self.new_roll)
for s in ['train', 'test']:
assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
"In pair mode, num train/test frames must be 1"
# Add a uniform noise to the center pos
jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
orig_anno = data[s + '_anno']
# Extract a crop containing the target
crops, boxes, mask_crops = prutils.target_image_crop(data[s + '_images'], jittered_anno,
data[s + '_anno'], self.search_area_factor,
self.output_sz, mode=self.crop_type,
max_scale_change=self.max_scale_change,
masks=data[s + '_masks'])
# Apply independent transformations to each image
data[s + '_images'], data[s + '_anno'], data[s + '_masks'] = self.transform[s](image=crops, bbox=boxes, mask=mask_crops, joint=False)
# Prepare output
if self.mode == 'sequence':
data = data.apply(stack_tensors)
else:
data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
return data
class KYSProcessing(BaseProcessing):
""" The processing class used for training KYS. The images are processed in the following way.
First, the target bounding box is jittered by adding some noise. Next, a square region (called search region )
centered at the jittered target center, and of area search_area_factor^2 times the area of the jittered box is
cropped from the image. The reason for jittering the target box is to avoid learning the bias that the target is
always at the center of the search region. The search region is then resized to a fixed size given by the
argument output_sz. A Gaussian label centered at the target is generated for each image. These label functions are
used for computing the loss of the predicted classification model on the test images. A set of proposals are
also generated for the test images by jittering the ground truth box. These proposals can be used to train the
bounding box estimating branch.
"""
def __init__(self, search_area_factor, output_sz, center_jitter_param, scale_jitter_param,
proposal_params=None, label_function_params=None, min_crop_inside_ratio=0,
*args, **kwargs):
"""
args:
search_area_factor - The size of the search region relative to the target size.
output_sz - An integer, denoting the size to which the search region is resized. The search region is always
square.
center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
extracting the search region. See _generate_synthetic_motion for how the jittering is done.
scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
extracting the search region. See _generate_synthetic_motion for how the jittering is done.
proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
label_function_params - Arguments for the label generation process. See _generate_label_function for details.
min_crop_inside_ratio - Minimum amount of cropped search area which should be inside the image.
See _check_if_crop_inside_image for details.
"""
super().__init__(*args, **kwargs)
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_param = center_jitter_param
self.scale_jitter_param = scale_jitter_param
self.proposal_params = proposal_params
self.label_function_params = label_function_params
self.min_crop_inside_ratio = min_crop_inside_ratio
def _check_if_crop_inside_image(self, box, im_shape):
x, y, w, h = box.tolist()
if w <= 0.0 or h <= 0.0:
return False
crop_sz = math.ceil(math.sqrt(w * h) * self.search_area_factor)
x1 = x + 0.5 * w - crop_sz * 0.5
x2 = x1 + crop_sz
y1 = y + 0.5 * h - crop_sz * 0.5
y2 = y1 + crop_sz
w_inside = max(min(x2, im_shape[1]) - max(x1, 0), 0)
h_inside = max(min(y2, im_shape[0]) - max(y1, 0), 0)
crop_area = ((x2 - x1) * (y2 - y1))
if crop_area > 0:
inside_ratio = w_inside * h_inside / crop_area
return inside_ratio > self.min_crop_inside_ratio
else:
return False
def _generate_synthetic_motion(self, boxes, images, mode):
num_frames = len(boxes)
out_boxes = []
for i in range(num_frames):
jittered_box = None
for _ in range(10):
orig_box = boxes[i]
jittered_size = orig_box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_param[mode + '_factor'])
if self.center_jitter_param.get(mode + '_mode', 'uniform') == 'uniform':
max_offset = (jittered_size.prod().sqrt() * self.center_jitter_param[mode + '_factor']).item()
offset_factor = (torch.rand(2) - 0.5)
jittered_center = orig_box[0:2] + 0.5 * orig_box[2:4] + max_offset * offset_factor
if self.center_jitter_param.get(mode + '_limit_motion', False) and i > 0:
prev_out_box_center = out_boxes[-1][:2] + 0.5 * out_boxes[-1][2:]
if abs(jittered_center[0] - prev_out_box_center[0]) > out_boxes[-1][2:].prod().sqrt() * 2.5:
jittered_center[0] = orig_box[0] + 0.5 * orig_box[2] + max_offset * offset_factor[0] * -1
if abs(jittered_center[1] - prev_out_box_center[1]) > out_boxes[-1][2:].prod().sqrt() * 2.5:
jittered_center[1] = orig_box[1] + 0.5 * orig_box[3] + max_offset * offset_factor[1] * -1
jittered_box = torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
if self._check_if_crop_inside_image(jittered_box, images[i].shape):
break
else:
jittered_box = torch.tensor([1, 1, 10, 10]).float()
out_boxes.append(jittered_box)
return out_boxes
def _generate_proposals(self, frame2_gt_crop):
# Generate proposals
num_proposals = self.proposal_params['boxes_per_frame']
frame2_proposals = np.zeros((num_proposals, 4))
gt_iou = np.zeros(num_proposals)
sample_p = np.zeros(num_proposals)
for i in range(num_proposals):
frame2_proposals[i, :], gt_iou[i], sample_p[i] = prutils.perturb_box(
frame2_gt_crop,
min_iou=self.proposal_params['min_iou'],
sigma_factor=self.proposal_params['sigma_factor']
)
gt_iou = gt_iou * 2 - 1
return frame2_proposals, gt_iou
def _generate_label_function(self, target_bb, target_absent=None):
gauss_label = prutils.gaussian_label_function(target_bb.view(-1, 4), self.label_function_params['sigma_factor'],
self.label_function_params['kernel_sz'],
self.label_function_params['feature_sz'], self.output_sz,
end_pad_if_even=self.label_function_params.get(
'end_pad_if_even', True))
if target_absent is not None:
gauss_label *= (1 - target_absent).view(-1, 1, 1).float()
return gauss_label
def __call__(self, data: TensorDict):
if self.transform['joint'] is not None:
data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'],
bbox=data['train_anno'])
data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
for s in ['train', 'test']:
# Generate synthetic sequence
jittered_anno = self._generate_synthetic_motion(data[s + '_anno'], data[s + '_images'], s)
# Crop images
crops, boxes, _ = prutils.jittered_center_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
self.search_area_factor, self.output_sz)
# Add transforms
data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
if self.proposal_params:
frame2_proposals, gt_iou = zip(*[self._generate_proposals(a.numpy()) for a in data['test_anno']])
data['test_proposals'] = [torch.tensor(p, dtype=torch.float32) for p in frame2_proposals]
data['proposal_iou'] = [torch.tensor(gi, dtype=torch.float32) for gi in gt_iou]
data = data.apply(stack_tensors)
if self.label_function_params is not None:
data['train_label'] = self._generate_label_function(data['train_anno'])
test_target_absent = 1 - (data['test_visible'] * data['test_valid_anno'])
data['test_label'] = self._generate_label_function(data['test_anno'], test_target_absent)
return data
class TargetCandiateMatchingProcessing(BaseProcessing):
""" The processing class used for training KeepTrack. The distractor dataset for LaSOT is required.
Two different modes are available partial supervision (partial_sup) or self-supervision (self_sup).
For partial supervision the candidates their meta data and the images of two consecutive frames are used to
form a single supervision cue among the candidates corresponding to the annotated target object. All other
candidates are ignored. First, the search area region is cropped from the image followed by augmentation.
Then, the candidate matching with the annotated target object is detected to supervise the matching. Then, the
score map coordinates of the candidates are transformed to full image coordinates. Next, it is randomly decided
whether the candidates corresponding to the target is dropped in one of the frames to simulate re-detection,
occlusions or normal tracking. To enable training in batches the number of candidates to match between
two frames is fixed. Hence, artificial candidates are added. Finally, the assignment matrix is formed where a 1
denotes a match between two candidates, -1 denotes that a match is not available and -2 denotes that no
information about the matching is available. These entries will be ignored.
The second method for partial supervision is used for validation only. It uses only the detected candidates and
thus results in different numbers of candidates for each frame-pair such that training in batches is not possible.
For self-supervision only a singe frame and its candidates are required. The second frame and candidates are
artificially created using augmentations. Here full supervision among all candidates is enabled.
First, the search area region is cropped from the full image. Then, the cropping coordinates are augmented to
crop a slightly different view that mimics search area region of the next frame.
Next, the two image regions are augmented further. Then, the matching between candidates is determined by randomly
dropping candidates to mimic occlusions or re-detections. Again, the number of candidates is fixed by adding
artificial candidates that are ignored during training. In addition, the scores and coordinates of each
candidate are altered to increase matching difficulty. Finally, the assignment matrix is formed where a 1
denotes a match between two candidates, -1 denotes that a match is not available.
"""
def __init__(self, output_sz, num_target_candidates=None, mode='self_sup',
img_aug_transform=None, score_map_sz=None, enable_search_area_aug=True,
search_area_jitter_value=100, real_target_candidates_only=False, *args, **kwargs):
super().__init__(*args, **kwargs)
self.output_sz = output_sz
self.num_target_candidates = num_target_candidates
self.mode = mode
self.img_aug_transform = img_aug_transform
self.enable_search_area_aug = enable_search_area_aug
self.search_area_jitter_value = search_area_jitter_value
self.real_target_candidates_only = real_target_candidates_only
self.score_map_sz = score_map_sz if score_map_sz is not None else (23, 23)
def __call__(self, data: TensorDict):
if data['sup_mode'] == 'self_sup':
data = self._original_and_augmented_frame(data)
elif data['sup_mode'] == 'partial_sup' and self.real_target_candidates_only == False:
data = self._previous_and_current_frame(data)
elif data['sup_mode'] == 'partial_sup' and self.real_target_candidates_only == True:
data = self._previous_and_current_frame_detected_target_candidates_only(data)
else:
raise NotImplementedError()
data = data.apply(stack_tensors)
return data
def _original_and_augmented_frame(self, data: TensorDict):
out = TensorDict()
img = data.pop('img')[0]
tsm_coords = data['target_candidate_coords'][0]
scores = data['target_candidate_scores'][0]