-
Notifications
You must be signed in to change notification settings - Fork 56
/
transforms.py
executable file
·1564 lines (1187 loc) · 50 KB
/
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
from __future__ import print_function
import numpy as np
# scipy.ndimage -> skimage -> cv2,
# skimage is one or two orders of magnitude slower than cv2
import cv2
try:
import torch
except ImportError:
pass
import collections
import numbers
import types
InterpolationFlags = {'nearest':cv2.INTER_NEAREST, 'linear':cv2.INTER_LINEAR,
'cubic':cv2.INTER_CUBIC, 'area':cv2.INTER_AREA,
'lanczos':cv2.INTER_LANCZOS4}
BorderTypes = {'constant':cv2.BORDER_CONSTANT,
'replicate':cv2.BORDER_REPLICATE, 'nearest':cv2.BORDER_REPLICATE,
'reflect':cv2.BORDER_REFLECT, 'mirror': cv2.BORDER_REFLECT,
'wrap':cv2.BORDER_WRAP, 'reflect_101':cv2.BORDER_REFLECT_101,}
def _loguniform(interval, random_state=np.random):
low, high = interval
return np.exp(random_state.uniform(np.log(low), np.log(high)))
def _clamp(img, min=None, max=None, dtype='uint8'):
if min is None and max is None:
if dtype == 'uint8':
min, max = 0, 255
elif dtype == 'uint16':
min, max = 0, 65535
else:
min, max = -np.inf, np.inf
img = np.clip(img, min, max)
return img.astype(dtype)
def _jaccard(boxes, rect):
def _intersect(boxes, rect):
lt = np.maximum(boxes[:, :2], rect[:2])
rb = np.minimum(boxes[:, 2:], rect[2:])
inter = np.clip(rb - lt, 0, None)
return inter[:, 0] * inter[:, 1]
inter = _intersect(boxes, rect)
area1 = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
area2 = (rect[2] - rect[0]) * (rect[3] - rect[1])
union = area1 + area2 - inter
jaccard = inter / np.clip(union, 1e-10, None)
coverage = inter / np.clip(area1, 1e-10, None)
return jaccard, coverage, inter
def _coords_clamp(cds, shape, outside=None):
w, h = shape[1] - 1, shape[0] - 1
if outside == 'discard':
cds_ = []
for x, y in cds:
x_ = x if 0 <= x <= w else np.sign(x) * np.inf
y_ = y if 0 <= y <= h else np.sign(y) * np.inf
cds_.append([x_, y_])
return np.array(cds_, dtype=np.float32)
else:
return np.array([[np.clip(cd[0], 0, w), np.clip(cd[1], 0, h)] for cd in cds], dtype=np.float32)
def _to_bboxes(cds, img_shape=None):
assert len(cds) % 4 == 0
h, w = img_shape if img_shape is not None else (np.inf, np.inf)
boxes = []
cds = np.array(cds)
for i in range(0, len(cds), 4):
xmin = np.clip(cds[i:i+4, 0].min(), 0, w - 1)
xmax = np.clip(cds[i:i+4, 0].max(), 0, w - 1)
ymin = np.clip(cds[i:i+4, 1].min(), 0, h - 1)
ymax = np.clip(cds[i:i+4, 1].max(), 0, h - 1)
boxes.append([xmin, ymin, xmax, ymax])
return np.array(boxes)
def _to_coords(boxes):
cds = []
for box in boxes:
xmin, ymin, xmax, ymax = box
cds += [
[xmin, ymin],
[xmax, ymin],
[xmax, ymax],
[xmin, ymax],
]
return np.array(cds)
# recursively reset transform's state
def transform_state(t, **kwargs):
if callable(t):
t_vars = vars(t)
if 'random_state' in kwargs and 'random' in t_vars:
t.__dict__['random'] = kwargs['random_state']
support = ['fillval', 'anchor', 'prob', 'mean', 'std', 'outside']
for arg in kwargs:
if arg in t_vars and arg in support:
t.__dict__[arg] = kwargs[arg]
if 'mode' in kwargs and 'mode' in t_vars:
t.__dict__['mode'] = kwargs['mode']
if 'border' in kwargs and 'border' in t_vars:
t.__dict__['border'] = BorderTypes.get(kwargs['border'], cv2.BORDER_REPLICATE)
if 'transforms' in t_vars:
t.__dict__['transforms'] = transforms_state(t.transforms, **kwargs)
return t
def transforms_state(ts, **kwargs):
assert isinstance(ts, collections.Sequence)
transforms = []
for t in ts:
if isinstance(t, collections.Sequence):
transforms.append(transforms_state(t, **kwargs))
else:
transforms.append(transform_state(t, **kwargs))
return transforms
# Operators
'''
class Clamp(object):
def __init__(self, min=0, max=255, soft=True, dtype='uint8'):
self.min, self.max = min, max
self.dtype = dtype
self.soft = soft
self.thresh =
def __call__(self, img):
if self.soft is None:
return _clamp(img, min=self.min, max=self.max, dtype=self.dtype)
else:
'''
class Unsqueeze(object):
def __call__(self, img):
if img.ndim == 2:
return img[..., np.newaxis]
elif img.ndim == 3:
return img
else:
raise ValueError('input muse be image')
class Normalize(object):
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, img):
# normalize np.ndarray or torch.FloatTensor
if isinstance(img, np.ndarray):
return (img - self.mean) / self.std
elif isinstance(img, torch.FloatTensor):
tensor = img
for t, m, s in zip(tensor, self.mean, self.std):
t.sub_(m).div_(s)
return tensor
else:
raise Exception('invalid input type')
class SubtractMean(object):
# TODO: pytorch tensor
def __init__(self, mean):
self.mean = mean
def __call__(self, img):
return img.astype(np.float32) - self.mean
class DivideBy(object):
# TODO: pytorch tensor
def __init__(self, divisor):
self.divisor = divisor
def __call__(self, img):
return img.astype(np.float32) / self.divisor
def HalfBlood(img, anchor, f1, f2):
assert isinstance(f1, types.LambdaType) and isinstance(f2, types.LambdaType)
if isinstance(anchor, numbers.Number):
anchor = int(np.ceil(anchor))
if isinstance(anchor, int) and img.ndim == 3 and 0 < anchor < img.shape[2]:
img1, img2 = img[:,:,:anchor], img[:,:,anchor:]
if img1.shape[2] == 1:
img1 = img1[:, :, 0]
if img2.shape[2] == 1:
img2 = img2[:, :, 0]
img1 = f1(img1)
img2 = f2(img2)
if img1.ndim == 2:
img1 = img1[..., np.newaxis]
if img2.ndim == 2:
img2 = img2[..., np.newaxis]
return np.concatenate((img1, img2), axis=2)
elif anchor == 0:
img = f2(img)
if img.ndim == 2:
img = img[..., np.newaxis]
return img
else:
img = f1(img)
if img.ndim == 2:
img = img[..., np.newaxis]
return img
# Photometric Transform
class RGB2BGR(object):
def __call__(self, img):
assert img.ndim == 3 and img.shape[2] == 3
return img[:, :, ::-1]
class BGR2RGB(object):
def __call__(self, img):
assert img.ndim == 3 and img.shape[2] == 3
return img[:, :, ::-1]
class GrayScale(object):
# RGB to Gray
def __call__(self, img):
if img.ndim == 3 and img.shape[2] == 1:
return img
assert img.ndim == 3 and img.shape[2] == 3
dtype = img.dtype
gray = np.sum(img * [0.299, 0.587, 0.114], axis=2).astype(dtype) #5x slower than cv2.cvtColor
#gray = cv2.cvtColor(img.astype('uint8'), cv2.COLOR_RGB2GRAY)
return gray[..., np.newaxis]
class Hue(object):
# skimage.color.rgb2hsv/hsv2rgb is almost 100x slower than cv2.cvtColor
def __init__(self, var=0.05, prob=0.5, random_state=np.random):
self.var = var
self.prob = prob
self.random = random_state
def __call__(self, img):
assert img.ndim == 3 and img.shape[2] == 3
if self.random.random_sample() >= self.prob:
return img
var = self.random.uniform(-self.var, self.var)
to_HSV, from_HSV = [(cv2.COLOR_RGB2HSV, cv2.COLOR_HSV2RGB),
(cv2.COLOR_BGR2HSV, cv2.COLOR_HSV2BGR)][self.random.randint(2)]
hsv = cv2.cvtColor(img, to_HSV).astype(np.float32)
hue = hsv[:, :, 0] / 179. + var
hue = hue - np.floor(hue)
hsv[:, :, 0] = hue * 179.
img = cv2.cvtColor(hsv.astype('uint8'), from_HSV)
return img
class Saturation(object):
def __init__(self, var=0.3, prob=0.5, random_state=np.random):
self.var = var
self.prob = prob
self.random = random_state
self.grayscale = GrayScale()
def __call__(self, img):
if self.random.random_sample() >= self.prob:
return img
dtype = img.dtype
gs = self.grayscale(img)
alpha = 1.0 + self.random.uniform(-self.var, self.var)
img = alpha * img.astype(np.float32) + (1 - alpha) * gs.astype(np.float32)
return _clamp(img, dtype=dtype)
class Brightness(object):
def __init__(self, delta=32, prob=0.5, random_state=np.random):
self.delta = delta
self.prob = prob
self.random = random_state
def __call__(self, img):
if self.random.random_sample() >= self.prob:
return img
dtype = img.dtype
#alpha = 1.0 + self.random.uniform(-self.var, self.var)
#img = alpha * img.astype(np.float32)
img = img.astype(np.float32) + self.random.uniform(-self.delta, self.delta)
return _clamp(img, dtype=dtype)
class Contrast(object):
def __init__(self, var=0.3, prob=0.5, random_state=np.random):
self.var = var
self.prob = prob
self.random = random_state
self.grayscale = GrayScale()
def __call__(self, img):
if self.random.random_sample() >= self.prob:
return img
dtype = img.dtype
gs = self.grayscale(img).mean()
alpha = 1.0 + self.random.uniform(-self.var, self.var)
img = alpha * img.astype(np.float32) + (1 - alpha) * gs
return _clamp(img, dtype=dtype)
class RandomOrder(object):
def __init__(self, transforms, random_state=None): #, **kwargs):
if random_state is None:
self.random = np.random
else:
self.random = random_state
#kwargs['random_state'] = random_state
self.transforms = transforms_state(transforms, random=random_state)
def __call__(self, img):
if self.transforms is None:
return img
order = self.random.permutation(len(self.transforms))
for i in order:
img = self.transforms[i](img)
return img
class ColorJitter(RandomOrder):
def __init__(self, brightness=32, contrast=0.5, saturation=0.5, hue=0.1,
prob=0.5, random_state=np.random):
self.transforms = []
self.random = random_state
if brightness != 0:
self.transforms.append(
Brightness(brightness, prob=prob, random_state=random_state))
if contrast != 0:
self.transforms.append(
Contrast(contrast, prob=prob, random_state=random_state))
if saturation != 0:
self.transforms.append(
Saturation(saturation, prob=prob, random_state=random_state))
if hue != 0:
self.transforms.append(
Hue(hue, prob=prob, random_state=random_state))
# "ImageNet Classification with Deep Convolutional Neural Networks"
# looks inferior to ColorJitter
class FancyPCA(object):
def __init__(self, var=0.2, random_state=np.random):
self.var = var
self.random = random_state
self.pca = None # shape (channels, channels)
def __call__(self, img):
dtype = img.dtype
channels = img.shape[2]
alpha = self.random.randn(channels) * self.var
if self.pca is None:
pca = self._pca(img)
else:
pca = self.pca
img = img + (pca * alpha).sum(axis=1)
return _clamp(img, dtype=dtype)
def _pca(self, img): # single image (hwc), or a batch (nhwc)
assert img.ndim >= 3
channels = img.shape[-1]
X = img.reshape(-1, channels)
cov = np.cov(X.T)
evals, evecs = np.linalg.eigh(cov)
pca = np.sqrt(evals) * evecs
return pca
def fit(self, imgs): # training
self.pca = self._pca(imgs)
print(self.pca)
class ShuffleChannels(object):
def __init__(self, prob=1., random_state=np.random):
self.prob = prob
self.random = random_state
def __call__(self, img):
if self.prob < 1 and self.random.random_sample() >= self.prob:
return img
assert img.ndim == 3
permut = self.random.permutation(img.shape[2])
img = img[:, :, permut]
return img
# "Improved Regularization of Convolutional Neural Networks with Cutout". (arXiv:1708.04552)
# fill with 0(if image is normalized) or dataset's per-channel mean.
class Cutout(object):
def __init__(self, size, fillval=0, prob=0.5, random_state=np.random):
if isinstance(size, numbers.Number):
size = (int(size), int(size))
self.size = size
self.fillval = fillval
self.prob = prob
self.random = random_state
def __call__(self, img):
if self.random.random_sample() >= self.prob:
return img
h, w = img.shape[:2]
tw, th = self.size
cx = self.random.randint(0, w)
cy = self.random.randint(0, h)
x1 = int(np.clip(cx - tw / 2, 0, w - 1))
x2 = int(np.clip(cx + (tw + 1) / 2, 0, w ))
y1 = int(np.clip(cy - th / 2, 0, h - 1))
y2 = int(np.clip(cy + (th + 1) / 2, 0, h ))
img[y1:y2, x1:x2] = self.fillval
return img
# "Random Erasing Data Augmentation". (arXiv:1708.04896). fill with random value
class RandomErasing(object):
def __init__(self, area_range=(0.02, 0.2), ratio_range=[0.3, 1/0.3], fillval=None,
prob=0.5, num=1, anchor=None, random_state=np.random):
self.area_range = area_range
self.ratio_range = ratio_range
self.fillval = fillval
self.prob = prob
self.num = num
self.anchor = anchor
self.random = random_state
def __call__(self, img):
if self.random.random_sample() >= self.prob:
return img
h, w = img.shape[:2]
num = self.random.randint(self.num) + 1
count = 0
for _ in range(10):
area = h * w
target_area = _loguniform(self.area_range, self.random) * area
aspect_ratio = _loguniform(self.ratio_range, self.random)
tw = int(round(np.sqrt(target_area * aspect_ratio)))
th = int(round(np.sqrt(target_area / aspect_ratio)))
if tw <= w and th <= h:
x1 = self.random.randint(0, w - tw + 1)
y1 = self.random.randint(0, h - th + 1)
fillval = self.random.randint(0, 256) if self.fillval is None else self.fillval
erase = lambda im: self._fill(im, (x1, y1, x1+tw, y1+th), fillval)
cut = lambda im: self._fill(im, (x1, y1, x1+tw, y1+th), 0)
img = HalfBlood(img, self.anchor, erase, cut)
count += 1
if count >= num:
return img
# Fallback
return img
def _fill(self, img, rect, val):
l, t, r, b = rect
img[t:b, l:r] = val
return img
#GaussianBlur
#MotionBlue
#RadialBlur
#ResizeBlur
#Sharpen
# Geometric Transform
def _expand(img, size, lt, val):
h, w = img.shape[:2]
nw, nh = size
x1, y1 = lt
expand = np.zeros([nh, nw] + list(img.shape[2:]), dtype=img.dtype)
expand[...] = val
expand[y1: h + y1, x1: w + x1] = img
#expand = cv2.copyMakeBorder(img, y1, nh-h-y1, x1, nw-w-x1,
# cv2.BORDER_CONSTANT, value=val) # slightly faster
return expand
class Pad(object):
def __init__(self, padding, fillval=0, anchor=None):
if isinstance(padding, numbers.Number):
padding = (padding, padding)
assert len(padding) == 2
self.padding = [int(np.clip(_), 0, None) for _ in padding]
self.fillval = fillval
self.anchor = anchor
def __call__(self, img, cds=None):
if max(self.padding) == 0:
return img if cds is None else (img, cds)
h, w = img.shape[:2]
pw, ph = self.padding
pad = lambda im: _expand(im, (w + pw*2, h + ph*2), (pw, ph), self.fillval)
purer = lambda im: _expand(im, (w + pw*2, h + ph*2), (pw, ph), 0)
img = HalfBlood(img, self.anchor, pad, purer)
if cds is not None:
return img, np.array([[x + pw, y + ph] for x, y in cds])
else:
return img
# "SSD: Single Shot MultiBox Detector". generate multi-resolution image/ multi-scale objects
class Expand(object):
def __init__(self, scale_range=(1, 4), fillval=0, prob=1.0, anchor=None, random_state=np.random):
if isinstance(scale_range, numbers.Number):
scale_range = (1, scale_range)
assert max(scale_range) <= 5
self.scale_range = scale_range
self.fillval = fillval
self.prob = prob
self.anchor = anchor
self.random = random_state
def __call__(self, img, cds=None):
if self.prob < 1 and self.random.random_sample() >= self.prob:
return img if cds is None else (img, cds)
#multiple = _loguniform(self.scale_range, self.random)
multiple = self.random.uniform(*self.scale_range)
h, w = img.shape[:2]
nh, nw = int(multiple * h), int(multiple * w)
if multiple < 1:
return RandomCrop(size=(nw, nh), random_state=self.random)(img, cds)
y1 = self.random.randint(0, nh - h + 1)
x1 = self.random.randint(0, nw - w + 1)
expand = lambda im: _expand(im, (nw, nh), (x1, y1), self.fillval)
purer = lambda im: _expand(im, (nw, nh), (x1, y1), 0)
img = HalfBlood(img, self.anchor, expand, purer)
if cds is not None:
return img, np.array([[x + x1, y + y1] for x, y in cds])
else:
return img
# scales the smaller edge to given size
class Scale(object):
def __init__(self, size, mode='linear', lazy=False, anchor=None, random_state=np.random):
assert isinstance(size, int)
self.size = int(size)
self.mode = mode
self.lazy = lazy
self.anchor = anchor
self.random = random_state
def __call__(self, img, cds=None):
interp_mode = (self.random.choice(list(InterpolationFlags.values())) if self.mode is None
else InterpolationFlags.get(self.mode, cv2.INTER_LINEAR))
h, w = img.shape[:2]
if self.lazy and min(h, w) >= self.size:
return img if cds is None else (img, cds)
if h < w:
tw, th = int(self.size / float(h) * w), self.size
else:
th, tw = int(self.size / float(w) * h), self.size
# skimage.transform.resize 10x slower than cv2.resize
resize = lambda im: cv2.resize(im, (tw, th), interpolation=interp_mode)
purer = lambda im: cv2.resize(im, (tw, th), interpolation=cv2.INTER_NEAREST)
img = HalfBlood(img, self.anchor, resize, purer)
if cds is not None:
s_x, s_y = tw / float(w), th / float(h)
return img, np.array([[x * s_x, y * s_y] for x, y in cds])
else:
return img
class RandomScale(object):
def __init__(self, size_range, mode='linear', anchor=None, random_state=np.random):
assert isinstance(size_range, collections.Sequence) and len(size_range) == 2
self.size_range = size_range
self.mode = mode
self.anchor = anchor
self.random = random_state
def __call__(self, img, cds=None):
interp_mode = (self.random.choice(list(InterpolationFlags.values())) if self.mode is None
else InterpolationFlags.get(self.mode, cv2.INTER_LINEAR))
h, w = img.shape[:2]
size = int(self.random.uniform(*self.size_range))
if h < w:
tw, th = int(size / float(h) * w), size
else:
th, tw = int(size / float(w) * h), size
resize = lambda im: cv2.resize(im, (tw, th), interpolation=interp_mode)
purer = lambda im: cv2.resize(im, (tw, th), interpolation=cv2.INTER_NEAREST)
img = HalfBlood(img, self.anchor, resize, purer)
if cds is not None:
s_x, s_y = tw / float(w), th / float(h)
return img, np.array([[x * s_x, y * s_y] for x, y in cds])
else:
return img
class CenterCrop(object):
def __init__(self, size):
if isinstance(size, numbers.Number):
size = (int(size), int(size))
self.size = size
def __call__(self, img, cds=None):
h, w = img.shape[:2]
tw, th = self.size
if h == th and w == tw:
return img if cds is None else (img, cds)
elif h < th or w < tw:
raise Exception('invalid crop size')
x1 = int(round((w - tw) / 2.))
y1 = int(round((h - th) / 2.))
img = img[y1:y1 + th, x1:x1 + tw]
if cds is not None:
return img, _coords_clamp([[x - x1, y - y1] for x, y in cds], img.shape)
else:
return img
class RandomCrop(object):
def __init__(self, size, fillval=0, random_state=np.random):
if isinstance(size, numbers.Number):
size = (int(size), int(size))
self.size = size
self.random = random_state
def __call__(self, img, cds=None):
h, w = img.shape[:2]
tw, th = self.size
assert h >= th and w >= tw
x1 = self.random.randint(0, w - tw + 1)
y1 = self.random.randint(0, h - th + 1)
img = img[y1:y1 + th, x1:x1 + tw]
if cds is not None:
return img, _coords_clamp([[x - x1, y - y1] for x, y in cds], img.shape)
else:
return img
'''
# "SSD: Single Shot MultiBox Detector".
# object-aware RandomCrop, crop multi-scale objects
class ObjectRandomCrop(object):
def __init__(self, final_size=None, prob=1., random_state=np.random):
self.final_size = final_size # reference size
self.final_area = (final_size * final_size if isinstance(final_size, numbers.Number)
else np.prod(final_size))
self.prob = prob
self.random = random_state
self.options = [
None, # keep original size
#(-np.inf, 0.1), # large crop
(0.02, 0.1),
(0.1, 0.3),
(0.3, 0.5),
(0.5, 0.7),
(0.7, np.inf), # small crop
(-np.inf, np.inf), # arbitrary size
]
def __call__(self, img, cbs):
h, w = img.shape[:2]
# ad-hoc
if len(cbs) == 0:
return img, cbs
if len(cbs[0]) == 4:
boxes = cbs
elif len(cbs[0]) == 2:
boxes = _to_bboxes(cbs, img.shape[:2])
else:
raise Exception('invalid input')
for attempt in range(30):
mode = self.random.choice(self.options)
if mode is None or (self.prob < 1 and self.random.random_sample() >= self.prob):
if self.final_size is not None:
# area constraint
box_areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1)
size = np.sqrt(box_areas * self.final_area / (h * w))
if not ((11 < size) * (size < 18)).any() and size.max() > 22:
return img, cbs
mode = self.options[self.random.randint(1, len(self.options))]
else:
return img, cbs
min_iou, max_iou = mode
for _ in range(50):
tw = self.random.uniform(0.3 * w, w)
th = self.random.uniform(0.3 * h, h)
if max(th / tw, tw / th) > 2:
continue
x1 = self.random.randint(0, w - tw + 1)
y1 = self.random.randint(0, h - th + 1)
rect = np.array([int(x1), int(y1), int(x1+tw), int(y1+th)])
jaccard, coverage, inter = _jaccard(boxes, rect)
# iou constraint
if jaccard.max() < min_iou or jaccard.max() > max_iou:
continue
# coverage constraint
m1 = coverage > 1/9.
m2 = coverage < 0.45
if (m1 * m2).any():
continue
mask = coverage >= 0.45
if not mask.any():
continue
# area constraint
if self.final_size is not None:
area = (rect[2] - rect[0]) * (rect[3] - rect[1]) * 1.
size = np.sqrt(inter[mask] * self.final_area / area)
if ((11 < size) * (size < 18)).any() or size.max() < 22:
continue
img = img[rect[1]:rect[3], rect[0]:rect[2]]
boxes[:, :2] = np.clip(boxes[:, :2], rect[:2], rect[2:])
boxes[:, :2] = boxes[:, :2] - rect[:2]
boxes[:, 2:] = np.clip(boxes[:, 2:], rect[:2], rect[2:])
boxes[:, 2:] = boxes[:, 2:] - rect[:2]
boxes[np.logical_not(mask), :] = 0
#print(min_iou, max_iou)
if len(cbs[0]) == 4:
return img, boxes
else:
return img, _to_coords(boxes)
# Fallback
return img, cbs
'''
class ObjectRandomCrop(object):
def __init__(self, prob=1., random_state=np.random):
self.prob = prob
self.random = random_state
self.options = [
#(0, None),
(0.1, None),
(0.3, None),
(0.5, None),
(0.7, None),
(0.9, None),
(None, 1), ]
def __call__(self, img, cbs):
h, w = img.shape[:2]
if len(cbs) == 0:
return img, cbs
# ad-hoc
if len(cbs[0]) == 4:
boxes = cbs
elif len(cbs[0]) == 2:
boxes = _to_bboxes(cbs, img.shape[:2])
else:
raise Exception('invalid input')
params = [(np.array([0, 0, w, h]), None)]
for min_iou, max_iou in self.options:
if min_iou is None:
min_iou = 0
if max_iou is None:
max_iou = 1
for _ in range(50):
scale = self.random.uniform(0.3, 1)
aspect_ratio = self.random.uniform(
max(1 / 2., scale * scale),
min(2., 1 / (scale * scale)))
th = int(h * scale / np.sqrt(aspect_ratio))
tw = int(w * scale * np.sqrt(aspect_ratio))
x1 = self.random.randint(0, w - tw + 1)
y1 = self.random.randint(0, h - th + 1)
rect = np.array([x1, y1, x1 + tw, y1 + th])
iou, coverage, _ = _jaccard(boxes, rect)
#m1 = coverage > 0.1
#m2 = coverage < 0.45
#if (m1 * m2).any():
# continue
center = (boxes[:, :2] + boxes[:, 2:]) / 2
mask = np.logical_and(rect[:2] <= center, center < rect[2:]).all(axis=1)
#mask = coverage >= 0.45
#mask
if not mask.any():
continue
if min_iou <= iou.max() and iou.min() <= max_iou:
params.append((rect, mask))
break
rect, mask = params[self.random.randint(len(params))]
img = img[rect[1]:rect[3], rect[0]:rect[2]]
boxes[:, :2] = np.clip(boxes[:, :2], rect[:2], rect[2:])
boxes[:, :2] = boxes[:, :2] - rect[:2]
boxes[:, 2:] = np.clip(boxes[:, 2:], rect[:2], rect[2:])
boxes[:, 2:] = boxes[:, 2:] - rect[:2]
if mask is not None:
boxes[np.logical_not(mask), :] = 0
if len(cbs[0]) == 4:
return img, boxes
else:
return img, _to_coords(boxes)
# Random crop with size 8%-100% and aspect ratio 3/4 - 4/3. (Inception-style)
class RandomSizedCrop(object):
def __init__(self, size, mode='linear', anchor=None, random_state=np.random):
self.size = size
self.mode = mode
self.anchor = anchor
self.random = random_state
self.scale = Scale(size, mode=mode, anchor=anchor)
self.crop = CenterCrop(size)
def __call__(self, img, cds=None):
interp_mode = (self.random.choice(list(InterpolationFlags.values())) if self.mode is None
else InterpolationFlags.get(self.mode, cv2.INTER_LINEAR))
h, w = img.shape[:2]
for _ in range(10):
area = h * w
target_area = self.random.uniform(0.16, 1.0) * area # 0.08~1.0
aspect_ratio = self.random.uniform(3. / 4, 4. / 3)
tw = int(round(np.sqrt(target_area * aspect_ratio)))
th = int(round(np.sqrt(target_area / aspect_ratio)))
if self.random.random_sample() < 0.5:
tw, th = th, tw
if tw <= w and th <= h:
x1 = self.random.randint(0, w - tw + 1)
y1 = self.random.randint(0, h - th + 1)
img = img[y1:y1 + th, x1:x1 + tw]
resize = lambda im: cv2.resize(im, (self.size, self.size), interpolation=interp_mode)
purer = lambda im: cv2.resize(im, (self.size, self.size), interpolation=cv2.INTER_NEAREST)
img = HalfBlood(img, self.anchor, resize, purer)
if cds is not None:
scale_x = self.size / float(tw)
scale_y = self.size / float(th)
return img, _coords_clamp([[scale_x*(x-x1), scale_y*(y-y1)] for x, y in cds], img.shape)
else:
return img
# Fallback
return self.crop(self.scale(img, cds=cds), cds=cds)
class GridCrop(object):
def __init__(self, size, grid=5, random_state=np.random):
# 4 grids, 5 grids or 9 grids
if isinstance(size, numbers.Number):
size = (int(size), int(size))
self.size = size
self.grid = grid
self.random = random_state
self.map = {
0: lambda w, h, tw, th: ( 0, 0),
1: lambda w, h, tw, th: ( w - tw, 0),
2: lambda w, h, tw, th: ( w - tw, h - th),
3: lambda w, h, tw, th: ( 0, h - th),
4: lambda w, h, tw, th: ((w - tw) // 2, (h - th) // 2),
5: lambda w, h, tw, th: ((w - tw) // 2, 0),
6: lambda w, h, tw, th: ( w - tw, (h - th) // 2),
7: lambda w, h, tw, th: ((w - tw) // 2, h - th),
8: lambda w, h, tw, th: ( 0, (h - th) // 2),
}