Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

transforms.py 43 KB

You have to be logged in to leave a comment. Sign In
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
  1. import collections
  2. import math
  3. import random
  4. from typing import Optional, Union, Tuple, List, Sequence, Dict
  5. import torch.nn
  6. from PIL import Image, ImageFilter, ImageOps
  7. from torchvision import transforms as transforms
  8. import numpy as np
  9. import cv2
  10. from super_gradients.common.abstractions.abstract_logger import get_logger
  11. from super_gradients.training.utils.detection_utils import get_mosaic_coordinate, adjust_box_anns, xyxy2cxcywh, cxcywh2xyxy, DetectionTargetsFormat
  12. image_resample = Image.BILINEAR
  13. mask_resample = Image.NEAREST
  14. logger = get_logger(__name__)
  15. class SegmentationTransform:
  16. def __call__(self, *args, **kwargs):
  17. raise NotImplementedError
  18. def __repr__(self):
  19. return self.__class__.__name__ + str(self.__dict__).replace("{", "(").replace("}", ")")
  20. class SegResize(SegmentationTransform):
  21. def __init__(self, h, w):
  22. self.h = h
  23. self.w = w
  24. def __call__(self, sample):
  25. image = sample["image"]
  26. mask = sample["mask"]
  27. sample["image"] = image.resize((self.w, self.h), image_resample)
  28. sample["mask"] = mask.resize((self.w, self.h), mask_resample)
  29. return sample
  30. class SegRandomFlip(SegmentationTransform):
  31. """
  32. Randomly flips the image and mask (synchronously) with probability 'prob'.
  33. """
  34. def __init__(self, prob: float = 0.5):
  35. assert 0.0 <= prob <= 1.0, f"Probability value must be between 0 and 1, found {prob}"
  36. self.prob = prob
  37. def __call__(self, sample: dict):
  38. image = sample["image"]
  39. mask = sample["mask"]
  40. if random.random() < self.prob:
  41. image = image.transpose(Image.FLIP_LEFT_RIGHT)
  42. mask = mask.transpose(Image.FLIP_LEFT_RIGHT)
  43. sample["image"] = image
  44. sample["mask"] = mask
  45. return sample
  46. class SegRescale(SegmentationTransform):
  47. """
  48. Rescales the image and mask (synchronously) while preserving aspect ratio.
  49. The rescaling can be done according to scale_factor, short_size or long_size.
  50. If more than one argument is given, the rescaling mode is determined by this order: scale_factor, then short_size,
  51. then long_size.
  52. Args:
  53. scale_factor: rescaling is done by multiplying input size by scale_factor:
  54. out_size = (scale_factor * w, scale_factor * h)
  55. short_size: rescaling is done by determining the scale factor by the ratio short_size / min(h, w).
  56. long_size: rescaling is done by determining the scale factor by the ratio long_size / max(h, w).
  57. """
  58. def __init__(self, scale_factor: Optional[float] = None, short_size: Optional[int] = None, long_size: Optional[int] = None):
  59. self.scale_factor = scale_factor
  60. self.short_size = short_size
  61. self.long_size = long_size
  62. self.check_valid_arguments()
  63. def __call__(self, sample: dict):
  64. image = sample["image"]
  65. mask = sample["mask"]
  66. w, h = image.size
  67. if self.scale_factor is not None:
  68. scale = self.scale_factor
  69. elif self.short_size is not None:
  70. short_size = min(w, h)
  71. scale = self.short_size / short_size
  72. else:
  73. long_size = max(w, h)
  74. scale = self.long_size / long_size
  75. out_size = int(scale * w), int(scale * h)
  76. image = image.resize(out_size, image_resample)
  77. mask = mask.resize(out_size, mask_resample)
  78. sample["image"] = image
  79. sample["mask"] = mask
  80. return sample
  81. def check_valid_arguments(self):
  82. if self.scale_factor is None and self.short_size is None and self.long_size is None:
  83. raise ValueError("Must assign one rescale argument: scale_factor, short_size or long_size")
  84. if self.scale_factor is not None and self.scale_factor <= 0:
  85. raise ValueError(f"Scale factor must be a positive number, found: {self.scale_factor}")
  86. if self.short_size is not None and self.short_size <= 0:
  87. raise ValueError(f"Short size must be a positive number, found: {self.short_size}")
  88. if self.long_size is not None and self.long_size <= 0:
  89. raise ValueError(f"Long size must be a positive number, found: {self.long_size}")
  90. class SegRandomRescale:
  91. """
  92. Random rescale the image and mask (synchronously) while preserving aspect ratio.
  93. Scale factor is randomly picked between scales [min, max]
  94. Args:
  95. scales: scale range tuple (min, max), if scales is a float range will be defined as (1, scales) if scales > 1,
  96. otherwise (scales, 1). must be a positive number.
  97. """
  98. def __init__(self, scales: Union[float, Tuple, List] = (0.5, 2.0)):
  99. self.scales = scales
  100. self.check_valid_arguments()
  101. def __call__(self, sample: dict):
  102. image = sample["image"]
  103. mask = sample["mask"]
  104. w, h = image.size
  105. scale = random.uniform(self.scales[0], self.scales[1])
  106. out_size = int(scale * w), int(scale * h)
  107. image = image.resize(out_size, image_resample)
  108. mask = mask.resize(out_size, mask_resample)
  109. sample["image"] = image
  110. sample["mask"] = mask
  111. return sample
  112. def check_valid_arguments(self):
  113. """
  114. Check the scale values are valid. if order is wrong, flip the order and return the right scale values.
  115. """
  116. if not isinstance(self.scales, collections.abc.Iterable):
  117. if self.scales <= 1:
  118. self.scales = (self.scales, 1)
  119. else:
  120. self.scales = (1, self.scales)
  121. if self.scales[0] < 0 or self.scales[1] < 0:
  122. raise ValueError(f"SegRandomRescale scale values must be positive numbers, found: {self.scales}")
  123. if self.scales[0] > self.scales[1]:
  124. self.scales = (self.scales[1], self.scales[0])
  125. return self.scales
  126. class SegRandomRotate(SegmentationTransform):
  127. """
  128. Randomly rotates image and mask (synchronously) between 'min_deg' and 'max_deg'.
  129. """
  130. def __init__(self, min_deg: float = -10, max_deg: float = 10, fill_mask: int = 0, fill_image: Union[int, Tuple, List] = 0):
  131. self.min_deg = min_deg
  132. self.max_deg = max_deg
  133. self.fill_mask = fill_mask
  134. # grey color in RGB mode
  135. self.fill_image = (fill_image, fill_image, fill_image)
  136. self.check_valid_arguments()
  137. def __call__(self, sample: dict):
  138. image = sample["image"]
  139. mask = sample["mask"]
  140. deg = random.uniform(self.min_deg, self.max_deg)
  141. image = image.rotate(deg, resample=image_resample, fillcolor=self.fill_image)
  142. mask = mask.rotate(deg, resample=mask_resample, fillcolor=self.fill_mask)
  143. sample["image"] = image
  144. sample["mask"] = mask
  145. return sample
  146. def check_valid_arguments(self):
  147. self.fill_mask, self.fill_image = _validate_fill_values_arguments(self.fill_mask, self.fill_image)
  148. class SegCropImageAndMask(SegmentationTransform):
  149. """
  150. Crops image and mask (synchronously).
  151. In "center" mode a center crop is performed while, in "random" mode the drop will be positioned around
  152. random coordinates.
  153. """
  154. def __init__(self, crop_size: Union[float, Tuple, List], mode: str):
  155. """
  156. :param crop_size: tuple of (width, height) for the final crop size, if is scalar size is a
  157. square (crop_size, crop_size)
  158. :param mode: how to choose the center of the crop, 'center' for the center of the input image,
  159. 'random' center the point is chosen randomally
  160. """
  161. self.crop_size = crop_size
  162. self.mode = mode
  163. self.check_valid_arguments()
  164. def __call__(self, sample: dict):
  165. image = sample["image"]
  166. mask = sample["mask"]
  167. w, h = image.size
  168. if self.mode == "random":
  169. x1 = random.randint(0, w - self.crop_size[0])
  170. y1 = random.randint(0, h - self.crop_size[1])
  171. else:
  172. x1 = int(round((w - self.crop_size[0]) / 2.0))
  173. y1 = int(round((h - self.crop_size[1]) / 2.0))
  174. image = image.crop((x1, y1, x1 + self.crop_size[0], y1 + self.crop_size[1]))
  175. mask = mask.crop((x1, y1, x1 + self.crop_size[0], y1 + self.crop_size[1]))
  176. sample["image"] = image
  177. sample["mask"] = mask
  178. return sample
  179. def check_valid_arguments(self):
  180. if self.mode not in ["center", "random"]:
  181. raise ValueError(f"Unsupported mode: found: {self.mode}, expected: 'center' or 'random'")
  182. if not isinstance(self.crop_size, collections.abc.Iterable):
  183. self.crop_size = (self.crop_size, self.crop_size)
  184. if self.crop_size[0] <= 0 or self.crop_size[1] <= 0:
  185. raise ValueError(f"Crop size must be positive numbers, found: {self.crop_size}")
  186. class SegRandomGaussianBlur(SegmentationTransform):
  187. """
  188. Adds random Gaussian Blur to image with probability 'prob'.
  189. """
  190. def __init__(self, prob: float = 0.5):
  191. assert 0.0 <= prob <= 1.0, "Probability value must be between 0 and 1"
  192. self.prob = prob
  193. def __call__(self, sample: dict):
  194. image = sample["image"]
  195. mask = sample["mask"]
  196. if random.random() < self.prob:
  197. image = image.filter(ImageFilter.GaussianBlur(radius=random.random()))
  198. sample["image"] = image
  199. sample["mask"] = mask
  200. return sample
  201. class SegPadShortToCropSize(SegmentationTransform):
  202. """
  203. Pads image to 'crop_size'.
  204. Should be called only after "SegRescale" or "SegRandomRescale" in augmentations pipeline.
  205. """
  206. def __init__(self, crop_size: Union[float, Tuple, List], fill_mask: int = 0, fill_image: Union[int, Tuple, List] = 0):
  207. """
  208. :param crop_size: tuple of (width, height) for the final crop size, if is scalar size is a
  209. square (crop_size, crop_size)
  210. :param fill_mask: value to fill mask labels background.
  211. :param fill_image: grey value to fill image padded background.
  212. """
  213. # CHECK IF CROP SIZE IS A ITERABLE OR SCALAR
  214. self.crop_size = crop_size
  215. self.fill_mask = fill_mask
  216. self.fill_image = tuple(fill_image) if isinstance(fill_image, Sequence) else fill_image
  217. self.check_valid_arguments()
  218. def __call__(self, sample: dict):
  219. image = sample["image"]
  220. mask = sample["mask"]
  221. w, h = image.size
  222. # pad images from center symmetrically
  223. if w < self.crop_size[0] or h < self.crop_size[1]:
  224. padh = (self.crop_size[1] - h) / 2 if h < self.crop_size[1] else 0
  225. pad_top, pad_bottom = math.ceil(padh), math.floor(padh)
  226. padw = (self.crop_size[0] - w) / 2 if w < self.crop_size[0] else 0
  227. pad_left, pad_right = math.ceil(padw), math.floor(padw)
  228. image = ImageOps.expand(image, border=(pad_left, pad_top, pad_right, pad_bottom), fill=self.fill_image)
  229. mask = ImageOps.expand(mask, border=(pad_left, pad_top, pad_right, pad_bottom), fill=self.fill_mask)
  230. sample["image"] = image
  231. sample["mask"] = mask
  232. return sample
  233. def check_valid_arguments(self):
  234. if not isinstance(self.crop_size, collections.abc.Iterable):
  235. self.crop_size = (self.crop_size, self.crop_size)
  236. if self.crop_size[0] <= 0 or self.crop_size[1] <= 0:
  237. raise ValueError(f"Crop size must be positive numbers, found: {self.crop_size}")
  238. self.fill_mask, self.fill_image = _validate_fill_values_arguments(self.fill_mask, self.fill_image)
  239. class SegColorJitter(transforms.ColorJitter):
  240. def __call__(self, sample):
  241. sample["image"] = super(SegColorJitter, self).__call__(sample["image"])
  242. return sample
  243. def _validate_fill_values_arguments(fill_mask: int, fill_image: Union[int, Tuple, List]):
  244. if not isinstance(fill_image, collections.abc.Iterable):
  245. # If fill_image is single value, turn to grey color in RGB mode.
  246. fill_image = (fill_image, fill_image, fill_image)
  247. elif len(fill_image) != 3:
  248. raise ValueError(f"fill_image must be an RGB tuple of size equal to 3, found: {fill_image}")
  249. # assert values are integers
  250. if not isinstance(fill_mask, int) or not all(isinstance(x, int) for x in fill_image):
  251. raise ValueError(f"Fill value must be integers," f" found: fill_image = {fill_image}, fill_mask = {fill_mask}")
  252. # assert values in range 0-255
  253. if min(fill_image) < 0 or max(fill_image) > 255 or fill_mask < 0 or fill_mask > 255:
  254. raise ValueError(f"Fill value must be a value from 0 to 255," f" found: fill_image = {fill_image}, fill_mask = {fill_mask}")
  255. return fill_mask, fill_image
  256. class DetectionTransform:
  257. """
  258. Detection transform base class.
  259. Complex transforms that require extra data loading can use the the additional_samples_count attribute in a
  260. similar fashion to what's been done in COCODetectionDataset:
  261. self._load_additional_inputs_for_transform(sample, transform)
  262. # after the above call, sample["additional_samples"] holds a list of additional inputs and targets.
  263. sample = transform(sample)
  264. Attributes:
  265. additional_samples_count: (int) additional samples to be loaded.
  266. non_empty_targets: (bool) whether the additianl targets can have empty targets or not.
  267. """
  268. def __init__(self, additional_samples_count: int = 0, non_empty_targets: bool = False):
  269. self.additional_samples_count = additional_samples_count
  270. self.non_empty_targets = non_empty_targets
  271. def __call__(self, sample: Union[dict, list]):
  272. raise NotImplementedError
  273. def __repr__(self):
  274. return self.__class__.__name__ + str(self.__dict__).replace("{", "(").replace("}", ")")
  275. class DetectionMosaic(DetectionTransform):
  276. """
  277. DetectionMosaic detection transform
  278. Attributes:
  279. input_dim: (tuple) input dimension.
  280. prob: (float) probability of applying mosaic.
  281. enable_mosaic: (bool) whether to apply mosaic at all (regardless of prob) (default=True).
  282. border_value: value for filling borders after applying transforms (default=114).
  283. """
  284. def __init__(self, input_dim: tuple, prob: float = 1.0, enable_mosaic: bool = True, border_value=114):
  285. super(DetectionMosaic, self).__init__(additional_samples_count=3)
  286. self.prob = prob
  287. self.input_dim = input_dim
  288. self.enable_mosaic = enable_mosaic
  289. self.border_value = border_value
  290. def close(self):
  291. self.additional_samples_count = 0
  292. self.enable_mosaic = False
  293. def __call__(self, sample: Union[dict, list]):
  294. if self.enable_mosaic and random.random() < self.prob:
  295. mosaic_labels = []
  296. mosaic_labels_seg = []
  297. input_h, input_w = self.input_dim[0], self.input_dim[1]
  298. # yc, xc = s, s # mosaic center x, y
  299. yc = int(random.uniform(0.5 * input_h, 1.5 * input_h))
  300. xc = int(random.uniform(0.5 * input_w, 1.5 * input_w))
  301. # 3 additional samples, total of 4
  302. all_samples = [sample] + sample["additional_samples"]
  303. for i_mosaic, mosaic_sample in enumerate(all_samples):
  304. img, _labels = mosaic_sample["image"], mosaic_sample["target"]
  305. _labels_seg = mosaic_sample.get("target_seg")
  306. h0, w0 = img.shape[:2] # orig hw
  307. scale = min(1.0 * input_h / h0, 1.0 * input_w / w0)
  308. img = cv2.resize(img, (int(w0 * scale), int(h0 * scale)), interpolation=cv2.INTER_LINEAR)
  309. # generate output mosaic image
  310. (h, w, c) = img.shape[:3]
  311. if i_mosaic == 0:
  312. mosaic_img = np.full((input_h * 2, input_w * 2, c), self.border_value, dtype=np.uint8)
  313. # suffix l means large image, while s means small image in mosaic aug.
  314. (l_x1, l_y1, l_x2, l_y2), (s_x1, s_y1, s_x2, s_y2) = get_mosaic_coordinate(i_mosaic, xc, yc, w, h, input_h, input_w)
  315. mosaic_img[l_y1:l_y2, l_x1:l_x2] = img[s_y1:s_y2, s_x1:s_x2]
  316. padw, padh = l_x1 - s_x1, l_y1 - s_y1
  317. labels = _labels.copy()
  318. # Normalized xywh to pixel xyxy format
  319. if _labels.size > 0:
  320. labels[:, 0] = scale * _labels[:, 0] + padw
  321. labels[:, 1] = scale * _labels[:, 1] + padh
  322. labels[:, 2] = scale * _labels[:, 2] + padw
  323. labels[:, 3] = scale * _labels[:, 3] + padh
  324. mosaic_labels.append(labels)
  325. if _labels_seg is not None:
  326. labels_seg = _labels_seg.copy()
  327. if _labels.size > 0:
  328. labels_seg[:, ::2] = scale * labels_seg[:, ::2] + padw
  329. labels_seg[:, 1::2] = scale * labels_seg[:, 1::2] + padh
  330. mosaic_labels_seg.append(labels_seg)
  331. if len(mosaic_labels):
  332. mosaic_labels = np.concatenate(mosaic_labels, 0)
  333. np.clip(mosaic_labels[:, 0], 0, 2 * input_w, out=mosaic_labels[:, 0])
  334. np.clip(mosaic_labels[:, 1], 0, 2 * input_h, out=mosaic_labels[:, 1])
  335. np.clip(mosaic_labels[:, 2], 0, 2 * input_w, out=mosaic_labels[:, 2])
  336. np.clip(mosaic_labels[:, 3], 0, 2 * input_h, out=mosaic_labels[:, 3])
  337. if len(mosaic_labels_seg):
  338. mosaic_labels_seg = np.concatenate(mosaic_labels_seg, 0)
  339. np.clip(mosaic_labels_seg[:, ::2], 0, 2 * input_w, out=mosaic_labels_seg[:, ::2])
  340. np.clip(mosaic_labels_seg[:, 1::2], 0, 2 * input_h, out=mosaic_labels_seg[:, 1::2])
  341. sample["image"] = mosaic_img
  342. sample["target"] = mosaic_labels
  343. sample["info"] = (mosaic_img.shape[1], mosaic_img.shape[0])
  344. if len(mosaic_labels_seg):
  345. sample["target_seg"] = mosaic_labels_seg
  346. return sample
  347. class DetectionRandomAffine(DetectionTransform):
  348. """
  349. DetectionRandomAffine detection transform
  350. Attributes:
  351. target_size: (tuple) desired output shape.
  352. degrees: (Union[tuple, float]) degrees for random rotation, when float the random values are drawn uniformly
  353. from (-degrees, degrees)
  354. translate: (Union[tuple, float]) translate size (in pixels) for random translation, when float the random values
  355. are drawn uniformly from (-translate, translate)
  356. scales: (Union[tuple, float]) values for random rescale, when float the random values are drawn uniformly
  357. from (0.1-scales, 0.1+scales)
  358. shear: (Union[tuple, float]) degrees for random shear, when float the random values are drawn uniformly
  359. from (shear, shear)
  360. enable: (bool) whether to apply the below transform at all.
  361. filter_box_candidates: (bool) whether to filter out transformed bboxes by edge size, area ratio, and aspect ratio (default=False).
  362. wh_thr: (float) edge size threshold when filter_box_candidates = True. Bounding oxes with edges smaller
  363. then this values will be filtered out. (default=2)
  364. ar_thr: (float) aspect ratio threshold filter_box_candidates = True. Bounding boxes with aspect ratio larger
  365. then this values will be filtered out. (default=20)
  366. area_thr:(float) threshold for area ratio between original image and the transformed one, when when filter_box_candidates = True.
  367. Bounding boxes with such ratio smaller then this value will be filtered out. (default=0.1)
  368. border_value: value for filling borders after applying transforms (default=114).
  369. """
  370. def __init__(
  371. self,
  372. degrees=10,
  373. translate=0.1,
  374. scales=0.1,
  375. shear=10,
  376. target_size=(640, 640),
  377. filter_box_candidates: bool = False,
  378. wh_thr=2,
  379. ar_thr=20,
  380. area_thr=0.1,
  381. border_value=114,
  382. ):
  383. super(DetectionRandomAffine, self).__init__()
  384. self.degrees = degrees
  385. self.translate = translate
  386. self.scale = scales
  387. self.shear = shear
  388. self.target_size = target_size
  389. self.enable = True
  390. self.filter_box_candidates = filter_box_candidates
  391. self.wh_thr = wh_thr
  392. self.ar_thr = ar_thr
  393. self.area_thr = area_thr
  394. self.border_value = border_value
  395. def close(self):
  396. self.enable = False
  397. def __call__(self, sample: dict):
  398. if self.enable:
  399. img, target = random_affine(
  400. sample["image"],
  401. sample["target"],
  402. sample.get("target_seg"),
  403. target_size=self.target_size,
  404. degrees=self.degrees,
  405. translate=self.translate,
  406. scales=self.scale,
  407. shear=self.shear,
  408. filter_box_candidates=self.filter_box_candidates,
  409. wh_thr=self.wh_thr,
  410. area_thr=self.area_thr,
  411. ar_thr=self.ar_thr,
  412. border_value=self.border_value,
  413. )
  414. sample["image"] = img
  415. sample["target"] = target
  416. return sample
  417. class DetectionMixup(DetectionTransform):
  418. """
  419. Mixup detection transform
  420. Attributes:
  421. input_dim: (tuple) input dimension.
  422. mixup_scale: (tuple) scale range for the additional loaded image for mixup.
  423. prob: (float) probability of applying mixup.
  424. enable_mixup: (bool) whether to apply mixup at all (regardless of prob) (default=True).
  425. flip_prob: (float) prbability to apply horizontal flip to the additional sample.
  426. border_value: value for filling borders after applying transform (default=114).
  427. """
  428. def __init__(self, input_dim, mixup_scale, prob=1.0, enable_mixup=True, flip_prob=0.5, border_value=114):
  429. super(DetectionMixup, self).__init__(additional_samples_count=1, non_empty_targets=True)
  430. self.input_dim = input_dim
  431. self.mixup_scale = mixup_scale
  432. self.prob = prob
  433. self.enable_mixup = enable_mixup
  434. self.flip_prob = flip_prob
  435. self.border_value = border_value
  436. def close(self):
  437. self.additional_samples_count = 0
  438. self.enable_mixup = False
  439. def __call__(self, sample: dict):
  440. if self.enable_mixup and random.random() < self.prob:
  441. origin_img, origin_labels = sample["image"], sample["target"]
  442. cp_sample = sample["additional_samples"][0]
  443. img, cp_labels = cp_sample["image"], cp_sample["target"]
  444. cp_boxes = cp_labels[:, :4]
  445. img, cp_boxes = _mirror(img, cp_boxes, self.flip_prob)
  446. # PLUG IN TARGET THE FLIPPED BOXES
  447. cp_labels[:, :4] = cp_boxes
  448. jit_factor = random.uniform(*self.mixup_scale)
  449. if len(img.shape) == 3:
  450. cp_img = np.ones((self.input_dim[0], self.input_dim[1], img.shape[2]), dtype=np.uint8) * self.border_value
  451. else:
  452. cp_img = np.ones(self.input_dim, dtype=np.uint8) * self.border_value
  453. cp_scale_ratio = min(self.input_dim[0] / img.shape[0], self.input_dim[1] / img.shape[1])
  454. resized_img = cv2.resize(
  455. img,
  456. (int(img.shape[1] * cp_scale_ratio), int(img.shape[0] * cp_scale_ratio)),
  457. interpolation=cv2.INTER_LINEAR,
  458. )
  459. cp_img[: int(img.shape[0] * cp_scale_ratio), : int(img.shape[1] * cp_scale_ratio)] = resized_img
  460. cp_img = cv2.resize(
  461. cp_img,
  462. (int(cp_img.shape[1] * jit_factor), int(cp_img.shape[0] * jit_factor)),
  463. )
  464. cp_scale_ratio *= jit_factor
  465. origin_h, origin_w = cp_img.shape[:2]
  466. target_h, target_w = origin_img.shape[:2]
  467. if len(img.shape) == 3:
  468. padded_img = np.zeros((max(origin_h, target_h), max(origin_w, target_w), img.shape[2]), dtype=np.uint8)
  469. else:
  470. padded_img = np.zeros((max(origin_h, target_h), max(origin_w, target_w)), dtype=np.uint8)
  471. padded_img[:origin_h, :origin_w] = cp_img
  472. x_offset, y_offset = 0, 0
  473. if padded_img.shape[0] > target_h:
  474. y_offset = random.randint(0, padded_img.shape[0] - target_h - 1)
  475. if padded_img.shape[1] > target_w:
  476. x_offset = random.randint(0, padded_img.shape[1] - target_w - 1)
  477. padded_cropped_img = padded_img[y_offset : y_offset + target_h, x_offset : x_offset + target_w]
  478. cp_bboxes_origin_np = adjust_box_anns(cp_labels[:, :4].copy(), cp_scale_ratio, 0, 0, origin_w, origin_h)
  479. cp_bboxes_transformed_np = cp_bboxes_origin_np.copy()
  480. cp_bboxes_transformed_np[:, 0::2] = np.clip(cp_bboxes_transformed_np[:, 0::2] - x_offset, 0, target_w)
  481. cp_bboxes_transformed_np[:, 1::2] = np.clip(cp_bboxes_transformed_np[:, 1::2] - y_offset, 0, target_h)
  482. cls_labels = cp_labels[:, 4:5].copy()
  483. box_labels = cp_bboxes_transformed_np
  484. labels = np.hstack((box_labels, cls_labels))
  485. origin_labels = np.vstack((origin_labels, labels))
  486. origin_img = origin_img.astype(np.float32)
  487. origin_img = 0.5 * origin_img + 0.5 * padded_cropped_img.astype(np.float32)
  488. sample["image"], sample["target"] = origin_img.astype(np.uint8), origin_labels
  489. return sample
  490. class DetectionPaddedRescale(DetectionTransform):
  491. """
  492. Preprocessing transform to be applied last of all transforms for validation.
  493. Image- Rescales and pads to self.input_dim.
  494. Targets- pads targets to max_targets, moves the class label to first index, converts boxes format- xyxy -> cxcywh.
  495. Attributes:
  496. input_dim: (tuple) final input dimension (default=(640,640))
  497. swap: image axis's to be rearranged.
  498. """
  499. def __init__(self, input_dim, swap=(2, 0, 1), max_targets=50, pad_value=114):
  500. self.swap = swap
  501. self.input_dim = input_dim
  502. self.max_targets = max_targets
  503. self.pad_value = pad_value
  504. def __call__(self, sample: Dict[str, np.array]):
  505. img, targets, crowd_targets = sample["image"], sample["target"], sample.get("crowd_target")
  506. img, r = rescale_and_pad_to_size(img, self.input_dim, self.swap, self.pad_value)
  507. sample["image"] = img
  508. sample["target"] = self._rescale_target(targets, r)
  509. if crowd_targets is not None:
  510. sample["crowd_target"] = self._rescale_target(crowd_targets, r)
  511. return sample
  512. def _rescale_target(self, targets: np.array, r: float) -> np.array:
  513. """SegRescale the target according to a coefficient used to rescale the image.
  514. This is done to have images and targets at the same scale.
  515. :param targets: Targets to rescale, shape (batch_size, 6)
  516. :param r: SegRescale coefficient that was applied to the image
  517. :return: Rescaled targets, shape (batch_size, 6)
  518. """
  519. targets = targets.copy() if len(targets) > 0 else np.zeros((self.max_targets, 5), dtype=np.float32)
  520. boxes, labels = targets[:, :4], targets[:, 4]
  521. boxes = xyxy2cxcywh(boxes)
  522. boxes *= r
  523. boxes = cxcywh2xyxy(boxes)
  524. return np.concatenate((boxes, labels[:, np.newaxis]), 1)
  525. class DetectionHorizontalFlip(DetectionTransform):
  526. """
  527. Horizontal Flip for Detection
  528. Attributes:
  529. prob: float: probability of applying horizontal flip
  530. max_targets: int: max objects in single image, padding target to this size in case of empty image.
  531. """
  532. def __init__(self, prob, max_targets: int = 120):
  533. super(DetectionHorizontalFlip, self).__init__()
  534. self.prob = prob
  535. self.max_targets = max_targets
  536. def __call__(self, sample):
  537. image, targets = sample["image"], sample["target"]
  538. boxes = targets[:, :4]
  539. if len(boxes) == 0:
  540. targets = np.zeros((self.max_targets, 5), dtype=np.float32)
  541. boxes = targets[:, :4]
  542. image, boxes = _mirror(image, boxes, self.prob)
  543. targets[:, :4] = boxes
  544. sample["target"] = targets
  545. sample["image"] = image
  546. return sample
  547. class DetectionHSV(DetectionTransform):
  548. """
  549. Detection HSV transform.
  550. Attributes:
  551. prob: (float) probability to apply the transform.
  552. hgain: (float) hue gain (default=0.5)
  553. sgain: (float) saturation gain (default=0.5)
  554. vgain: (float) value gain (default=0.5)
  555. bgr_channels: (tuple) channel indices of the BGR channels- useful for images with >3 channels,
  556. or when BGR channels are in different order. (default=(0,1,2)).
  557. """
  558. def __init__(self, prob: float, hgain: float = 0.5, sgain: float = 0.5, vgain: float = 0.5, bgr_channels=(0, 1, 2)):
  559. super(DetectionHSV, self).__init__()
  560. self.prob = prob
  561. self.hgain = hgain
  562. self.sgain = sgain
  563. self.vgain = vgain
  564. self.bgr_channels = bgr_channels
  565. self._additional_channels_warned = False
  566. def __call__(self, sample: dict) -> dict:
  567. if sample["image"].shape[2] < 3:
  568. raise ValueError("HSV transform expects at least 3 channels, got: " + str(sample["image"].shape[2]))
  569. if sample["image"].shape[2] > 3 and not self._additional_channels_warned:
  570. logger.warning(
  571. "HSV transform received image with "
  572. + str(sample["image"].shape[2])
  573. + " channels. HSV transform will only be applied on channels: "
  574. + str(self.bgr_channels)
  575. + "."
  576. )
  577. self._additional_channels_warned = True
  578. if random.random() < self.prob:
  579. augment_hsv(sample["image"], self.hgain, self.sgain, self.vgain, self.bgr_channels)
  580. return sample
  581. class DetectionTargetsFormatTransform(DetectionTransform):
  582. """
  583. Detection targets format transform
  584. Converts targets in input_format to output_format.
  585. Attributes:
  586. input_format: DetectionTargetsFormat: input target format
  587. output_format: DetectionTargetsFormat: output target format
  588. min_bbox_edge_size: int: bboxes with edge size lower then this values will be removed.
  589. max_targets: int: max objects in single image, padding target to this size.
  590. """
  591. def __init__(
  592. self,
  593. input_format: DetectionTargetsFormat = DetectionTargetsFormat.XYXY_LABEL,
  594. output_format: DetectionTargetsFormat = DetectionTargetsFormat.LABEL_CXCYWH,
  595. min_bbox_edge_size: float = 1,
  596. max_targets: int = 120,
  597. ):
  598. super(DetectionTargetsFormatTransform, self).__init__()
  599. self.input_format = input_format
  600. self.output_format = output_format
  601. self.min_bbox_edge_size = min_bbox_edge_size
  602. self.max_targets = max_targets
  603. def __call__(self, sample):
  604. normalized_input = "NORMALIZED" in self.input_format.value
  605. normalized_output = "NORMALIZED" in self.output_format.value
  606. normalize = not normalized_input and normalized_output
  607. denormalize = normalized_input and not normalized_output
  608. label_first_in_input = self.input_format.value.split("_")[0] == "LABEL"
  609. label_first_in_output = self.output_format.value.split("_")[0] == "LABEL"
  610. input_xyxy_format = "XYXY" in self.input_format.value
  611. output_xyxy_format = "XYXY" in self.output_format.value
  612. convert2xyxy = not input_xyxy_format and output_xyxy_format
  613. convert2cxcy = input_xyxy_format and not output_xyxy_format
  614. image, targets, crowd_targets = sample["image"], sample["target"], sample.get("crowd_target")
  615. _, h, w = image.shape
  616. def _format_target(targets_in):
  617. if label_first_in_input:
  618. labels, boxes = targets_in[:, 0], targets_in[:, 1:]
  619. else:
  620. boxes, labels = targets_in[:, :4], targets_in[:, 4]
  621. if convert2cxcy:
  622. boxes = xyxy2cxcywh(boxes)
  623. elif convert2xyxy:
  624. boxes = cxcywh2xyxy(boxes)
  625. if normalize:
  626. boxes[:, 0] = boxes[:, 0] / w
  627. boxes[:, 1] = boxes[:, 1] / h
  628. boxes[:, 2] = boxes[:, 2] / w
  629. boxes[:, 3] = boxes[:, 3] / h
  630. elif denormalize:
  631. boxes[:, 0] = boxes[:, 0] * w
  632. boxes[:, 1] = boxes[:, 1] * h
  633. boxes[:, 2] = boxes[:, 2] * w
  634. boxes[:, 3] = boxes[:, 3] * h
  635. min_bbox_edge_size = self.min_bbox_edge_size / max(w, h) if normalized_output else self.min_bbox_edge_size
  636. cxcywh_boxes = boxes if not output_xyxy_format else xyxy2cxcywh(boxes.copy())
  637. mask_b = np.minimum(cxcywh_boxes[:, 2], cxcywh_boxes[:, 3]) > min_bbox_edge_size
  638. boxes_t = boxes[mask_b]
  639. labels_t = labels[mask_b]
  640. labels_t = np.expand_dims(labels_t, 1)
  641. targets_t = np.hstack((labels_t, boxes_t)) if label_first_in_output else np.hstack((boxes_t, labels_t))
  642. padded_targets = np.zeros((self.max_targets, 5))
  643. padded_targets[range(len(targets_t))[: self.max_targets]] = targets_t[: self.max_targets]
  644. padded_targets = np.ascontiguousarray(padded_targets, dtype=np.float32)
  645. return padded_targets
  646. sample["target"] = _format_target(targets)
  647. if crowd_targets is not None:
  648. sample["crowd_target"] = _format_target(crowd_targets)
  649. return sample
  650. def get_aug_params(value: Union[tuple, float], center: float = 0):
  651. """
  652. Generates a random value for augmentations as described below
  653. :param value: Union[tuple, float] defines the range of values for generation. Wen tuple-
  654. drawn uniformly between (value[0], value[1]), and (center - value, center + value) when float
  655. :param center: float, defines center to subtract when value is float.
  656. :return: generated value
  657. """
  658. if isinstance(value, float):
  659. return random.uniform(center - value, center + value)
  660. elif len(value) == 2:
  661. return random.uniform(value[0], value[1])
  662. else:
  663. raise ValueError(
  664. "Affine params should be either a sequence containing two values\
  665. or single float values. Got {}".format(
  666. value
  667. )
  668. )
  669. def get_affine_matrix(
  670. target_size,
  671. degrees=10,
  672. translate=0.1,
  673. scales=0.1,
  674. shear=10,
  675. ):
  676. """
  677. Returns a random affine transform matrix.
  678. :param target_size: (tuple) desired output shape.
  679. :param degrees: (Union[tuple, float]) degrees for random rotation, when float the random values are drawn uniformly
  680. from (-degrees, degrees)
  681. :param translate: (Union[tuple, float]) translate size (in pixels) for random translation, when float the random values
  682. are drawn uniformly from (-translate, translate)
  683. :param scales: (Union[tuple, float]) values for random rescale, when float the random values are drawn uniformly
  684. from (0.1-scales, 0.1+scales)
  685. :param shear: (Union[tuple, float]) degrees for random shear, when float the random values are drawn uniformly
  686. from (shear, shear)
  687. :return: affine_transform_matrix, drawn_scale
  688. """
  689. twidth, theight = target_size
  690. # Rotation and Scale
  691. angle = get_aug_params(degrees)
  692. scale = get_aug_params(scales, center=1.0)
  693. if scale <= 0.0:
  694. raise ValueError("Argument scale should be positive")
  695. R = cv2.getRotationMatrix2D(angle=angle, center=(0, 0), scale=scale)
  696. M = np.ones([2, 3])
  697. # Shear
  698. shear_x = math.tan(get_aug_params(shear) * math.pi / 180)
  699. shear_y = math.tan(get_aug_params(shear) * math.pi / 180)
  700. M[0] = R[0] + shear_y * R[1]
  701. M[1] = R[1] + shear_x * R[0]
  702. # Translation
  703. translation_x = get_aug_params(translate) * twidth # x translation (pixels)
  704. translation_y = get_aug_params(translate) * theight # y translation (pixels)
  705. M[0, 2] = translation_x
  706. M[1, 2] = translation_y
  707. return M, scale
  708. def apply_affine_to_bboxes(targets, targets_seg, target_size, M):
  709. num_gts = len(targets)
  710. twidth, theight = target_size
  711. # targets_seg = [B x w x h]
  712. # if any is_not_nan in axis = 1
  713. seg_is_present_mask = np.logical_or.reduce(~np.isnan(targets_seg), axis=1)
  714. num_gts_masks = seg_is_present_mask.sum()
  715. num_gts_boxes = num_gts - num_gts_masks
  716. if num_gts_boxes:
  717. # warp corner points
  718. corner_points = np.ones((num_gts_boxes * 4, 3))
  719. # x1y1, x2y2, x1y2, x2y1
  720. corner_points[:, :2] = targets[~seg_is_present_mask][:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(num_gts_boxes * 4, 2)
  721. corner_points = corner_points @ M.T # apply affine transform
  722. corner_points = corner_points.reshape(num_gts_boxes, 8)
  723. # create new boxes
  724. corner_xs = corner_points[:, 0::2]
  725. corner_ys = corner_points[:, 1::2]
  726. new_bboxes = np.concatenate((np.min(corner_xs, 1), np.min(corner_ys, 1), np.max(corner_xs, 1), np.max(corner_ys, 1))).reshape(4, -1).T
  727. else:
  728. new_bboxes = np.ones((0, 4), dtype=np.float)
  729. if num_gts_masks:
  730. # warp segmentation points
  731. num_seg_points = targets_seg.shape[1] // 2
  732. corner_points_seg = np.ones((num_gts_masks * num_seg_points, 3))
  733. corner_points_seg[:, :2] = targets_seg[seg_is_present_mask].reshape(num_gts_masks * num_seg_points, 2)
  734. corner_points_seg = corner_points_seg @ M.T
  735. corner_points_seg = corner_points_seg.reshape(num_gts_masks, num_seg_points * 2)
  736. # create new boxes
  737. seg_points_xs = corner_points_seg[:, 0::2]
  738. seg_points_ys = corner_points_seg[:, 1::2]
  739. new_tight_bboxes = (
  740. np.concatenate((np.nanmin(seg_points_xs, 1), np.nanmin(seg_points_ys, 1), np.nanmax(seg_points_xs, 1), np.nanmax(seg_points_ys, 1)))
  741. .reshape(4, -1)
  742. .T
  743. )
  744. else:
  745. new_tight_bboxes = np.ones((0, 4), dtype=np.float)
  746. targets[~seg_is_present_mask, :4] = new_bboxes
  747. targets[seg_is_present_mask, :4] = new_tight_bboxes
  748. # clip boxes
  749. targets[:, [0, 2]] = targets[:, [0, 2]].clip(0, twidth)
  750. targets[:, [1, 3]] = targets[:, [1, 3]].clip(0, theight)
  751. return targets
  752. def random_affine(
  753. img: np.ndarray,
  754. targets: np.ndarray = (),
  755. targets_seg: np.ndarray = None,
  756. target_size: tuple = (640, 640),
  757. degrees: Union[float, tuple] = 10,
  758. translate: Union[float, tuple] = 0.1,
  759. scales: Union[float, tuple] = 0.1,
  760. shear: Union[float, tuple] = 10,
  761. filter_box_candidates: bool = False,
  762. wh_thr=2,
  763. ar_thr=20,
  764. area_thr=0.1,
  765. border_value=114,
  766. ):
  767. """
  768. Performs random affine transform to img, targets
  769. :param img: Input image
  770. :param targets: Input target
  771. :param targets_seg: Targets derived from segmentation masks
  772. :param target_size: Desired output shape
  773. :param degrees: Degrees for random rotation, when float the random values are drawn uniformly
  774. from (-degrees, degrees).
  775. :param translate: Translate size (in pixels) for random translation, when float the random values
  776. are drawn uniformly from (-translate, translate)
  777. :param scales: Values for random rescale, when float the random values are drawn uniformly
  778. from (0.1-scales, 0.1+scales)
  779. :param shear: Degrees for random shear, when float the random values are drawn uniformly
  780. from (shear, shear)
  781. :param filter_box_candidates: whether to filter out transformed bboxes by edge size, area ratio, and aspect ratio.
  782. :param wh_thr: (float) edge size threshold when filter_box_candidates = True. Bounding oxes with edges smaller
  783. then this values will be filtered out. (default=2)
  784. :param ar_thr: (float) aspect ratio threshold filter_box_candidates = True. Bounding boxes with aspect ratio larger
  785. then this values will be filtered out. (default=20)
  786. :param area_thr:(float) threshold for area ratio between original image and the transformed one, when when filter_box_candidates = True.
  787. Bounding boxes with such ratio smaller then this value will be filtered out. (default=0.1)
  788. :param border_value: value for filling borders after applying transforms (default=114).
  789. :return: Image and Target with applied random affine
  790. """
  791. targets_seg = np.zeros((targets.shape[0], 0)) if targets_seg is None else targets_seg
  792. M, scale = get_affine_matrix(target_size, degrees, translate, scales, shear)
  793. img = cv2.warpAffine(img, M, dsize=target_size, borderValue=border_value)
  794. # Transform label coordinates
  795. if len(targets) > 0:
  796. targets_orig = targets.copy()
  797. targets = apply_affine_to_bboxes(targets, targets_seg, target_size, M)
  798. if filter_box_candidates:
  799. box_candidates_ids = _filter_box_candidates(targets_orig[:, :4], targets[:, :4], wh_thr=wh_thr, ar_thr=ar_thr, area_thr=area_thr)
  800. targets = targets[box_candidates_ids]
  801. return img, targets
  802. def _filter_box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1):
  803. """
  804. compute candidate boxes
  805. :param box1: before augment
  806. :param box2: after augment
  807. :param wh_thr: wh_thr (pixels)
  808. :param ar_thr: aspect_ratio_thr
  809. :param area_thr: area_ratio
  810. :return:
  811. """
  812. box1 = box1.T
  813. box2 = box2.T
  814. w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
  815. w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
  816. ar = np.maximum(w2 / (h2 + 1e-16), h2 / (w2 + 1e-16)) # aspect ratio
  817. return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + 1e-16) > area_thr) & (ar < ar_thr) # candidates
  818. def _mirror(image, boxes, prob=0.5):
  819. """
  820. Horizontal flips image and bboxes with probability prob.
  821. :param image: (np.array) image to be flipped.
  822. :param boxes: (np.array) bboxes to be modified.
  823. :param prob: probability to perform flipping.
  824. :return: flipped_image, flipped_bboxes
  825. """
  826. flipped_boxes = boxes.copy()
  827. _, width, _ = image.shape
  828. if random.random() < prob:
  829. image = image[:, ::-1]
  830. flipped_boxes[:, 0::2] = width - boxes[:, 2::-2]
  831. return image, flipped_boxes
  832. def augment_hsv(img: np.array, hgain: float, sgain: float, vgain: float, bgr_channels=(0, 1, 2)):
  833. hsv_augs = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] # random gains
  834. hsv_augs *= np.random.randint(0, 2, 3) # random selection of h, s, v
  835. hsv_augs = hsv_augs.astype(np.int16)
  836. img_hsv = cv2.cvtColor(img[..., bgr_channels], cv2.COLOR_BGR2HSV).astype(np.int16)
  837. img_hsv[..., 0] = (img_hsv[..., 0] + hsv_augs[0]) % 180
  838. img_hsv[..., 1] = np.clip(img_hsv[..., 1] + hsv_augs[1], 0, 255)
  839. img_hsv[..., 2] = np.clip(img_hsv[..., 2] + hsv_augs[2], 0, 255)
  840. img[..., bgr_channels] = cv2.cvtColor(img_hsv.astype(img.dtype), cv2.COLOR_HSV2BGR) # no return needed
  841. def rescale_and_pad_to_size(img, input_size, swap=(2, 0, 1), pad_val=114):
  842. """
  843. Rescales image according to minimum ratio between the target height /image height, target width / image width,
  844. and pads the image to the target size.
  845. :param img: Image to be rescaled
  846. :param input_size: Target size
  847. :param swap: Axis's to be rearranged.
  848. :return: rescaled image, ratio
  849. """
  850. if len(img.shape) == 3:
  851. padded_img = np.ones((input_size[0], input_size[1], img.shape[-1]), dtype=np.uint8) * pad_val
  852. else:
  853. padded_img = np.ones(input_size, dtype=np.uint8) * pad_val
  854. r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])
  855. resized_img = cv2.resize(
  856. img,
  857. (int(img.shape[1] * r), int(img.shape[0] * r)),
  858. interpolation=cv2.INTER_LINEAR,
  859. ).astype(np.uint8)
  860. padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
  861. padded_img = padded_img.transpose(swap)
  862. padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
  863. return padded_img, r
  864. class Standardize(torch.nn.Module):
  865. """
  866. Standardize image pixel values.
  867. :return img/max_val
  868. attributes:
  869. max_val: float, value to as described above (default=255)
  870. """
  871. def __init__(self, max_val=255.0):
  872. super(Standardize, self).__init__()
  873. self.max_val = max_val
  874. def forward(self, img):
  875. return img / self.max_val
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...