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

#468 Bug/sg 399 external checkpoints fix

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

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