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

#257 allow using an external Optimizer (not initialized outside)

Merged
Ofri Masad merged 1 commits into Deci-AI:master from deci-ai:feature/SG-184_external_optimizer
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
  1. import collections
  2. import math
  3. import random
  4. from typing import Optional, Union, Tuple, List, Sequence, Dict
  5. from PIL import Image, ImageFilter, ImageOps
  6. from torchvision import transforms as transforms
  7. import numpy as np
  8. import cv2
  9. from super_gradients.common.abstractions.abstract_logger import get_logger
  10. from super_gradients.training.utils.detection_utils import get_mosaic_coordinate, \
  11. 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 ResizeSeg(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 RandomFlip(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. <= prob <= 1., 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 Rescale(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,
  59. scale_factor: Optional[float] = None,
  60. short_size: Optional[int] = None,
  61. long_size: Optional[int] = None):
  62. self.scale_factor = scale_factor
  63. self.short_size = short_size
  64. self.long_size = long_size
  65. self.check_valid_arguments()
  66. def __call__(self, sample: dict):
  67. image = sample["image"]
  68. mask = sample["mask"]
  69. w, h = image.size
  70. if self.scale_factor is not None:
  71. scale = self.scale_factor
  72. elif self.short_size is not None:
  73. short_size = min(w, h)
  74. scale = self.short_size / short_size
  75. else:
  76. long_size = max(w, h)
  77. scale = self.long_size / long_size
  78. out_size = int(scale * w), int(scale * h)
  79. image = image.resize(out_size, image_resample)
  80. mask = mask.resize(out_size, mask_resample)
  81. sample["image"] = image
  82. sample["mask"] = mask
  83. return sample
  84. def check_valid_arguments(self):
  85. if self.scale_factor is None and self.short_size is None and self.long_size is None:
  86. raise ValueError("Must assign one rescale argument: scale_factor, short_size or long_size")
  87. if self.scale_factor is not None and self.scale_factor <= 0:
  88. raise ValueError(f"Scale factor must be a positive number, found: {self.scale_factor}")
  89. if self.short_size is not None and self.short_size <= 0:
  90. raise ValueError(f"Short size must be a positive number, found: {self.short_size}")
  91. if self.long_size is not None and self.long_size <= 0:
  92. raise ValueError(f"Long size must be a positive number, found: {self.long_size}")
  93. class RandomRescale:
  94. """
  95. Random rescale the image and mask (synchronously) while preserving aspect ratio.
  96. Scale factor is randomly picked between scales [min, max]
  97. Args:
  98. scales: scale range tuple (min, max), if scales is a float range will be defined as (1, scales) if scales > 1,
  99. otherwise (scales, 1). must be a positive number.
  100. """
  101. def __init__(self, scales: Union[float, Tuple, List] = (0.5, 2.0)):
  102. self.scales = scales
  103. self.check_valid_arguments()
  104. def __call__(self, sample: dict):
  105. image = sample["image"]
  106. mask = sample["mask"]
  107. w, h = image.size
  108. scale = random.uniform(self.scales[0], self.scales[1])
  109. out_size = int(scale * w), int(scale * h)
  110. image = image.resize(out_size, image_resample)
  111. mask = mask.resize(out_size, mask_resample)
  112. sample["image"] = image
  113. sample["mask"] = mask
  114. return sample
  115. def check_valid_arguments(self):
  116. """
  117. Check the scale values are valid. if order is wrong, flip the order and return the right scale values.
  118. """
  119. if not isinstance(self.scales, collections.abc.Iterable):
  120. if self.scales <= 1:
  121. self.scales = (self.scales, 1)
  122. else:
  123. self.scales = (1, self.scales)
  124. if self.scales[0] < 0 or self.scales[1] < 0:
  125. raise ValueError(f"RandomRescale scale values must be positive numbers, found: {self.scales}")
  126. if self.scales[0] > self.scales[1]:
  127. self.scales = (self.scales[1], self.scales[0])
  128. return self.scales
  129. class RandomRotate(SegmentationTransform):
  130. """
  131. Randomly rotates image and mask (synchronously) between 'min_deg' and 'max_deg'.
  132. """
  133. def __init__(self, min_deg: float = -10, max_deg: float = 10, fill_mask: int = 0,
  134. fill_image: Union[int, Tuple, List] = 0):
  135. self.min_deg = min_deg
  136. self.max_deg = max_deg
  137. self.fill_mask = fill_mask
  138. # grey color in RGB mode
  139. self.fill_image = (fill_image, fill_image, fill_image)
  140. self.check_valid_arguments()
  141. def __call__(self, sample: dict):
  142. image = sample["image"]
  143. mask = sample["mask"]
  144. deg = random.uniform(self.min_deg, self.max_deg)
  145. image = image.rotate(deg, resample=image_resample, fillcolor=self.fill_image)
  146. mask = mask.rotate(deg, resample=mask_resample, fillcolor=self.fill_mask)
  147. sample["image"] = image
  148. sample["mask"] = mask
  149. return sample
  150. def check_valid_arguments(self):
  151. self.fill_mask, self.fill_image = _validate_fill_values_arguments(self.fill_mask, self.fill_image)
  152. class CropImageAndMask(SegmentationTransform):
  153. """
  154. Crops image and mask (synchronously).
  155. In "center" mode a center crop is performed while, in "random" mode the drop will be positioned around
  156. random coordinates.
  157. """
  158. def __init__(self, crop_size: Union[float, Tuple, List], mode: str):
  159. """
  160. :param crop_size: tuple of (width, height) for the final crop size, if is scalar size is a
  161. square (crop_size, crop_size)
  162. :param mode: how to choose the center of the crop, 'center' for the center of the input image,
  163. 'random' center the point is chosen randomally
  164. """
  165. self.crop_size = crop_size
  166. self.mode = mode
  167. self.check_valid_arguments()
  168. def __call__(self, sample: dict):
  169. image = sample["image"]
  170. mask = sample["mask"]
  171. w, h = image.size
  172. if self.mode == "random":
  173. x1 = random.randint(0, w - self.crop_size[0])
  174. y1 = random.randint(0, h - self.crop_size[1])
  175. else:
  176. x1 = int(round((w - self.crop_size[0]) / 2.))
  177. y1 = int(round((h - self.crop_size[1]) / 2.))
  178. image = image.crop((x1, y1, x1 + self.crop_size[0], y1 + self.crop_size[1]))
  179. mask = mask.crop((x1, y1, x1 + self.crop_size[0], y1 + self.crop_size[1]))
  180. sample["image"] = image
  181. sample["mask"] = mask
  182. return sample
  183. def check_valid_arguments(self):
  184. if self.mode not in ["center", "random"]:
  185. raise ValueError(f"Unsupported mode: found: {self.mode}, expected: 'center' or 'random'")
  186. if not isinstance(self.crop_size, collections.abc.Iterable):
  187. self.crop_size = (self.crop_size, self.crop_size)
  188. if self.crop_size[0] <= 0 or self.crop_size[1] <= 0:
  189. raise ValueError(f"Crop size must be positive numbers, found: {self.crop_size}")
  190. class RandomGaussianBlur(SegmentationTransform):
  191. """
  192. Adds random Gaussian Blur to image with probability 'prob'.
  193. """
  194. def __init__(self, prob: float = 0.5):
  195. assert 0. <= prob <= 1., "Probability value must be between 0 and 1"
  196. self.prob = prob
  197. def __call__(self, sample: dict):
  198. image = sample["image"]
  199. mask = sample["mask"]
  200. if random.random() < self.prob:
  201. image = image.filter(ImageFilter.GaussianBlur(
  202. radius=random.random()))
  203. sample["image"] = image
  204. sample["mask"] = mask
  205. return sample
  206. class PadShortToCropSize(SegmentationTransform):
  207. """
  208. Pads image to 'crop_size'.
  209. Should be called only after "Rescale" or "RandomRescale" in augmentations pipeline.
  210. """
  211. def __init__(self, crop_size: Union[float, Tuple, List], fill_mask: int = 0,
  212. fill_image: Union[int, Tuple, List] = 0):
  213. """
  214. :param crop_size: tuple of (width, height) for the final crop size, if is scalar size is a
  215. square (crop_size, crop_size)
  216. :param fill_mask: value to fill mask labels background.
  217. :param fill_image: grey value to fill image padded background.
  218. """
  219. # CHECK IF CROP SIZE IS A ITERABLE OR SCALAR
  220. self.crop_size = crop_size
  221. self.fill_mask = fill_mask
  222. self.fill_image = tuple(fill_image) if isinstance(fill_image, Sequence) else fill_image
  223. self.check_valid_arguments()
  224. def __call__(self, sample: dict):
  225. image = sample["image"]
  226. mask = sample["mask"]
  227. w, h = image.size
  228. # pad images from center symmetrically
  229. if w < self.crop_size[0] or h < self.crop_size[1]:
  230. padh = (self.crop_size[1] - h) / 2 if h < self.crop_size[1] else 0
  231. pad_top, pad_bottom = math.ceil(padh), math.floor(padh)
  232. padw = (self.crop_size[0] - w) / 2 if w < self.crop_size[0] else 0
  233. pad_left, pad_right = math.ceil(padw), math.floor(padw)
  234. image = ImageOps.expand(image, border=(pad_left, pad_top, pad_right, pad_bottom), fill=self.fill_image)
  235. mask = ImageOps.expand(mask, border=(pad_left, pad_top, pad_right, pad_bottom), fill=self.fill_mask)
  236. sample["image"] = image
  237. sample["mask"] = mask
  238. return sample
  239. def check_valid_arguments(self):
  240. if not isinstance(self.crop_size, collections.abc.Iterable):
  241. self.crop_size = (self.crop_size, self.crop_size)
  242. if self.crop_size[0] <= 0 or self.crop_size[1] <= 0:
  243. raise ValueError(f"Crop size must be positive numbers, found: {self.crop_size}")
  244. self.fill_mask, self.fill_image = _validate_fill_values_arguments(self.fill_mask, self.fill_image)
  245. class ColorJitterSeg(transforms.ColorJitter):
  246. def __call__(self, sample):
  247. sample["image"] = super(ColorJitterSeg, self).__call__(sample["image"])
  248. return sample
  249. def _validate_fill_values_arguments(fill_mask: int, fill_image: Union[int, Tuple, List]):
  250. if not isinstance(fill_image, collections.abc.Iterable):
  251. # If fill_image is single value, turn to grey color in RGB mode.
  252. fill_image = (fill_image, fill_image, fill_image)
  253. elif len(fill_image) != 3:
  254. raise ValueError(f"fill_image must be an RGB tuple of size equal to 3, found: {fill_image}")
  255. # assert values are integers
  256. if not isinstance(fill_mask, int) or not all(isinstance(x, int) for x in fill_image):
  257. raise ValueError(f"Fill value must be integers,"
  258. f" found: fill_image = {fill_image}, fill_mask = {fill_mask}")
  259. # assert values in range 0-255
  260. if min(fill_image) < 0 or max(fill_image) > 255 or fill_mask < 0 or fill_mask > 255:
  261. raise ValueError(f"Fill value must be a value from 0 to 255,"
  262. f" found: fill_image = {fill_image}, fill_mask = {fill_mask}")
  263. return fill_mask, fill_image
  264. class DetectionTransform:
  265. """
  266. Detection transform base class.
  267. Complex transforms that require extra data loading can use the the additional_samples_count attribute in a
  268. similar fashion to what's been done in COCODetectionDatasetV2:
  269. self._load_additional_inputs_for_transform(sample, transform)
  270. # after the above call, sample["additional_samples"] holds a list of additional inputs and targets.
  271. sample = transform(sample)
  272. Attributes:
  273. additional_samples_count: (int) additional samples to be loaded.
  274. non_empty_targets: (bool) whether the additianl targets can have empty targets or not.
  275. """
  276. def __init__(self, additional_samples_count: int = 0, non_empty_targets: bool = False):
  277. self.additional_samples_count = additional_samples_count
  278. self.non_empty_targets = non_empty_targets
  279. def __call__(self, sample: Union[dict, list]):
  280. raise NotImplementedError
  281. def __repr__(self):
  282. return self.__class__.__name__ + str(self.__dict__).replace('{', '(').replace('}', ')')
  283. class DetectionMosaic(DetectionTransform):
  284. """
  285. DetectionMosaic detection transform
  286. Attributes:
  287. input_dim: (tuple) input dimension.
  288. prob: (float) probability of applying mosaic.
  289. enable_mosaic: (bool) whether to apply mosaic at all (regardless of prob) (default=True).
  290. """
  291. def __init__(self, input_dim: tuple, prob: float = 1., enable_mosaic: bool = True):
  292. super(DetectionMosaic, self).__init__(additional_samples_count=3)
  293. self.prob = prob
  294. self.input_dim = input_dim
  295. self.enable_mosaic = enable_mosaic
  296. def close(self):
  297. self.additional_samples_count = 0
  298. self.enable_mosaic = False
  299. def __call__(self, sample: Union[dict, list]):
  300. if self.enable_mosaic and random.random() < self.prob:
  301. mosaic_labels = []
  302. mosaic_labels_seg = []
  303. input_h, input_w = self.input_dim[0], self.input_dim[1]
  304. # yc, xc = s, s # mosaic center x, y
  305. yc = int(random.uniform(0.5 * input_h, 1.5 * input_h))
  306. xc = int(random.uniform(0.5 * input_w, 1.5 * input_w))
  307. # 3 additional samples, total of 4
  308. all_samples = [sample] + sample["additional_samples"]
  309. for i_mosaic, mosaic_sample in enumerate(all_samples):
  310. img, _labels, _labels_seg, _ = mosaic_sample["image"], mosaic_sample["target"], mosaic_sample[
  311. "target_seg"], mosaic_sample["id"]
  312. h0, w0 = img.shape[:2] # orig hw
  313. scale = min(1. * input_h / h0, 1. * input_w / w0)
  314. img = cv2.resize(
  315. img, (int(w0 * scale), int(h0 * scale)), interpolation=cv2.INTER_LINEAR
  316. )
  317. # generate output mosaic image
  318. (h, w, c) = img.shape[:3]
  319. if i_mosaic == 0:
  320. mosaic_img = np.full((input_h * 2, input_w * 2, c), 114, dtype=np.uint8)
  321. # suffix l means large image, while s means small image in mosaic aug.
  322. (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,
  323. input_h, input_w)
  324. mosaic_img[l_y1:l_y2, l_x1:l_x2] = img[s_y1:s_y2, s_x1:s_x2]
  325. padw, padh = l_x1 - s_x1, l_y1 - s_y1
  326. labels = _labels.copy()
  327. labels_seg = _labels_seg.copy()
  328. # Normalized xywh to pixel xyxy format
  329. if _labels.size > 0:
  330. labels[:, 0] = scale * _labels[:, 0] + padw
  331. labels[:, 1] = scale * _labels[:, 1] + padh
  332. labels[:, 2] = scale * _labels[:, 2] + padw
  333. labels[:, 3] = scale * _labels[:, 3] + padh
  334. labels_seg[:, ::2] = scale * labels_seg[:, ::2] + padw
  335. labels_seg[:, 1::2] = scale * labels_seg[:, 1::2] + padh
  336. mosaic_labels_seg.append(labels_seg)
  337. mosaic_labels.append(labels)
  338. if len(mosaic_labels):
  339. mosaic_labels = np.concatenate(mosaic_labels, 0)
  340. np.clip(mosaic_labels[:, 0], 0, 2 * input_w, out=mosaic_labels[:, 0])
  341. np.clip(mosaic_labels[:, 1], 0, 2 * input_h, out=mosaic_labels[:, 1])
  342. np.clip(mosaic_labels[:, 2], 0, 2 * input_w, out=mosaic_labels[:, 2])
  343. np.clip(mosaic_labels[:, 3], 0, 2 * input_h, out=mosaic_labels[:, 3])
  344. mosaic_labels_seg = np.concatenate(mosaic_labels_seg, 0)
  345. np.clip(mosaic_labels_seg[:, ::2], 0, 2 * input_w, out=mosaic_labels_seg[:, ::2])
  346. np.clip(mosaic_labels_seg[:, 1::2], 0, 2 * input_h, out=mosaic_labels_seg[:, 1::2])
  347. sample = {"image": mosaic_img, "target": mosaic_labels, "target_seg": mosaic_labels_seg,
  348. "info": (mosaic_img.shape[1], mosaic_img.shape[0]), "id": sample["id"]}
  349. return sample
  350. class DetectionRandomAffine(DetectionTransform):
  351. """
  352. DetectionRandomAffine detection transform
  353. Attributes:
  354. target_size: (tuple) desired output shape.
  355. degrees: (Union[tuple, float]) degrees for random rotation, when float the random values are drawn uniformly
  356. from (-degrees, degrees)
  357. translate: (Union[tuple, float]) translate size (in pixels) for random translation, when float the random values
  358. are drawn uniformly from (-translate, translate)
  359. scales: (Union[tuple, float]) values for random rescale, when float the random values are drawn uniformly
  360. from (0.1-scales, 0.1+scales)
  361. shear: (Union[tuple, float]) degrees for random shear, when float the random values are drawn uniformly
  362. from (shear, shear)
  363. enable: (bool) whether to apply the below transform at all.
  364. """
  365. def __init__(self, degrees=10, translate=0.1, scales=0.1, shear=10, target_size=(640, 640)):
  366. super(DetectionRandomAffine, self).__init__()
  367. self.degrees = degrees
  368. self.translate = translate
  369. self.scale = scales
  370. self.shear = shear
  371. self.target_size = target_size
  372. self.enable = True
  373. def close(self):
  374. self.enable = False
  375. def __call__(self, sample: dict):
  376. if self.enable:
  377. img, target = random_affine(
  378. sample["image"],
  379. sample["target"],
  380. sample["target_seg"],
  381. target_size=self.target_size,
  382. degrees=self.degrees,
  383. translate=self.translate,
  384. scales=self.scale,
  385. shear=self.shear,
  386. )
  387. sample["image"] = img
  388. sample["target"] = target
  389. return sample
  390. class DetectionMixup(DetectionTransform):
  391. """
  392. Mixup detection transform
  393. Attributes:
  394. input_dim: (tuple) input dimension.
  395. mixup_scale: (tuple) scale range for the additional loaded image for mixup.
  396. prob: (float) probability of applying mixup.
  397. enable_mixup: (bool) whether to apply mixup at all (regardless of prob) (default=True).
  398. """
  399. def __init__(self, input_dim, mixup_scale, prob=1., enable_mixup=True):
  400. super(DetectionMixup, self).__init__(additional_samples_count=1, non_empty_targets=True)
  401. self.input_dim = input_dim
  402. self.mixup_scale = mixup_scale
  403. self.prob = prob
  404. self.enable_mixup = enable_mixup
  405. def close(self):
  406. self.additional_samples_count = 0
  407. self.enable_mixup = False
  408. def __call__(self, sample: dict):
  409. if self.enable_mixup and random.random() < self.prob:
  410. origin_img, origin_labels = sample["image"], sample["target"]
  411. cp_sample = sample["additional_samples"][0]
  412. img, cp_labels = cp_sample["image"], cp_sample["target"]
  413. img, cp_labels = _mirror(img, cp_labels, 0.5)
  414. jit_factor = random.uniform(*self.mixup_scale)
  415. if len(img.shape) == 3:
  416. cp_img = np.ones((self.input_dim[0], self.input_dim[1], 3), dtype=np.uint8) * 114
  417. else:
  418. cp_img = np.ones(self.input_dim, dtype=np.uint8) * 114
  419. cp_scale_ratio = min(self.input_dim[0] / img.shape[0], self.input_dim[1] / img.shape[1])
  420. resized_img = cv2.resize(
  421. img,
  422. (int(img.shape[1] * cp_scale_ratio), int(img.shape[0] * cp_scale_ratio)),
  423. interpolation=cv2.INTER_LINEAR,
  424. )
  425. cp_img[: int(img.shape[0] * cp_scale_ratio), : int(img.shape[1] * cp_scale_ratio)] = resized_img
  426. cp_img = cv2.resize(
  427. cp_img,
  428. (int(cp_img.shape[1] * jit_factor), int(cp_img.shape[0] * jit_factor)),
  429. )
  430. cp_scale_ratio *= jit_factor
  431. origin_h, origin_w = cp_img.shape[:2]
  432. target_h, target_w = origin_img.shape[:2]
  433. padded_img = np.zeros(
  434. (max(origin_h, target_h), max(origin_w, target_w), 3), dtype=np.uint8
  435. )
  436. padded_img[:origin_h, :origin_w] = cp_img
  437. x_offset, y_offset = 0, 0
  438. if padded_img.shape[0] > target_h:
  439. y_offset = random.randint(0, padded_img.shape[0] - target_h - 1)
  440. if padded_img.shape[1] > target_w:
  441. x_offset = random.randint(0, padded_img.shape[1] - target_w - 1)
  442. padded_cropped_img = padded_img[y_offset: y_offset + target_h, x_offset: x_offset + target_w]
  443. cp_bboxes_origin_np = adjust_box_anns(
  444. cp_labels[:, :4].copy(), cp_scale_ratio, 0, 0, origin_w, origin_h
  445. )
  446. cp_bboxes_transformed_np = cp_bboxes_origin_np.copy()
  447. cp_bboxes_transformed_np[:, 0::2] = np.clip(
  448. cp_bboxes_transformed_np[:, 0::2] - x_offset, 0, target_w
  449. )
  450. cp_bboxes_transformed_np[:, 1::2] = np.clip(
  451. cp_bboxes_transformed_np[:, 1::2] - y_offset, 0, target_h
  452. )
  453. cls_labels = cp_labels[:, 4:5].copy()
  454. box_labels = cp_bboxes_transformed_np
  455. labels = np.hstack((box_labels, cls_labels))
  456. origin_labels = np.vstack((origin_labels, labels))
  457. origin_img = origin_img.astype(np.float32)
  458. origin_img = 0.5 * origin_img + 0.5 * padded_cropped_img.astype(np.float32)
  459. sample["image"], sample["target"] = origin_img.astype(np.uint8), origin_labels
  460. return sample
  461. class DetectionPaddedRescale(DetectionTransform):
  462. """
  463. Preprocessing transform to be applied last of all transforms for validation.
  464. Image- Rescales and pads to self.input_dim.
  465. Targets- pads targets to max_targets, moves the class label to first index, converts boxes format- xyxy -> cxcywh.
  466. Attributes:
  467. input_dim: (tuple) final input dimension (default=(640,640))
  468. swap: image axis's to be rearranged.
  469. """
  470. def __init__(self, input_dim, swap=(2, 0, 1), max_targets=50):
  471. self.swap = swap
  472. self.input_dim = input_dim
  473. self.max_targets = max_targets
  474. def __call__(self, sample: Dict[str, np.array]):
  475. img, targets, crowd_targets = sample["image"], sample["target"], sample.get("crowd_target", [])
  476. new_targets = np.zeros((self.max_targets, 5), dtype=np.float32) if len(targets) == 0 else targets.copy()
  477. new_crowd_targets = np.zeros((self.max_targets, 5), dtype=np.float32) if len(crowd_targets) == 0 else crowd_targets.copy()
  478. img, r = rescale_and_pad_to_size(img, self.input_dim, self.swap)
  479. sample["image"] = img
  480. sample["target"] = self._rescale_target(new_targets, r)
  481. if crowd_targets is not None:
  482. sample["crowd_target"] = self._rescale_target(new_crowd_targets, r)
  483. return sample
  484. def _rescale_target(self, targets: np.array, r: float) -> np.array:
  485. """Rescale the target according to a coefficient used to rescale the image.
  486. This is done to have images and targets at the same scale.
  487. :param targets: Targets to rescale, shape (batch_size, 6)
  488. :param r: Rescale coefficient that was applied to the image
  489. :return: Rescaled targets, shape (batch_size, 6)
  490. """
  491. boxes, labels = targets[:, :4], targets[:, 4]
  492. boxes = xyxy2cxcywh(boxes)
  493. boxes *= r
  494. boxes = cxcywh2xyxy(boxes)
  495. return np.concatenate((boxes, labels[:, np.newaxis]), 1)
  496. class DetectionHorizontalFlip(DetectionTransform):
  497. """
  498. Horizontal Flip for Detection
  499. Attributes:
  500. prob: float: probability of applying HSV transform
  501. max_targets: int: max objects in single image, padding target to this size in case of empty image.
  502. """
  503. def __init__(self, prob, max_targets: int = 120):
  504. super(DetectionHorizontalFlip, self).__init__()
  505. self.prob = prob
  506. self.max_targets = max_targets
  507. def __call__(self, sample):
  508. image, targets = sample["image"], sample["target"]
  509. boxes = targets[:, :4]
  510. if len(boxes) == 0:
  511. targets = np.zeros((self.max_targets, 5), dtype=np.float32)
  512. boxes = targets[:, :4]
  513. image, boxes = _mirror(image, boxes, self.prob)
  514. sample["image"] = image
  515. return sample
  516. class DetectionHSV(DetectionTransform):
  517. """
  518. Detection HSV transform.
  519. """
  520. def __init__(self, prob):
  521. super(DetectionHSV, self).__init__()
  522. self.prob = prob
  523. def __call__(self, sample):
  524. if random.random() < self.prob:
  525. augment_hsv(sample["image"])
  526. return sample
  527. class DetectionTargetsFormatTransform(DetectionTransform):
  528. """
  529. Detection targets format transform
  530. Converts targets in input_format to output_format.
  531. Attributes:
  532. input_format: DetectionTargetsFormat: input target format
  533. output_format: DetectionTargetsFormat: output target format
  534. min_bbox_edge_size: int: bboxes with edge size lower then this values will be removed.
  535. max_targets: int: max objects in single image, padding target to this size.
  536. """
  537. def __init__(self, input_format: DetectionTargetsFormat = DetectionTargetsFormat.XYXY_LABEL,
  538. output_format: DetectionTargetsFormat = DetectionTargetsFormat.LABEL_CXCYWH,
  539. min_bbox_edge_size: float = 1, max_targets: int = 120):
  540. super(DetectionTargetsFormatTransform, self).__init__()
  541. self.input_format = input_format
  542. self.output_format = output_format
  543. self.min_bbox_edge_size = min_bbox_edge_size
  544. self.max_targets = max_targets
  545. def __call__(self, sample):
  546. normalized_input = "NORMALIZED" in self.input_format.value
  547. normalized_output = "NORMALIZED" in self.output_format.value
  548. normalize = not normalized_input and normalized_output
  549. denormalize = normalized_input and not normalized_output
  550. label_first_in_input = self.input_format.value.split("_")[0] == "LABEL"
  551. label_first_in_output = self.output_format.value.split("_")[0] == "LABEL"
  552. input_xyxy_format = "XYXY" in self.input_format.value
  553. output_xyxy_format = "XYXY" in self.output_format.value
  554. convert2xyxy = not input_xyxy_format and output_xyxy_format
  555. convert2cxcy = input_xyxy_format and not output_xyxy_format
  556. image, targets, crowd_targets = sample["image"], sample["target"], sample.get("crowd_target", [])
  557. _, h, w = image.shape
  558. def _format_target(targets_in):
  559. if label_first_in_input:
  560. labels, boxes = targets_in[:, 0], targets_in[:, 1:]
  561. else:
  562. boxes, labels = targets_in[:, :4], targets_in[:, 4]
  563. if convert2cxcy:
  564. boxes = xyxy2cxcywh(boxes)
  565. elif convert2xyxy:
  566. boxes = cxcywh2xyxy(boxes)
  567. if normalize:
  568. boxes[:, 0] = boxes[:, 0] / w
  569. boxes[:, 1] = boxes[:, 1] / h
  570. boxes[:, 2] = boxes[:, 2] / w
  571. boxes[:, 3] = boxes[:, 3] / h
  572. elif denormalize:
  573. boxes[:, 0] = boxes[:, 0] * w
  574. boxes[:, 1] = boxes[:, 1] * h
  575. boxes[:, 2] = boxes[:, 2] * w
  576. boxes[:, 3] = boxes[:, 3] * h
  577. min_bbox_edge_size = self.min_bbox_edge_size / max(w, h) if normalized_output else self.min_bbox_edge_size
  578. cxcywh_boxes = boxes if not output_xyxy_format else xyxy2cxcywh(boxes.copy())
  579. mask_b = np.minimum(cxcywh_boxes[:, 2], cxcywh_boxes[:, 3]) > min_bbox_edge_size
  580. boxes_t = boxes[mask_b]
  581. labels_t = labels[mask_b]
  582. labels_t = np.expand_dims(labels_t, 1)
  583. targets_t = np.hstack((labels_t, boxes_t)) if label_first_in_output else np.hstack((boxes_t, labels_t))
  584. padded_targets = np.zeros((self.max_targets, 5))
  585. padded_targets[range(len(targets_t))[: self.max_targets]] = targets_t[: self.max_targets]
  586. padded_targets = np.ascontiguousarray(padded_targets, dtype=np.float32)
  587. return padded_targets
  588. sample["target"] = _format_target(targets)
  589. if crowd_targets != []:
  590. sample["crowd_target"] = _format_target(crowd_targets)
  591. return sample
  592. def get_aug_params(value: Union[tuple, float], center: float = 0):
  593. """
  594. Generates a random value for augmentations as described below
  595. :param value: Union[tuple, float] defines the range of values for generation. Wen tuple-
  596. drawn uniformly between (value[0], value[1]), and (center - value, center + value) when float
  597. :param center: float, defines center to subtract when value is float.
  598. :return: generated value
  599. """
  600. if isinstance(value, float):
  601. return random.uniform(center - value, center + value)
  602. elif len(value) == 2:
  603. return random.uniform(value[0], value[1])
  604. else:
  605. raise ValueError(
  606. "Affine params should be either a sequence containing two values\
  607. or single float values. Got {}".format(
  608. value
  609. )
  610. )
  611. def get_affine_matrix(
  612. target_size,
  613. degrees=10,
  614. translate=0.1,
  615. scales=0.1,
  616. shear=10,
  617. ):
  618. """
  619. Returns a random affine transform matrix.
  620. :param target_size: (tuple) desired output shape.
  621. :param degrees: (Union[tuple, float]) degrees for random rotation, when float the random values are drawn uniformly
  622. from (-degrees, degrees)
  623. :param translate: (Union[tuple, float]) translate size (in pixels) for random translation, when float the random values
  624. are drawn uniformly from (-translate, translate)
  625. :param scales: (Union[tuple, float]) values for random rescale, when float the random values are drawn uniformly
  626. from (0.1-scales, 0.1+scales)
  627. :param shear: (Union[tuple, float]) degrees for random shear, when float the random values are drawn uniformly
  628. from (shear, shear)
  629. :return: affine_transform_matrix, drawn_scale
  630. """
  631. twidth, theight = target_size
  632. # Rotation and Scale
  633. angle = get_aug_params(degrees)
  634. scale = get_aug_params(scales, center=1.0)
  635. if scale <= 0.0:
  636. raise ValueError("Argument scale should be positive")
  637. R = cv2.getRotationMatrix2D(angle=angle, center=(0, 0), scale=scale)
  638. M = np.ones([2, 3])
  639. # Shear
  640. shear_x = math.tan(get_aug_params(shear) * math.pi / 180)
  641. shear_y = math.tan(get_aug_params(shear) * math.pi / 180)
  642. M[0] = R[0] + shear_y * R[1]
  643. M[1] = R[1] + shear_x * R[0]
  644. # Translation
  645. translation_x = get_aug_params(translate) * twidth # x translation (pixels)
  646. translation_y = get_aug_params(translate) * theight # y translation (pixels)
  647. M[0, 2] = translation_x
  648. M[1, 2] = translation_y
  649. return M, scale
  650. def apply_affine_to_bboxes(targets, targets_seg, target_size, M):
  651. num_gts = len(targets)
  652. twidth, theight = target_size
  653. seg_is_present_mask = np.logical_or.reduce(~np.isnan(targets_seg), axis=1)
  654. num_gts_masks = seg_is_present_mask.sum()
  655. num_gts_boxes = num_gts - num_gts_masks
  656. if num_gts_boxes:
  657. # warp corner points
  658. corner_points = np.ones((num_gts_boxes * 4, 3))
  659. # x1y1, x2y2, x1y2, x2y1
  660. corner_points[:, :2] = targets[~seg_is_present_mask][:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(num_gts_boxes * 4, 2)
  661. corner_points = corner_points @ M.T # apply affine transform
  662. corner_points = corner_points.reshape(num_gts_boxes, 8)
  663. # create new boxes
  664. corner_xs = corner_points[:, 0::2]
  665. corner_ys = corner_points[:, 1::2]
  666. new_bboxes = (np.concatenate(
  667. (np.min(corner_xs, 1), np.min(corner_ys, 1),
  668. np.max(corner_xs, 1), np.max(corner_ys, 1))
  669. ).reshape(4, -1).T)
  670. else:
  671. new_bboxes = np.ones((0, 4), dtype=np.float)
  672. if num_gts_masks:
  673. # warp segmentation points
  674. num_seg_points = targets_seg.shape[1] // 2
  675. corner_points_seg = np.ones((num_gts_masks * num_seg_points, 3))
  676. corner_points_seg[:, :2] = targets_seg[seg_is_present_mask].reshape(num_gts_masks * num_seg_points, 2)
  677. corner_points_seg = corner_points_seg @ M.T
  678. corner_points_seg = corner_points_seg.reshape(num_gts_masks, num_seg_points * 2)
  679. # create new boxes
  680. seg_points_xs = corner_points_seg[:, 0::2]
  681. seg_points_ys = corner_points_seg[:, 1::2]
  682. new_tight_bboxes = (np.concatenate(
  683. (np.nanmin(seg_points_xs, 1), np.nanmin(seg_points_ys, 1),
  684. np.nanmax(seg_points_xs, 1), np.nanmax(seg_points_ys, 1))
  685. ).reshape(4, -1).T)
  686. else:
  687. new_tight_bboxes = np.ones((0, 4), dtype=np.float)
  688. targets[~seg_is_present_mask, :4] = new_bboxes
  689. targets[seg_is_present_mask, :4] = new_tight_bboxes
  690. # clip boxes
  691. targets[:, [0, 2]] = targets[:, [0, 2]].clip(0, twidth)
  692. targets[:, [1, 3]] = targets[:, [1, 3]].clip(0, theight)
  693. return targets
  694. def random_affine(
  695. img,
  696. targets=(),
  697. targets_seg=(),
  698. target_size=(640, 640),
  699. degrees=10,
  700. translate=0.1,
  701. scales=0.1,
  702. shear=10,
  703. ):
  704. """
  705. Performs random affine transform to img, targets
  706. :param img: (array) input image.
  707. :param targets: (array) input target.
  708. :param targets_seg: (array) targets derived from segmentation masks.
  709. :param target_size: (tuple) desired output shape.
  710. :param degrees: (Union[tuple, float]) degrees for random rotation, when float the random values are drawn uniformly
  711. from (-degrees, degrees)
  712. :param translate: (Union[tuple, float]) translate size (in pixels) for random translation, when float the random values
  713. are drawn uniformly from (-translate, translate)
  714. :param scales: (Union[tuple, float]) values for random rescale, when float the random values are drawn uniformly
  715. from (0.1-scales, 0.1+scales)
  716. :param shear: (Union[tuple, float]) degrees for random shear, when float the random values are drawn uniformly
  717. from (shear, shear)
  718. :return:
  719. """
  720. M, scale = get_affine_matrix(target_size, degrees, translate, scales, shear)
  721. img = cv2.warpAffine(img, M, dsize=target_size, borderValue=(114, 114, 114))
  722. # Transform label coordinates
  723. if len(targets) > 0:
  724. targets = apply_affine_to_bboxes(targets, targets_seg, target_size, M)
  725. return img, targets
  726. def _mirror(image, boxes, prob=0.5):
  727. """
  728. Horizontal flips image and bboxes with probability prob.
  729. :param image: (np.array) image to be flipped.
  730. :param boxes: (np.array) bboxes to be modified.
  731. :param prob: probability to perform flipping.
  732. :return: flipped_image, flipped_bboxes
  733. """
  734. _, width, _ = image.shape
  735. if random.random() < prob:
  736. image = image[:, ::-1]
  737. boxes[:, 0::2] = width - boxes[:, 2::-2]
  738. return image, boxes
  739. def augment_hsv(img, hgain=5, sgain=30, vgain=30):
  740. hsv_augs = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] # random gains
  741. hsv_augs *= np.random.randint(0, 2, 3) # random selection of h, s, v
  742. hsv_augs = hsv_augs.astype(np.int16)
  743. img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype(np.int16)
  744. img_hsv[..., 0] = (img_hsv[..., 0] + hsv_augs[0]) % 180
  745. img_hsv[..., 1] = np.clip(img_hsv[..., 1] + hsv_augs[1], 0, 255)
  746. img_hsv[..., 2] = np.clip(img_hsv[..., 2] + hsv_augs[2], 0, 255)
  747. cv2.cvtColor(img_hsv.astype(img.dtype), cv2.COLOR_HSV2BGR, dst=img) # no return needed
  748. def rescale_and_pad_to_size(img, input_size, swap=(2, 0, 1), pad_val=114):
  749. """
  750. Rescales image according to minimum ratio between the target height /image height, target width / image width,
  751. and pads the image to the target size.
  752. :param img: Image to be rescaled
  753. :param input_size: Target size
  754. :param swap: Axis's to be rearranged.
  755. :return: rescaled image, ratio
  756. """
  757. if len(img.shape) == 3:
  758. padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * pad_val
  759. else:
  760. padded_img = np.ones(input_size, dtype=np.uint8) * pad_val
  761. r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])
  762. resized_img = cv2.resize(
  763. img,
  764. (int(img.shape[1] * r), int(img.shape[0] * r)),
  765. interpolation=cv2.INTER_LINEAR,
  766. ).astype(np.uint8)
  767. padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
  768. padded_img = padded_img.transpose(swap)
  769. padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
  770. return padded_img, r
Discard
Tip!

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