-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreprocessing_transforms.py
1220 lines (935 loc) · 43.9 KB
/
preprocessing_transforms.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
"""
Functions used to process and augment video data prior to passing into a model to train.
Additionally also processing all bounding boxes in a video according to the transformations performed on the video.
Usage:
In a custom dataset class:
from preprocessing_transforms import *
clip: Input to __call__ of each transform is a list of PIL images
All functions have an example in the TestPreproc class at the bottom of this file
"""
import torch
import torchvision
from torchvision.transforms import functional as F
from PIL import Image
from PIL import ImageChops
import cv2
from scipy import ndimage
import numpy as np
from abc import ABCMeta
from math import floor, ceil
class PreprocTransform(object):
"""
Abstract class for preprocessing transforms that contains methods to convert clips to PIL images.
"""
__metaclass__ = ABCMeta
def __init__(self, **kwargs):
pass
def __init__(self, *args, **kwargs):
pass
def _to_pil(self, clip):
# Must be of type uint8 if images have multiple channels, int16, int32, or float32 if there is only one channel
if isinstance(clip[0], np.ndarray):
if 'float' in str(clip[0].dtype):
clip = np.array(clip).astype('float32')
if 'int64' == str(clip[0].dtype):
clip = np.array(clip).astype('int32')
if clip[0].ndim == 3:
clip = np.array(clip).astype('uint8')
output=[]
for frame in clip:
output.append(F.to_pil_image(frame))
return output
def _to_numpy(self, clip):
output = []
if isinstance(clip[0], torch.Tensor):
if isinstance(clip, torch.Tensor):
output = clip.numpy()
else:
for frame in clip:
f_shape = frame.shape
# Convert from torch's C, H, W to numpy H, W, C
frame = frame.numpy().reshape(f_shape[1], f_shape[2], f_shape[0])
output.append(frame)
elif isinstance(clip[0], Image.Image):
for frame in clip:
output.append(np.array(frame))
else:
output = clip
output = np.array(output)
#if output.max() > 1.0:
# output = output/255.
return output
def _to_tensor(self, clip):
"""
torchvision converts PIL images and numpy arrays that are uint8 0 to 255 to float 0 to 1
Converts numpy arrays that are float to float tensor
"""
if isinstance(clip[0], torch.Tensor):
return clip
output = []
for frame in clip:
output.append(F.to_tensor(frame))
return output
class ResizeClip(PreprocTransform):
def __init__(self, *args, **kwargs):
super(ResizeClip, self).__init__(*args, **kwargs)
self.size_h, self.size_w = kwargs['resize_shape']
def resize_bbox(self, xmin, ymin, xmax, ymax, img_shape, resize_shape):
# Resize a bounding box within a frame relative to the amount that the frame was resized
img_h = img_shape[0]
img_w = img_shape[1]
res_h = resize_shape[0]
res_w = resize_shape[1]
frac_h = res_h/float(img_h)
frac_w = res_w/float(img_w)
xmin_new = int(xmin * frac_w)
xmax_new = int(xmax * frac_w)
ymin_new = int(ymin * frac_h)
ymax_new = int(ymax * frac_h)
return xmin_new, ymin_new, xmax_new, ymax_new
def resize_pt_coords(self, x, y, img_shape, resize_shape):
# Get relative position for point coords within a frame, after it's resized
img_h = img_shape[0]
img_w = img_shape[1]
res_h = resize_shape[0]
res_w = resize_shape[1]
frac_h = res_h/float(img_h)
frac_w = res_w/float(img_w)
x_new = (x * frac_w).astype(int)
y_new = (y * frac_h).astype(int)
return x_new, y_new
def __call__(self, clip, bbox=[]):
clip = self._to_numpy(clip)
out_clip = []
out_bbox = []
for frame_ind in range(len(clip)):
frame = clip[frame_ind]
proc_frame = cv2.resize(frame, (self.size_w, self.size_h))
out_clip.append(proc_frame)
if bbox!=[]:
temp_bbox = np.zeros(bbox[frame_ind].shape)-1
for class_ind, box in enumerate(bbox[frame_ind]):
if np.array_equal(box,-1*np.ones(box.shape)): #only annotated objects
continue
if box.shape[-1] == 2: #Operate on point coordinates
proc_bbox = np.stack(self.resize_pt_coords(box[:,0], box[:,1], frame.shape, (self.size_h, self.size_w)),1)
else: #Operate on bounding box
xmin, ymin, xmax, ymax = box
proc_bbox = self.resize_bbox(xmin, ymin, xmax, ymax, frame.shape, (self.size_h, self.size_w))
temp_bbox[class_ind,:] = proc_bbox
out_bbox.append(temp_bbox)
out_clip = np.array(out_clip)
assert(out_clip.shape[1:3] == (self.size_h, self.size_w)), 'Proc frame: {} Crop h,w: {},{}'.format(out_clip.shape,self.size_h,self.size_w)
if bbox!=[]:
return out_clip, np.array(out_bbox)
else:
return out_clip
class CropClip(PreprocTransform):
def __init__(self, xmin=None, xmax=None, ymin=None, ymax=None, *args, **kwargs):
super(CropClip, self).__init__(*args, **kwargs)
self.crop_xmin = xmin
self.crop_xmax = xmax
self.crop_ymin = ymin
self.crop_ymax = ymax
self.crop_h, self.crop_w = kwargs['crop_shape']
def _update_bbox(self, xmin, xmax, ymin, ymax, update_crop_shape=False):
'''
Args:
xmin (Float, shape []):
xmax (Float, shape []):
ymin (Float, shape []):
ymax (Float, shape []):
update_crop_shape (Boolean): Update expected crop shape along with bbox update call
'''
self.crop_xmin = xmin
self.crop_xmax = xmax
self.crop_ymin = ymin
self.crop_ymax = ymax
if update_crop_shape:
self.crop_h = ymax - ymin
self.crop_w = xmax - xmin
def crop_bbox(self, xmin, ymin, xmax, ymax, crop_xmin, crop_ymin, crop_xmax, crop_ymax):
if (xmin >= crop_xmax) or (xmax <= crop_xmin) or (ymin >= crop_ymax) or (ymax <= crop_ymin):
return -1, -1, -1, -1
if ymax > crop_ymax:
ymax_new = crop_ymax
else:
ymax_new = ymax
if xmax > crop_xmax:
xmax_new = crop_xmax
else:
xmax_new = xmax
if ymin < crop_ymin:
ymin_new = crop_ymin
else:
ymin_new = ymin
if xmin < crop_xmin:
xmin_new = crop_xmin
else:
xmin_new = xmin
return xmin_new-crop_xmin, ymin_new-crop_ymin, xmax_new-crop_xmin, ymax_new-crop_ymin
def crop_coords(self, x, y, crop_xmin, crop_ymin, crop_xmax, crop_ymax):
if np.any(x >= crop_xmax) or np.any(x <= crop_xmin) or np.any(y >= crop_ymax) or np.any(y <= crop_ymin):
return -1*np.ones(x.shape), -1*np.ones(y.shape)
x_new = np.clip(x, crop_xmin, crop_xmax)
y_new = np.clip(y, crop_ymin, crop_ymax)
return x_new-crop_xmin, y_new-crop_ymin
def __call__(self, clip, bbox=[]):
out_clip = []
out_bbox = []
for frame_ind in range(len(clip)):
frame = clip[frame_ind]
proc_frame = np.array(frame[self.crop_ymin:self.crop_ymax, self.crop_xmin:self.crop_xmax])
out_clip.append(proc_frame)
assert(proc_frame.shape[:2] == (self.crop_h, self.crop_w)), 'Frame shape: {}, Proc frame: {} Crop h,w: {},{}'.format(frame.shape, proc_frame.shape,self.crop_h,self.crop_w)
if bbox!=[]:
temp_bbox = np.zeros(bbox[frame_ind].shape)-1
for class_ind, box in enumerate(bbox[frame_ind]):
if np.array_equal(box,-1*np.ones(box.shape)): #only annotated objects
continue
if box.shape[-1] == 2: #Operate on point coordinates
proc_bbox = np.stack(self.crop_coords(box[:,0], box[:,1], self.crop_xmin, self.crop_ymin, self.crop_xmax, self.crop_ymax), 1)
else: #Operate on bounding box
xmin, ymin, xmax, ymax = box
proc_bbox = self.crop_bbox(xmin, ymin, xmax, ymax, self.crop_xmin, self.crop_ymin, self.crop_xmax, self.crop_ymax)
temp_bbox[class_ind,:] = proc_bbox
out_bbox.append(temp_bbox)
if bbox!=[]:
return np.array(out_clip), np.array(out_bbox)
else:
return np.array(out_clip)
class RandomCropClip(PreprocTransform):
def __init__(self, *args, **kwargs):
super(RandomCropClip, self).__init__(*args, **kwargs)
self.crop_h, self.crop_w = kwargs['crop_shape']
self.crop_transform = CropClip(0, 0, self.crop_w, self.crop_h, **kwargs)
self.xmin = None
self.xmax = None
self.ymin = None
self.ymax = None
def _update_random_sample(self, frame_h, frame_w):
if frame_w == self.crop_w:
self.xmin = 0
else:
self.xmin = np.random.randint(0, frame_w-self.crop_w)
self.xmax = self.xmin + self.crop_w
if frame_h == self.crop_h:
self.ymin = 0
else:
self.ymin = np.random.randint(0, frame_h-self.crop_h)
self.ymax = self.ymin + self.crop_h
def get_random_sample(self):
return self.xmin, self.xmax, self.ymin, self.ymax
def __call__(self, clip, bbox=[]):
frame_shape = clip[0].shape
self._update_random_sample(frame_shape[0], frame_shape[1])
self.crop_transform._update_bbox(self.xmin, self.xmax, self.ymin, self.ymax)
proc_clip = self.crop_transform(clip, bbox)
if isinstance(proc_clip, tuple):
assert(proc_clip[0].shape[1:3] == (self.crop_h, self.crop_w)), 'Proc frame: {} Crop h,w: {},{}'.format(proc_clip[0].shape,self.crop_h,self.crop_w)
else:
assert(proc_clip.shape[1:3] == (self.crop_h, self.crop_w)), 'Proc frame: {} Crop h,w: {},{}'.format(proc_clip.shape,self.crop_h,self.crop_w)
return proc_clip
class CenterCropClip(PreprocTransform):
def __init__(self, *args, **kwargs):
super(CenterCropClip, self).__init__(*args, **kwargs)
self.crop_h, self.crop_w = kwargs['crop_shape']
self.crop_transform = CropClip(0, 0, self.crop_w, self.crop_h, **kwargs)
def _calculate_center(self, frame_h, frame_w):
xmin = int(frame_w/2 - self.crop_w/2)
xmax = int(frame_w/2 + self.crop_w/2)
ymin = int(frame_h/2 - self.crop_h/2)
ymax = int(frame_h/2 + self.crop_h/2)
return xmin, xmax, ymin, ymax
def __call__(self, clip, bbox=[]):
frame_shape = clip[0].shape
xmin, xmax, ymin, ymax = self._calculate_center(frame_shape[0], frame_shape[1])
self.crop_transform._update_bbox(xmin, xmax, ymin, ymax)
proc_clip = self.crop_transform(clip, bbox)
if isinstance(proc_clip, tuple):
assert(proc_clip[0].shape[1:3] == (self.crop_h, self.crop_w)), 'Proc frame: {} Crop h,w: {},{}'.format(proc_clip[0].shape,self.crop_h,self.crop_w)
else:
assert(proc_clip.shape[1:3] == (self.crop_h, self.crop_w)), 'Proc frame: {} Crop h,w: {},{}'.format(proc_clip.shape,self.crop_h,self.crop_w)
return proc_clip
class RandomFlipClip(PreprocTransform):
"""
Specify a flip direction:
Horizontal, left right flip = 'h' (Default)
Vertical, top bottom flip = 'v'
"""
def __init__(self, direction='h', p=0.5, *args, **kwargs):
super(RandomFlipClip, self).__init__(*args, **kwargs)
self.direction = direction
self.p = p
def _update_p(self, p):
self.p = p
def _random_flip(self):
flip_prob = np.random.random()
if flip_prob >= self.p:
return 0
else:
return 1
def _h_flip(self, bbox, frame_size):
width = frame_size[1]
bbox_shape = bbox.shape
output_bbox = np.zeros(bbox_shape)-1
for bbox_ind, box in enumerate(bbox):
if np.array_equal(box,-1*np.ones(box.shape)): #only annotated objects
continue
if box.shape[-1] == 2: #Operate on point coordinates
x = box[:,0]
x_new = width - x
output_bbox[bbox_ind] = np.stack((x_new,box[:,1]),1)
else: #Operate on bounding box
xmin, ymin, xmax, ymax = box
xmax_new = width - xmin
xmin_new = width - xmax
output_bbox[bbox_ind] = xmin_new, ymin, xmax_new, ymax
return output_bbox
def _v_flip(self, bbox, frame_size):
height = frame_size[0]
bbox_shape = bbox.shape
output_bbox = np.zeros(bbox_shape)-1
for bbox_ind, box in enumerate(bbox):
if np.array_equal(box,-1*np.ones(box.shape)): #only annotated objects
continue
if box.shape[-1] == 2: #Operate on point coordinates
y = box[:,1]
y_new = height - y
output_bbox[bbox_ind] = np.stack((box[:,0],y_new),1)
else: #Operate on bounding box
xmin, ymin, xmax, ymax = box
ymax_new = height - ymin
ymin_new = height - ymax
output_bbox[bbox_ind] = xmin, ymin_new, xmax, ymax_new
return output_bbox
bbox_shape = bbox.shape
output_bbox = np.zeros(bbox_shape)-1
for bbox_ind in range(bbox_shape[0]):
xmin, ymin, xmax, ymax = bbox[bbox_ind]
height = frame_size[0]
ymax_new = height - ymin
ymin_new = height - ymax
output_bbox[bbox_ind] = xmin, ymin_new, xmax, ymax_new
return output_bbox
def _flip_data(self, clip, bbox=[]):
output_bbox = []
if self.direction == 'h':
output_clip = [cv2.flip(np.array(frame), 1) for frame in clip]
if bbox!=[]:
output_bbox = [self._h_flip(frame, output_clip[0].shape) for frame in bbox]
elif self.direction == 'v':
output_clip = [cv2.flip(np.array(frame), 0) for frame in clip]
if bbox!=[]:
output_bbox = [self._v_flip(frame, output_clip[0].shape) for frame in bbox]
return output_clip, output_bbox
def __call__(self, clip, bbox=[]):
input_shape = np.array(clip).shape
flip = self._random_flip()
out_clip = clip
out_bbox = bbox
if flip:
out_clip, out_bbox = self._flip_data(clip, bbox)
out_clip = np.array(out_clip)
assert(input_shape == out_clip.shape), "Input shape {}, output shape {}".format(input_shape, out_clip.shape)
if bbox!=[]:
return out_clip, out_bbox
else:
return out_clip
class ToTensorClip(PreprocTransform):
"""
Convert a list of PIL images or numpy arrays to a 5 dimensional pytorch tensor [batch, frame, channel, height, width]
"""
def __init__(self, *args, **kwargs):
super(ToTensorClip, self).__init__(*args, **kwargs)
self.transform = torchvision.transforms.ToTensor()
def __call__(self, clip, bbox=[]):
if isinstance(clip[0], Image.Image):
# a little round-about but it maintains consistency
temp_clip = []
for c in clip:
temp_clip.append(np.array(c))
clip = temp_clip
output_clip = torch.from_numpy(np.array(clip)).float() #Numpy array to Tensor
if bbox!=[]:
bbox = torch.from_numpy(np.array(bbox))
return output_clip, bbox
else:
return output_clip
class RandomRotateClip(PreprocTransform):
"""
Randomly rotate a clip from a fixed set of angles.
The rotation is counterclockwise
"""
def __init__(self, angles=[0,90,180,270], *args, **kwargs):
super(RandomRotateClip, self).__init__(*args, **kwargs)
self.angles = angles
######
# Code from: https://stackoverflow.com/questions/20924085/python-conversion-between-coordinates
def _cart2pol(self, point):
x,y = point
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return(rho, phi)
def _pol2cart(self, point):
rho, phi = point
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return(x, y)
#####
def _update_angles(self, angles):
self.angles=angles
def _rotate_bbox(self, bboxes, frame_shape, angle):
angle = np.deg2rad(angle)
bboxes_shape = bboxes.shape
output_bboxes = np.zeros(bboxes_shape)-1
frame_h, frame_w = frame_shape[0], frame_shape[1]
half_h = frame_h/2.
half_w = frame_w/2.
for bbox_ind in range(bboxes_shape[0]):
xmin, ymin, xmax, ymax = bboxes[bbox_ind]
tl = (xmin-half_w, ymax-half_h)
tr = (xmax-half_w, ymax-half_h)
bl = (xmin-half_w, ymin-half_h)
br = (xmax-half_w, ymin-half_h)
tl = self._cart2pol(tl)
tr = self._cart2pol(tr)
bl = self._cart2pol(bl)
br = self._cart2pol(br)
tl = (tl[0], tl[1] - angle)
tr = (tr[0], tr[1] - angle)
bl = (bl[0], bl[1] - angle)
br = (br[0], br[1] - angle)
tl = self._pol2cart(tl)
tr = self._pol2cart(tr)
bl = self._pol2cart(bl)
br = self._pol2cart(br)
tl = (tl[0]+half_w, tl[1]+half_h)
tr = (tr[0]+half_w, tr[1]+half_h)
bl = (bl[0]+half_w, bl[1]+half_h)
br = (br[0]+half_w, br[1]+half_h)
xmin_new = int(np.clip(min(floor(tl[0]), floor(tr[0]), floor(bl[0]), floor(br[0])), 0, frame_w-1))
xmax_new = int(np.clip(max(ceil(tl[0]), ceil(tr[0]), ceil(bl[0]), ceil(br[0])), 0, frame_w-1))
ymin_new = int(np.clip(min(floor(tl[1]), floor(tr[1]), floor(bl[1]), floor(br[1])), 0, frame_h-1))
ymax_new = int(np.clip(max(ceil(tl[1]), ceil(tr[1]), ceil(bl[1]), ceil(br[1])), 0, frame_h-1))
output_bboxes[bbox_ind] = [xmin_new, ymin_new, xmax_new, ymax_new]
return output_bboxes
def _rotate_coords(self, bboxes, frame_shape, angle):
angle = np.deg2rad(angle)
bboxes_shape = bboxes.shape
output_bboxes = np.zeros(bboxes_shape)-1
frame_h, frame_w = frame_shape[0], frame_shape[1]
half_h = frame_h/2.
half_w = frame_w/2.
for bbox_ind in range(bboxes_shape[0]):
x, y = bboxes[bbox_ind].transpose()
pts = (x-half_w, y-half_h)
pts = self._cart2pol(pts)
pts = (pts[0], pts[1]-angle)
pts = self._pol2cart(pts)
pts = (pts[0]+half_w, pts[1]+half_h)
output_bboxes[bbox_ind,:,0] = (np.clip(pts[0], 0, frame_w-1))
output_bboxes[bbox_ind,:,1] = (np.clip(pts[1], 0, frame_h-1))
return output_bboxes
def __call__(self, clip, bbox=[]):
angle = np.random.choice(self.angles)
output_clip = []
clip = self._to_numpy(clip)
for frame in clip:
output_clip.append(ndimage.rotate(frame, angle, reshape=False))
if bbox!=[]:
bbox = np.array(bbox)
output_bboxes = np.zeros(bbox.shape)-1
for bbox_ind in range(bbox.shape[0]):
if bbox.shape[-1] == 2:
output_bboxes[bbox_ind] = self._rotate_coords(bbox[bbox_ind], clip[0].shape, angle)
else:
output_bboxes[bbox_ind] = self._rotate_bbox(bbox[bbox_ind], clip[0].shape, angle)
return output_clip, output_bboxes
return output_clip
class RandomTranslateClip(PreprocTransform):
"""
Random horizontal and/or vertical shift on frames in a clip. All frames receive same shifting
Shift will be bounded by object bounding box (if given). Meaning, object will always be in view
Input numpy array must be of type np.uint8
Args:
- translate (Tuple)
- max_x (float): maximum absolute fraction for horizontal shift
- max_y (float): maximum absolute fraction for vertical shift
"""
def __init__(self, translate, **kwargs):
super(RandomTranslateClip, self).__init__(**kwargs)
self.max_x, self.max_y = translate
assert(self.max_x >= 0.0 and self.max_y >= 0.0)
assert(self.max_x < 1.0 and self.max_y < 1.0) #Cannot shift past image bounds
def _shift_frame(self, bbox, frame, tx, ty):
M = np.array([[1, 0, tx],[0, 1, ty]], dtype=np.float) # 2 x 3 transformation matrix
out_frame = cv2.warpAffine(frame, M, (frame.shape[1], frame.shape[0]))
if bbox is not None:
bbox_h = np.reshape(bbox, (-1,2)) #x-y coords
bbox_h = np.concatenate((bbox_h, np.ones((bbox_h.shape[0],1))), axis=1).transpose() #homography coords
out_box = M @ bbox_h
if bbox.shape[-1] == 2: #Operate on point coordinates
out_box = np.reshape(out_box.transpose(), (bbox.shape[0], bbox.shape[1],2))
else: #Operate on bounding box
out_box = np.reshape(out_box.transpose(), (-1,4))
return out_frame, out_box
else:
return out_frame
def __call__(self, clip, bbox=[]):
out_clip = []
clip = self._to_numpy(clip)
frac_x = np.random.rand()*(2*self.max_x)-self.max_x
frac_y = np.random.rand()*(2*self.max_y)-self.max_y
if bbox != []:
out_bbox = []
for frame, box in zip(clip,bbox):
img_h, img_w = frame.shape[:2]
tx = int(img_w * frac_x)
ty = int(img_h * frac_y)
#Bound translation amount so all objects remain in scene
if box.shape[-1] == 2: #Operate on point coordinates
mask = box[:,:,0] != -1
tx = np.clip(tx, np.max(-1*box[mask,0]), np.min(img_w-box[mask,0]))
ty = np.clip(ty, np.max(-1*box[mask,1]), np.min(img_h-box[mask,1]))
out_frame, out_box = self._shift_frame(box, frame, tx, ty)
out_box[~mask] = -1*np.ones(2)
else: #Operate on bounding box
#bbox is bounding box object
mask = box[:,0] != -1
tx = np.clip(tx, np.max(-1*box[mask,0]), np.min(img_w-box[mask,2]))
ty = np.clip(ty, np.max(-1*box[mask,1]), np.min(img_h-box[mask,3]))
out_frame, out_box = self._shift_frame(box, frame, tx, ty)
out_box[~mask] = -1*np.ones(4)
out_clip.append(out_frame)
out_bbox.append(out_box)
return out_clip, out_bbox
else:
for frame in clip:
img_h, img_w = frame.shape[:2]
tx = int(img_w * frac_x)
ty = int(img_h * frac_y)
out_clip.append(self._shift_frame(None, frame, tx, ty))
return out_clip
class RandomZoomClip(PreprocTransform):
"""
Random zoom on all frames in a clip. All frames receive same scaling
Scale will be bounded by object bounding box (if given). Meaning, object will always be in view
If zooming out, the borders will be filled with black.
>1: Zoom in
<1: Zoom out
=1: Same size
Args:
- scale (Tuple)
- min_scale (float): minimum scaling on frame
- max_scale (float): maximum scaling on frame
"""
def __init__(self, scale, **kwargs):
super(RandomZoomClip, self).__init__(**kwargs)
self.min_scale, self.max_scale = scale
assert(self.min_scale > 0 and self.min_scale <= self.max_scale)
def _scale_frame(self, bbox, frame, sc):
M = cv2.getRotationMatrix2D((frame.shape[1]/2, frame.shape[0]/2), 0, sc) # 2 x 3 rotation matrix
out_frame = cv2.warpAffine(frame, M, (frame.shape[1], frame.shape[0]))
if bbox is not None:
bbox_h = np.reshape(bbox, (-1,2)) #x-y coords
bbox_h = np.concatenate((bbox_h, np.ones((bbox_h.shape[0],1))), axis=1).transpose() #homography coords
out_box = M @ bbox_h
if bbox.shape[-1] == 2: #Operate on point coordinates
out_box = np.reshape(out_box.transpose(), (bbox.shape[0], bbox.shape[1],2))
else: #Operate on bounding box
out_box = np.reshape(out_box.transpose(), (-1,4))
return out_frame, out_box
else:
return out_frame
def __call__(self, clip, bbox=[]):
out_clip = []
clip = self._to_numpy(clip)
sc = np.random.uniform(self.min_scale, self.max_scale)
if bbox != []:
out_bbox = []
for frame, box in zip(clip,bbox):
img_h, img_w = frame.shape[:2]
cx, cy = (img_w/2, img_h/2)
#Bound scaling so all objects remain in scene
if box.shape[-1] == 2: #Operate on point coordinates
mask = box[:,:,0] != -1
max_x = min(img_w, np.max(cx + sc * (box[mask,0] - cx)))
min_x = max(0, np.min(cx + sc * (box[mask,0] - cx)))
sx = (max_x - cx) / np.max(box[mask,0] - cx)
if min_x == 0:
sx = min(sx, (min_x - cx) / np.min(box[mask,0] - cx))
max_y = min(img_h, np.max(cy + sc * (box[mask,1] - cy)))
min_y = max(0, np.min(cy + sc * (box[mask,1] - cy)))
sy = (max_y - cy) / np.max(box[mask,1] - cy)
if min_y == 0:
sy = min(sy, (min_y - cy) / np.min(box[mask,1] - cy))
sc = min(sx, sy)
out_frame, out_box = self._scale_frame(box, frame, sc)
out_box[~mask] = -1*np.ones(2)
else: #Operate on bounding box
mask = box[:,0] != -1
max_x = min(img_w, np.max(cx + sc * (box[mask,2] - cx)))
min_x = max(0, np.min(cx + sc * (box[mask,0] - cx)))
sx = (max_x - cx) / np.max(box[mask,2] - cx)
if min_x == 0:
sx = min(sx, (min_x - cx) / np.min(box[mask,0] - cx))
max_y = min(img_h, np.max(cy + sc * (box[mask,3] - cy)))
min_y = max(0, np.min(cy + sc * (box[mask,1] - cy)))
sy = (max_y - cy) / np.max(box[mask,3] - cy)
if min_y == 0:
sy = min(sy, (min_y - cy) / np.min(box[mask,1] - cy))
sc = min(sx, sy)
out_frame, out_box = self._scale_frame(box, frame, sc)
out_box[~mask] = -1*np.ones(4)
out_clip.append(out_frame)
out_bbox.append(out_box)
return out_clip, out_bbox
else:
for frame in clip:
img_h, img_w = frame.shape[:2]
sx = int(img_w * sc)
sy = int(img_h * sc)
out_clip.append(self._scale_frame(None, frame, sc))
return out_clip
class SubtractMeanClip(PreprocTransform):
def __init__(self, **kwargs):
super(SubtractMeanClip, self).__init__(**kwargs)
# self.clip_mean = torch.tensor(kwargs['clip_mean']).float()
self.clip_mean = kwargs['clip_mean']
# self.clip_mean = []
#
# for frame in self.clip_mean_args:
# self.clip_mean.append(Image.fromarray(frame))
def __call__(self, clip, bbox=[]):
#clip = clip-self.clip_mean
for clip_ind in range(len(clip)):
clip[clip_ind] = clip[clip_ind] - self.clip_mean[clip_ind]
if bbox!=[]:
return clip, bbox
else:
return clip
class SubtractRGBMean(PreprocTransform):
def __init__(self, **kwargs):
super(SubtractRGBMean, self).__init__(**kwargs)
self.rgb_mean = kwargs['subtract_mean']
def __call__(self, clip, bbox=[]):
clip = self._to_numpy(clip)
out_clip = []
out_bbox = []
for frame_ind in range(len(clip)):
frame = clip[frame_ind]
proc_frame = frame - self.rgb_mean
out_clip.append(proc_frame)
if bbox != []:
return out_clip, bbox
else:
return out_clip
class ApplyToPIL(PreprocTransform):
"""
Apply standard pytorch transforms that require PIL images as input to their __call__ function, for example Resize
NOTE: The __call__ function of this class converts the clip to a list of PIL images in the form of integers from 0-255. If the clips are floats (for example afer mean subtraction), then only call this transform before the float transform
Bounding box coordinates are not guaranteed to be transformed properly!
https://pytorch.org/docs/stable/_modules/torchvision/transforms/transforms.html
"""
def __init__(self, **kwargs):
"""
class_kwargs is a dictionary that contains the keyword arguments to be passed to the chosen pytorch transform class
"""
super(ApplyToPIL, self).__init__( **kwargs)
self.kwargs = kwargs
self.class_kwargs = kwargs['class_kwargs']
self.transform = kwargs['transform'](**self.class_kwargs)
def __call__(self, clip, bbox=[]):
input_pil = True
output_clip = []
if not isinstance(clip[0], Image.Image):
clip = self._to_pil(clip)
clip = [frame.convert('RGB') for frame in clip]
input_pil = False
if input_pil:
for frame in clip:
transformed_frame = self.transform(frame)
if isinstance(transformed_frame, tuple) or isinstance(transformed_frame, list):
for tf in transformed_frame:
output_clip.append(tf)
else:
output_clip.append(self.transform(frame)) #Apply transform and convert back to Numpy
else:
for frame in clip:
transformed_frame = self.transform(frame)
if isinstance(transformed_frame, tuple) or isinstance(transformed_frame, list):
for tf in transformed_frame:
output_clip.append(np.array(tf))
else:
output_clip.append(np.array(self.transform(frame))) #Apply transform and convert back to Numpy
if bbox!=[]:
return output_clip, bbox
else:
return output_clip
class ApplyToTensor(PreprocTransform):
"""
Apply standard pytorch transforms that require pytorch Tensors as input to their __call__ function, for example Normalize
NOTE: The __call__ function of this class converts the clip to a pytorch float tensor. If other transforms require PIL inputs, call them prior tho this one
Bounding box coordinates are not guaranteed to be transformed properly!
https://pytorch.org/docs/stable/_modules/torchvision/transforms/transforms.html
"""
def __init__(self, **kwargs):
super(ApplyToTensor, self).__init__(**kwargs)
self.kwargs = kwargs
self.class_kwargs = kwargs['class_kwargs']
self.transform = kwargs['transform'](**self.class_kwargs)
def __call__(self, clip, bbox=[]):
if not isinstance(clip, torch.Tensor):
clip = self._to_tensor(clip)
output_clip = []
for frame in clip:
output_clip.append(self.transform(frame))
output_clip = torch.stack(output_clip)
if bbox!=[]:
return output_clip, bbox
else:
return output_clip
class ApplyOpenCV(PreprocTransform):
"""
Apply opencv transforms that require numpy arrays as input to their __call__ function, for example Rotate
NOTE: The __call__ function of this class converts the clip to a Numpy array. If other transforms require PIL inputs, call them prior tho this one
Bounding box coordinates are not guaranteed to be transformed properly!
"""
def __init__(self, **kwargs):
super(ApplyOpenCV, self).__init__(**kwargs)
self.kwargs = kwargs
self.class_kwargs = kwargs['class_kwargs']
self.transform = kwargs['transform']
def __call__(self, clip, bbox=[]):
if not isinstance(clip, torch.Tensor):
clip = self._to_numpy(clip)
output_clip = []
for frame in clip:
output_clip.append(self.transform(frame, **self.class_kwargs))
if bbox!=[]:
return output_clip, bbox
else:
return output_clip
class TestPreproc(object):
def __init__(self):
self.resize = ResizeClip(resize_shape = [2,2])
self.crop = CropClip(0,0,0,0, crop_shape=[2,2])
self.rand_crop = RandomCropClip(crop_shape=[2,2])
self.cent_crop = CenterCropClip(crop_shape=[2,2])
self.rand_flip_h = RandomFlipClip(direction='h', p=1.0)
self.rand_flip_v = RandomFlipClip(direction='v', p=1.0)
self.rand_rot = RandomRotateClip(angles=[90])
self.rand_trans = RandomTranslateClip(translate=(0.5,0.5))
self.rand_zoom = RandomZoomClip(scale=(1.25,1.25))
self.sub_mean = SubtractMeanClip(clip_mean=np.zeros(1))
self.applypil = ApplyToPIL(transform=torchvision.transforms.ColorJitter, class_kwargs=dict(brightness=1))
self.applypil2 = ApplyToPIL(transform=torchvision.transforms.FiveCrop, class_kwargs=dict(size=(64,64)))
self.applytensor = ApplyToTensor(transform=torchvision.transforms.Normalize, class_kwargs=dict(mean=torch.tensor([0.,0.,0.]), std=torch.tensor([1.,1.,1.])))
self.applycv = ApplyOpenCV(transform=cv2.threshold, class_kwargs=dict(thresh=100, maxval=100, type=cv2.THRESH_TRUNC))
self.preproc = PreprocTransform()
def resize_test(self):
inp = np.array([[[.1,.2,.3,.4],[.1,.2,.3,.4],[.1,.2,.3,.4]]]).astype(float)
inp2 = np.array([[[.1,.1,.1,.1],[.2,.2,.2,.2],[.3,.3,.3,.3]]]).astype(float)
expected_out = np.array([[[.15,.35],[.15,.35]]]).astype(float)
expected_out2 = np.array([[[.125,.125],[.275,.275]]]).astype(float)
out = self.resize(inp)
out2 = self.resize(inp2)
assert (False not in np.isclose(out,expected_out)) and (False not in np.isclose(out2,expected_out2))
bbox = np.array([[[0,0,3,3]]]).astype(float)
_, bbox_out = self.resize(inp, bbox)
exp_bbox = np.array([[[0,0,1,2]]])
assert (False not in np.isclose(bbox_out, exp_bbox))
coord_pts = np.array([[[[1,1], [7,5], [9,6]]]]).astype(float)
_, bbox_out = self.resize(inp, coord_pts)
exp_bbox = np.array([[[[0., 0.],
[3., 3.],
[4., 4.]]]])
assert (False not in np.isclose(bbox_out, exp_bbox))
def crop_test(self):
inp = np.array([[[.1,.2,.3],[.4,.5,.6],[.7,.8,.9]]]).astype(float)
self.crop._update_bbox(1, 3, 1, 3)
exp_out = np.array([[[.5,.6],[.8,.9]]]).astype(float)
out = self.crop(inp)
assert (False not in np.isclose(out,exp_out))
def cent_crop_test(self):
inp = np.array([[[.1,.2,.3,.4],[.1,.2,.3,.4],[.1,.2,.3,.4],[.1,.2,.3,.4]]]).astype(float)
exp_out = np.array([[[.2,.3],[.2,.3]]]).astype(float)
out = self.cent_crop(inp)
assert (False not in np.isclose(out, exp_out))
def rand_crop_test(self):
inp = np.array([[[.1,.2,.3,.4],[.3,.4,.5,.6],[.2,.3,.4,.5],[.1,.2,.3,.4]]]).astype(float)
out = self.rand_crop(inp)
coords = self.rand_crop.get_random_sample()