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

detection_utils.py 50 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
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
  1. import math
  2. import os
  3. from abc import ABC, abstractmethod
  4. from enum import Enum
  5. from typing import Callable, List, Union, Tuple
  6. import cv2
  7. from deprecated import deprecated
  8. from scipy.cluster.vq import kmeans
  9. from tqdm import tqdm
  10. import matplotlib.pyplot as plt
  11. from PIL import Image
  12. import torch
  13. import torchvision
  14. import numpy as np
  15. from torch import nn
  16. from torch.nn import functional as F
  17. from super_gradients.common.abstractions.abstract_logger import get_logger
  18. from omegaconf import ListConfig
  19. def base_detection_collate_fn(batch):
  20. """
  21. Batch Processing helper function for detection training/testing.
  22. stacks the lists of images and targets into tensors and adds the image index to each target (so the targets could
  23. later be associated to the correct images)
  24. :param batch: Input batch from the Dataset __get_item__ method
  25. :return: batch with the transformed values
  26. """
  27. images_batch, labels_batch = list(zip(*batch))
  28. for i, labels in enumerate(labels_batch):
  29. # ADD TARGET IMAGE INDEX
  30. labels[:, 0] = i
  31. return torch.stack(images_batch, 0), torch.cat(labels_batch, 0)
  32. def convert_xyxy_bbox_to_xywh(input_bbox):
  33. """
  34. convert_xyxy_bbox_to_xywh - Converts bounding box format from [x1, y1, x2, y2] to [x, y, w, h]
  35. :param input_bbox: input bbox
  36. :return: Converted bbox
  37. """
  38. converted_bbox = torch.zeros_like(input_bbox) if isinstance(input_bbox, torch.Tensor) else np.zeros_like(input_bbox)
  39. converted_bbox[:, 0] = (input_bbox[:, 0] + input_bbox[:, 2]) / 2
  40. converted_bbox[:, 1] = (input_bbox[:, 1] + input_bbox[:, 3]) / 2
  41. converted_bbox[:, 2] = input_bbox[:, 2] - input_bbox[:, 0]
  42. converted_bbox[:, 3] = input_bbox[:, 3] - input_bbox[:, 1]
  43. return converted_bbox
  44. def convert_xywh_bbox_to_xyxy(input_bbox: torch.Tensor):
  45. """
  46. Converts bounding box format from [x, y, w, h] to [x1, y1, x2, y2]
  47. :param input_bbox: input bbox either 2-dimensional (for all boxes of a single image) or 3-dimensional (for
  48. boxes of a batch of images)
  49. :return: Converted bbox in same dimensions as the original
  50. """
  51. need_squeeze = False
  52. # the input is always processed as a batch. in case it not a batch, it is unsqueezed, process and than squeeze back.
  53. if input_bbox.dim() < 3:
  54. need_squeeze = True
  55. input_bbox = input_bbox.unsqueeze(0)
  56. converted_bbox = torch.zeros_like(input_bbox) if isinstance(input_bbox, torch.Tensor) else np.zeros_like(input_bbox)
  57. converted_bbox[:, :, 0] = input_bbox[:, :, 0] - input_bbox[:, :, 2] / 2
  58. converted_bbox[:, :, 1] = input_bbox[:, :, 1] - input_bbox[:, :, 3] / 2
  59. converted_bbox[:, :, 2] = input_bbox[:, :, 0] + input_bbox[:, :, 2] / 2
  60. converted_bbox[:, :, 3] = input_bbox[:, :, 1] + input_bbox[:, :, 3] / 2
  61. # squeeze back if needed
  62. if need_squeeze:
  63. converted_bbox = converted_bbox[0]
  64. return converted_bbox
  65. def calculate_wh_iou(box1, box2) -> float:
  66. """
  67. calculate_wh_iou - Gets the Intersection over Union of the w,h values of the bboxes
  68. :param box1:
  69. :param box2:
  70. :return: IOU
  71. """
  72. # RETURNS THE IOU OF WH1 TO WH2. WH1 IS 2, WH2 IS NX2
  73. box2 = box2.t()
  74. # W, H = BOX1
  75. w1, h1 = box1[0], box1[1]
  76. w2, h2 = box2[0], box2[1]
  77. # INTERSECTION AREA
  78. intersection_area = torch.min(w1, w2) * torch.min(h1, h2)
  79. # UNION AREA
  80. union_area = (w1 * h1 + 1e-16) + w2 * h2 - intersection_area
  81. return intersection_area / union_area
  82. def _iou(CIoU: bool, DIoU: bool, GIoU: bool, b1_x1, b1_x2, b1_y1, b1_y2, b2_x1, b2_x2, b2_y1, b2_y2, eps):
  83. """
  84. Internal function for the use of calculate_bbox_iou_matrix and calculate_bbox_iou_elementwise functions
  85. DO NOT CALL THIS FUNCTIONS DIRECTLY - use one of the functions mentioned above
  86. """
  87. # Intersection area
  88. intersection_area = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
  89. (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
  90. # Union Area
  91. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
  92. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
  93. union_area = w1 * h1 + w2 * h2 - intersection_area + eps
  94. iou = intersection_area / union_area # iou
  95. if GIoU or DIoU or CIoU:
  96. cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
  97. ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
  98. # Generalized IoU https://arxiv.org/pdf/1902.09630.pdf
  99. if GIoU:
  100. c_area = cw * ch + eps # convex area
  101. iou -= (c_area - union_area) / c_area # GIoU
  102. # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  103. if DIoU or CIoU:
  104. # convex diagonal squared
  105. c2 = cw ** 2 + ch ** 2 + eps
  106. # centerpoint distance squared
  107. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
  108. if DIoU:
  109. iou -= rho2 / c2 # DIoU
  110. elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  111. v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
  112. with torch.no_grad():
  113. alpha = v / ((1 + eps) - iou + v)
  114. iou -= (rho2 / c2 + v * alpha) # CIoU
  115. return iou
  116. def calculate_bbox_iou_matrix(box1, box2, x1y1x2y2=True, GIoU: bool = False, DIoU=False, CIoU=False, eps=1e-9):
  117. """
  118. calculate iou matrix containing the iou of every couple iuo(i,j) where i is in box1 and j is in box2
  119. :param box1: a 2D tensor of boxes (shape N x 4)
  120. :param box2: a 2D tensor of boxes (shape M x 4)
  121. :param x1y1x2y2: boxes format is x1y1x2y2 (True) or xywh where xy is the center (False)
  122. :return: a 2D iou matrix (shape NxM)
  123. """
  124. if box1.dim() > 1:
  125. box1 = box1.T
  126. # Get the coordinates of bounding boxes
  127. if x1y1x2y2: # x1, y1, x2, y2 = box1
  128. b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
  129. b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]
  130. else: # x, y, w, h = box1
  131. b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
  132. b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
  133. b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
  134. b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
  135. b1_x1, b1_y1, b1_x2, b1_y2 = b1_x1.unsqueeze(1), b1_y1.unsqueeze(1), b1_x2.unsqueeze(1), b1_y2.unsqueeze(1)
  136. return _iou(CIoU, DIoU, GIoU, b1_x1, b1_x2, b1_y1, b1_y2, b2_x1, b2_x2, b2_y1, b2_y2, eps)
  137. def calculate_bbox_iou_elementwise(box1, box2, x1y1x2y2=True, GIoU: bool = False, DIoU=False, CIoU=False, eps=1e-9):
  138. """
  139. calculate elementwise iou of two bbox tensors
  140. :param box1: a 2D tensor of boxes (shape N x 4)
  141. :param box2: a 2D tensor of boxes (shape N x 4)
  142. :param x1y1x2y2: boxes format is x1y1x2y2 (True) or xywh where xy is the center (False)
  143. :return: a 1D iou tensor (shape N)
  144. """
  145. # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
  146. box2 = box2.T
  147. # Get the coordinates of bounding boxes
  148. if x1y1x2y2: # x1, y1, x2, y2 = box1
  149. b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
  150. b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
  151. else: # x, y, w, h = box1
  152. b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
  153. b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
  154. b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
  155. b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
  156. return _iou(CIoU, DIoU, GIoU, b1_x1, b1_x2, b1_y1, b1_y2, b2_x1, b2_x2, b2_y1, b2_y2, eps)
  157. def calc_bbox_iou_matrix(pred: torch.Tensor):
  158. """
  159. calculate iou for every pair of boxes in the boxes vector
  160. :param pred: a 3-dimensional tensor containing all boxes for a batch of images [N, num_boxes, 4], where
  161. each box format is [x1,y1,x2,y2]
  162. :return: a 3-dimensional matrix where M_i_j_k is the iou of box j and box k of the i'th image in the batch
  163. """
  164. box = pred[:, :, :4] #
  165. b1_x1, b1_y1 = box[:, :, 0].unsqueeze(1), box[:, :, 1].unsqueeze(1)
  166. b1_x2, b1_y2 = box[:, :, 2].unsqueeze(1), box[:, :, 3].unsqueeze(1)
  167. b2_x1 = b1_x1.transpose(2, 1)
  168. b2_x2 = b1_x2.transpose(2, 1)
  169. b2_y1 = b1_y1.transpose(2, 1)
  170. b2_y2 = b1_y2.transpose(2, 1)
  171. intersection_area = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
  172. (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
  173. # Union Area
  174. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
  175. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
  176. union_area = (w1 * h1 + 1e-16) + w2 * h2 - intersection_area
  177. ious = intersection_area / union_area
  178. return ious
  179. def build_detection_targets(detection_net: nn.Module, targets: torch.Tensor):
  180. """
  181. build_detection_targets - Builds the outputs of the Detection NN
  182. This function filters all of the targets that don't have a sufficient iou coverage
  183. of the Model's pre-trained k-means anchors
  184. The iou_threshold is a parameter of the NN Model
  185. :param detection_net: The nn.Module of the Detection Algorithm
  186. :param targets: targets (labels)
  187. :return:
  188. """
  189. # TARGETS = [image, class, x, y, w, h]
  190. targets_num = len(targets)
  191. target_classes, target_bbox, indices, anchor_vector_list = [], [], [], []
  192. reject, use_all_anchors = True, True
  193. for i in detection_net.yolo_layers_indices:
  194. yolo_layer_module = list(detection_net.module_list)[i]
  195. # GET NUMBER OF GRID POINTS AND ANCHOR VEC FOR THIS YOLO LAYER
  196. grid_points_num, anchor_vec = yolo_layer_module.grid_size, yolo_layer_module.anchor_vec
  197. # IOU OF TARGETS-ANCHORS
  198. iou_targets, anchors = targets, []
  199. gwh = iou_targets[:, 4:6] * grid_points_num
  200. if targets_num:
  201. iou = torch.stack([calculate_wh_iou(x, gwh) for x in anchor_vec], 0)
  202. if use_all_anchors:
  203. anchors_num = len(anchor_vec)
  204. anchors = torch.arange(anchors_num).view((-1, 1)).repeat([1, targets_num]).view(-1)
  205. iou_targets = targets.repeat([anchors_num, 1])
  206. gwh = gwh.repeat([anchors_num, 1])
  207. else:
  208. # USE ONLY THE BEST ANCHOR
  209. iou, anchors = iou.max(0) # best iou and anchor
  210. # REJECT ANCHORS BELOW IOU_THRES (OPTIONAL, INCREASES P, LOWERS R)
  211. if reject:
  212. # IOU THRESHOLD HYPERPARAMETER
  213. j = iou.view(-1) > detection_net.iou_t
  214. iou_targets, anchors, gwh = iou_targets[j], anchors[j], gwh[j]
  215. # INDICES
  216. target_image, target_class = iou_targets[:, :2].long().t()
  217. x_y_grid = iou_targets[:, 2:4] * grid_points_num
  218. x_grid_idx, y_grid_idx = x_y_grid.long().t()
  219. indices.append((target_image, anchors, y_grid_idx, x_grid_idx))
  220. # GIoU
  221. x_y_grid -= x_y_grid.floor()
  222. target_bbox.append(torch.cat((x_y_grid, gwh), 1))
  223. anchor_vector_list.append(anchor_vec[anchors])
  224. # Class
  225. target_classes.append(target_class)
  226. if target_class.shape[0]:
  227. if not target_class.max() < detection_net.num_classes:
  228. raise ValueError('Labeled Class is out of bounds of the classes list')
  229. return target_classes, target_bbox, indices, anchor_vector_list
  230. def yolo_v3_non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.5, device='cpu'): # noqa: C901
  231. """
  232. non_max_suppression - Removes detections with lower object confidence score than 'conf_thres'
  233. Non-Maximum Suppression to further filter detections.
  234. :param prediction: the raw prediction as produced by the yolo_v3 network
  235. :param conf_thres: confidence threshold - only prediction with confidence score higher than the threshold
  236. will be considered
  237. :param nms_thres: IoU threshold for the nms algorithm
  238. :param device: the device to move all output tensors into
  239. :return: (x1, y1, x2, y2, object_conf, class_conf, class)
  240. """
  241. # MINIMUM AND MAXIMIUM BOX WIDTH AND HEIGHT IN PIXELS
  242. min_wh = 2
  243. max_wh = 10000
  244. output = [None] * len(prediction)
  245. for image_i, pred in enumerate(prediction):
  246. # MULTIPLY CONF BY CLASS CONF TO GET COMBINED CONFIDENCE
  247. class_conf, class_pred = pred[:, 5:].max(1)
  248. pred[:, 4] *= class_conf
  249. # IGNORE ANYTHING UNDER conf_thres
  250. i = (pred[:, 4] > conf_thres) & (pred[:, 2:4] > min_wh).all(1) & (pred[:, 2:4] < max_wh).all(1) & \
  251. torch.isfinite(pred).all(1)
  252. pred = pred[i]
  253. # NOTHING IS OVER THE THRESHOLD
  254. if len(pred) == 0:
  255. continue
  256. class_conf = class_conf[i]
  257. class_pred = class_pred[i].unsqueeze(1).float()
  258. # BOX (CENTER X, CENTER Y, WIDTH, HEIGHT) TO (X1, Y1, X2, Y2)
  259. pred[:, :4] = convert_xywh_bbox_to_xyxy(pred[:, :4])
  260. # DETECTIONS ORDERED AS (x1y1x2y2, obj_conf, class_conf, class_pred)
  261. pred = torch.cat((pred[:, :5], class_conf.unsqueeze(1), class_pred), 1)
  262. # SORT DETECTIONS BY DECREASING CONFIDENCE SCORES
  263. pred = pred[(-pred[:, 4]).argsort()]
  264. # 'OR', 'AND', 'MERGE', 'VISION', 'VISION_BATCHED'
  265. # MERGE is highest mAP, VISION is fastest
  266. method = 'MERGE' if conf_thres <= 0.01 else 'VISION'
  267. # BATCHED NMS
  268. if method == 'VISION_BATCHED':
  269. i = torchvision.ops.boxes.batched_nms(boxes=pred[:, :4],
  270. scores=pred[:, 4],
  271. idxs=pred[:, 6],
  272. iou_threshold=nms_thres)
  273. output[image_i] = pred[i]
  274. continue
  275. # Non-maximum suppression
  276. det_max = []
  277. for detection_class in pred[:, -1].unique():
  278. dc = pred[pred[:, -1] == detection_class]
  279. n = len(dc)
  280. if n == 1:
  281. # NO NMS REQUIRED FOR A SINGLE CLASS
  282. det_max.append(dc)
  283. continue
  284. elif n > 500:
  285. dc = dc[:500]
  286. if method == 'VISION':
  287. i = torchvision.ops.boxes.nms(dc[:, :4], dc[:, 4], nms_thres)
  288. det_max.append(dc[i])
  289. elif method == 'OR':
  290. while dc.shape[0]:
  291. det_max.append(dc[:1])
  292. if len(dc) == 1:
  293. break
  294. iou = calculate_bbox_iou_elementwise(dc[0], dc[1:])
  295. dc = dc[1:][iou < nms_thres]
  296. elif method == 'AND':
  297. while len(dc) > 1:
  298. iou = calculate_bbox_iou_elementwise(dc[0], dc[1:])
  299. if iou.max() > 0.5:
  300. det_max.append(dc[:1])
  301. dc = dc[1:][iou < nms_thres]
  302. elif method == 'MERGE':
  303. while len(dc):
  304. if len(dc) == 1:
  305. det_max.append(dc)
  306. break
  307. i = calculate_bbox_iou_elementwise(dc[0], dc) > nms_thres
  308. weights = dc[i, 4:5]
  309. dc[0, :4] = (weights * dc[i, :4]).sum(0) / weights.sum()
  310. det_max.append(dc[:1])
  311. dc = dc[i == 0]
  312. elif method == 'SOFT':
  313. sigma = 0.5
  314. while len(dc):
  315. if len(dc) == 1:
  316. det_max.append(dc)
  317. break
  318. det_max.append(dc[:1])
  319. iou = calculate_bbox_iou_elementwise(dc[0], dc[1:])
  320. dc = dc[1:]
  321. dc[:, 4] *= torch.exp(-iou ** 2 / sigma)
  322. dc = dc[dc[:, 4] > conf_thres]
  323. if len(det_max):
  324. det_max = torch.cat(det_max)
  325. output[image_i] = det_max[(-det_max[:, 4]).argsort()].to(device)
  326. return output
  327. def change_bbox_bounds_for_image_size(boxes, img_shape):
  328. # CLIP BOUNDING XYXY BOUNDING BOXES TO IMAGE SHAPE (HEIGHT, WIDTH)
  329. boxes[:, [0, 2]] = boxes[:, [0, 2]].clamp(min=0, max=img_shape[1])
  330. boxes[:, [1, 3]] = boxes[:, [1, 3]].clamp(min=0, max=img_shape[0])
  331. return boxes
  332. def rescale_bboxes_for_image_size(current_image_shape, bbox, original_image_shape, ratio_pad=None):
  333. """
  334. rescale_bboxes_for_image_size - Changes the bboxes to fit the original image
  335. :param current_image_shape:
  336. :param bbox:
  337. :param original_image_shape:
  338. :param ratio_pad:
  339. :return:
  340. """
  341. if ratio_pad is None:
  342. gain = max(current_image_shape) / max(original_image_shape)
  343. # WH PADDING
  344. pad = (current_image_shape[1] - original_image_shape[1] * gain) / 2, \
  345. (current_image_shape[0] - original_image_shape[0] * gain) / 2
  346. else:
  347. gain = ratio_pad[0][0]
  348. pad = ratio_pad[1]
  349. # X PADDING
  350. bbox[:, [0, 2]] -= pad[0]
  351. # Y PADDING
  352. bbox[:, [1, 3]] -= pad[1]
  353. bbox[:, :4] /= gain
  354. bbox = change_bbox_bounds_for_image_size(bbox, original_image_shape)
  355. return bbox
  356. class DetectionPostPredictionCallback(ABC, nn.Module):
  357. def __init__(self) -> None:
  358. super().__init__()
  359. @abstractmethod
  360. def forward(self, x, device: str):
  361. """
  362. :param x: the output of your model
  363. :param device: the device to move all output tensors into
  364. :return: a list with length batch_size, each item in the list is a detections
  365. with shape: nx6 (x1, y1, x2, y2, confidence, class) where x and y are in range [0,1]
  366. """
  367. raise NotImplementedError
  368. class YoloV3NonMaxSuppression(DetectionPostPredictionCallback):
  369. def __init__(self, conf: float = 0.001, nms_thres: float = 0.5, max_predictions=500) -> None:
  370. super().__init__()
  371. self.conf = conf
  372. self.max_predictions = max_predictions
  373. self.nms_thres = nms_thres
  374. def forward(self, x, device: str):
  375. return yolo_v3_non_max_suppression(x[0], device=device, conf_thres=self.conf, nms_thres=self.nms_thres)
  376. class IouThreshold(tuple, Enum):
  377. MAP_05 = (0.5, 0.5)
  378. MAP_05_TO_095 = (0.5, 0.95)
  379. def is_range(self):
  380. return self[0] != self[1]
  381. def scale_img(img, ratio=1.0, pad_to_original_img_size=False):
  382. """
  383. Scales the image by ratio (image dims is (batch_size, channels, height, width)
  384. Taken from Yolov5 Ultralitics repo"""
  385. if ratio == 1.0:
  386. return img
  387. else:
  388. h, w = img.shape[2:]
  389. rescaled_size = (int(h * ratio), int(w * ratio))
  390. img = F.interpolate(img, size=rescaled_size, mode='bilinear', align_corners=False)
  391. # PAD THE IMAGE TO BE A MULTIPLIER OF grid_size. O.W. PAD IT TO THE ORIGINAL IMAGE SIZE
  392. if not pad_to_original_img_size:
  393. # THE MULTIPLIER WHICH THE DIMENSION MUST BE DIVISIBLE BY
  394. grid_size = 32
  395. # COMPUTE THE NEW SIZE OF THE IMAGE TO RETURN
  396. h, w = [math.ceil(x * ratio / grid_size) * grid_size for x in (h, w)]
  397. # PAD THE IMAGE TO FIT w, h (EITHER THE ORIGINAL SIZE OR THE NEW SIZE
  398. return F.pad(img, [0, w - rescaled_size[1], 0, h - rescaled_size[0]], value=0.447) # value = imagenet mean
  399. @deprecated(reason="use @torch.nn.utils.fuse_conv_bn_eval(conv, bn) instead")
  400. def fuse_conv_and_bn(conv, bn):
  401. """Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
  402. Taken from Yolov5 Ultralitics repo"""
  403. # init
  404. fusedconv = nn.Conv2d(conv.in_channels,
  405. conv.out_channels,
  406. kernel_size=conv.kernel_size,
  407. stride=conv.stride,
  408. padding=conv.padding,
  409. groups=conv.groups,
  410. bias=True).requires_grad_(False).to(conv.weight.device)
  411. # prepare filters
  412. w_conv = conv.weight.clone().view(conv.out_channels, -1)
  413. w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
  414. fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))
  415. # prepare spatial bias
  416. b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
  417. b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
  418. fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
  419. return fusedconv
  420. def check_anchor_order(m):
  421. """Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
  422. Taken from Yolov5 Ultralitics repo"""
  423. anchor_area = m.anchor_grid.prod(-1).view(-1)
  424. delta_area = anchor_area[-1] - anchor_area[0]
  425. delta_stride = m.stride[-1] - m.stride[0] # delta s
  426. # IF THE SIGN OF THE SUBTRACTION IS DIFFERENT => THE STRIDE IS NOT ALIGNED WITH ANCHORS => m.anchors ARE REVERSED
  427. if delta_area.sign() != delta_stride.sign():
  428. print('Reversing anchor order')
  429. m.anchors[:] = m.anchors.flip(0)
  430. m.anchor_grid[:] = m.anchor_grid.flip(0)
  431. def box_iou(box1, box2):
  432. # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
  433. """
  434. Return intersection-over-union (Jaccard index) of boxes.
  435. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
  436. Arguments:
  437. box1 (Tensor[N, 4])
  438. box2 (Tensor[M, 4])
  439. Returns:
  440. iou (Tensor[N, M]): the NxM matrix containing the pairwise
  441. IoU values for every element in boxes1 and boxes2
  442. Taken from Yolov5 Ultralitics repo
  443. """
  444. def box_area(box):
  445. # box = 4xn
  446. return (box[2] - box[0]) * (box[3] - box[1])
  447. area1 = box_area(box1.T)
  448. area2 = box_area(box2.T)
  449. # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
  450. inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
  451. return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
  452. def non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, merge=False, classes=None,
  453. agnostic=False): # noqa: C901
  454. """Performs Non-Maximum Suppression (NMS) on inference results
  455. :param prediction: raw model prediction
  456. :param conf_thres: below the confidence threshold - prediction are discarded
  457. :param iou_thres: IoU threshold for the nms algorithm
  458. :param merge: Merge boxes using weighted mean
  459. :param classes: (optional list) filter by class
  460. :param agnostic: Determines if is class agnostic. i.e. may display a box with 2 predictions
  461. :return: (x1, y1, x2, y2, object_conf, class_conf, class)
  462. Returns:
  463. detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
  464. """
  465. # TODO: INVESTIGATE THE COMMENTED OUT PARTS AND DECIDE IF TO ERASE OR UNCOMMENT
  466. number_of_classes = prediction[0].shape[1] - 5
  467. candidates_above_thres = prediction[..., 4] > conf_thres
  468. # Settings
  469. # min_box_width_and_height = 2
  470. max_box_width_and_height = 4096
  471. max_num_of_detections = 300
  472. require_redundant_detections = True
  473. multi_label_per_box = number_of_classes > 1 # (adds 0.5ms/img)
  474. output = [None] * prediction.shape[0]
  475. for image_idx, pred in enumerate(prediction):
  476. # Apply constraints
  477. # pred[((pred[..., 2:4] < min_box_width_and_height) | (pred[..., 2:4] > max_box_width_and_height)).any(1), 4] = 0 # width-height
  478. pred = pred[candidates_above_thres[image_idx]] # confidence
  479. # If none remain process next image
  480. if not pred.shape[0]:
  481. continue
  482. # Compute confidence = object_conf * class_conf
  483. pred[:, 5:] *= pred[:, 4:5]
  484. # Box (center x, center y, width, height) to (x1, y1, x2, y2)
  485. box = convert_xywh_bbox_to_xyxy(pred[:, :4])
  486. # Detections matrix nx6 (xyxy, conf, cls)
  487. if multi_label_per_box:
  488. i, j = (pred[:, 5:] > conf_thres).nonzero(as_tuple=False).T
  489. pred = torch.cat((box[i], pred[i, j + 5, None], j[:, None].float()), 1)
  490. else: # best class only
  491. conf, j = pred[:, 5:].max(1, keepdim=True)
  492. pred = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
  493. # Filter by class
  494. if classes:
  495. pred = pred[(pred[:, 5:6] == torch.tensor(classes, device=pred.device)).any(1)]
  496. # Apply finite constraint
  497. # if not torch.isfinite(x).all():
  498. # x = x[torch.isfinite(x).all(1)]
  499. # If none remain process next image
  500. number_of_boxes = pred.shape[0]
  501. if not number_of_boxes:
  502. continue
  503. # Sort by confidence
  504. # x = x[x[:, 4].argsort(descending=True)]
  505. # Batched NMS
  506. # CREATE AN OFFSET OF THE PREDICTIVE BOX OF DIFFERENT CLASSES IF not agnostic
  507. offset = pred[:, 5:6] * (0 if agnostic else max_box_width_and_height)
  508. boxes, scores = pred[:, :4] + offset, pred[:, 4]
  509. idx_to_keep = torch.ops.torchvision.nms(boxes, scores, iou_thres)
  510. if idx_to_keep.shape[0] > max_num_of_detections: # limit number of detections
  511. idx_to_keep = idx_to_keep[:max_num_of_detections]
  512. if merge and (1 < number_of_boxes < 3000):
  513. try: # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
  514. iou = box_iou(boxes[idx_to_keep], boxes) > iou_thres # iou matrix
  515. box_weights = iou * scores[None]
  516. # MERGED BOXES
  517. pred[idx_to_keep, :4] = torch.mm(box_weights, pred[:, :4]).float() / box_weights.sum(1, keepdim=True)
  518. if require_redundant_detections:
  519. idx_to_keep = idx_to_keep[iou.sum(1) > 1]
  520. except RuntimeError: # possible CUDA error https://github.com/ultralytics/yolov3/issues/1139
  521. print(pred, idx_to_keep, pred.shape, idx_to_keep.shape)
  522. pass
  523. output[image_idx] = pred[idx_to_keep]
  524. return output
  525. def check_img_size_divisibilty(img_size: int, stride: int = 32):
  526. """
  527. :param img_size: Int, the size of the image (H or W).
  528. :param stride: Int, the number to check if img_size is divisible by.
  529. :return: (True, None) if img_size is divisble by stride, (False, Suggestions) if it's not.
  530. Note: Suggestions are the two closest numbers to img_size that *are* divisible by stride.
  531. For example if img_size=321, stride=32, it will return (False,(352, 320)).
  532. """
  533. new_size = make_divisible(img_size, int(stride))
  534. if new_size != img_size:
  535. return False, (new_size, make_divisible(img_size, int(stride), ceil=False))
  536. else:
  537. return True, None
  538. def make_divisible(x, divisor, ceil=True):
  539. """
  540. Returns x evenly divisible by divisor.
  541. If ceil=True it will return the closest larger number to the original x, and ceil=False the closest smaller number.
  542. """
  543. if ceil:
  544. return math.ceil(x / divisor) * divisor
  545. else:
  546. return math.floor(x / divisor) * divisor
  547. def matrix_non_max_suppression(pred, conf_thres: float = 0.1, kernel: str = 'gaussian',
  548. sigma: float = 3.0, max_num_of_detections: int = 500):
  549. """Performs Matrix Non-Maximum Suppression (NMS) on inference results
  550. https://arxiv.org/pdf/1912.04488.pdf
  551. :param pred: raw model prediction (in test mode) - a Tensor of shape [batch, num_predictions, 85]
  552. where each item format is (x, y, w, h, object_conf, class_conf, ... 80 classes score ...)
  553. :param conf_thres: below the confidence threshold - prediction are discarded
  554. :param kernel: type of kernel to use ['gaussian', 'linear']
  555. :param sigma: sigma for the gussian kernel
  556. :param max_num_of_detections: maximum number of boxes to output
  557. :return: list of (x1, y1, x2, y2, object_conf, class_conf, class)
  558. Returns:
  559. detections list with shape: (x1, y1, x2, y2, conf, cls)
  560. """
  561. # MULTIPLY CONF BY CLASS CONF TO GET COMBINED CONFIDENCE
  562. class_conf, class_pred = pred[:, :, 5:].max(2)
  563. pred[:, :, 4] *= class_conf
  564. # BOX (CENTER X, CENTER Y, WIDTH, HEIGHT) TO (X1, Y1, X2, Y2)
  565. pred[:, :, :4] = convert_xywh_bbox_to_xyxy(pred[:, :, :4])
  566. # DETECTIONS ORDERED AS (x1y1x2y2, obj_conf, class_conf, class_pred)
  567. pred = torch.cat((pred[:, :, :5], class_pred.unsqueeze(2)), 2)
  568. # SORT DETECTIONS BY DECREASING CONFIDENCE SCORES
  569. sort_ind = (-pred[:, :, 4]).argsort()
  570. pred = torch.stack([pred[i, sort_ind[i]] for i in range(pred.shape[0])])[:, 0:max_num_of_detections]
  571. ious = calc_bbox_iou_matrix(pred)
  572. ious = ious.triu(1)
  573. # CREATE A LABELS MASK, WE WANT ONLY BOXES WITH THE SAME LABEL TO AFFECT EACH OTHER
  574. labels = pred[:, :, 5:]
  575. labeles_matrix = (labels == labels.transpose(2, 1)).float().triu(1)
  576. ious *= labeles_matrix
  577. ious_cmax, _ = ious.max(1)
  578. ious_cmax = ious_cmax.unsqueeze(2).repeat(1, 1, max_num_of_detections)
  579. if kernel == 'gaussian':
  580. decay_matrix = torch.exp(-1 * sigma * (ious ** 2))
  581. compensate_matrix = torch.exp(-1 * sigma * (ious_cmax ** 2))
  582. decay, _ = (decay_matrix / compensate_matrix).min(dim=1)
  583. else:
  584. decay = (1 - ious) / (1 - ious_cmax)
  585. decay, _ = decay.min(dim=1)
  586. pred[:, :, 4] *= decay
  587. output = [pred[i, pred[i, :, 4] > conf_thres] for i in range(pred.shape[0])]
  588. return output
  589. class NMS_Type(str, Enum):
  590. """
  591. Type of non max suppression algorithm that can be used for post processing detection
  592. """
  593. ITERATIVE = 'iterative'
  594. MATRIX = 'matrix'
  595. def calc_batch_prediction_accuracy(output: torch.Tensor, targets: torch.Tensor, height: int, width: int, # noqa: C901
  596. iou_thres: IouThreshold) -> tuple:
  597. """
  598. :param output: list (of length batch_size) of Tensors of shape (num_detections, 6)
  599. format: (x1, y1, x2, y2, confidence, class_label) where x1,y1,x2,y2 are according to image size
  600. :param targets: targets for all images of shape (total_num_targets, 6)
  601. format: (image_index, x, y, w, h, label) where x,y,w,h are in range [0,1]
  602. :param height,width: dimensions of the image
  603. :param iou_thres: Threshold to compute the mAP
  604. :param device: 'cuda'\'cpu' - where the computations are made
  605. :return:
  606. """
  607. batch_metrics = []
  608. batch_images_counter = 0
  609. device = targets.device
  610. if not iou_thres.is_range():
  611. num_ious = 1
  612. ious = torch.tensor([iou_thres[0]]).to(device)
  613. else:
  614. num_ious = int(round((iou_thres[1] - iou_thres[0]) / 0.05)) + 1
  615. ious = torch.linspace(iou_thres[0], iou_thres[1], num_ious).to(device)
  616. for i, pred in enumerate(output):
  617. labels = targets[targets[:, 0] == i, 1:]
  618. labels_num = len(labels)
  619. target_class = labels[:, 0].tolist() if labels_num else []
  620. batch_images_counter += 1
  621. if pred is None:
  622. if labels_num:
  623. batch_metrics.append(
  624. (np.zeros((0, num_ious), dtype=np.bool), np.array([], dtype=np.float32), np.array([], dtype=np.float32), target_class))
  625. continue
  626. # CHANGE bboxes TO FIT THE IMAGE SIZE
  627. change_bbox_bounds_for_image_size(pred, (height, width))
  628. # ZEROING ALL OF THE bbox PREDICTIONS BEFORE MAX IOU FILTERATION
  629. correct = torch.zeros(len(pred), num_ious, dtype=torch.bool, device=device)
  630. if labels_num:
  631. detected = []
  632. tcls_tensor = labels[:, 0]
  633. target_bboxes = convert_xywh_bbox_to_xyxy(labels[:, 1:5])
  634. target_bboxes[:, [0, 2]] *= width
  635. target_bboxes[:, [1, 3]] *= height
  636. # SEARCH FOR CORRECT PREDICTIONS
  637. # Per target class
  638. for cls in torch.unique(tcls_tensor):
  639. target_index = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1)
  640. pred_index = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1)
  641. # Search for detections
  642. if pred_index.shape[0]:
  643. # Prediction to target ious
  644. iou, i = box_iou(pred[pred_index, :4], target_bboxes[target_index]).max(1) # best ious, indices
  645. # Append detections
  646. detected_set = set()
  647. for j in (iou > ious[0]).nonzero(as_tuple=False):
  648. detected_target = target_index[i[j]]
  649. if detected_target.item() not in detected_set:
  650. detected_set.add(detected_target.item())
  651. detected.append(detected_target)
  652. correct[pred_index[j]] = iou[j] > ious # iou_thres is 1xn
  653. if len(detected) == labels_num: # all targets already located in image
  654. break
  655. # APPEND STATISTICS (CORRECT, CONF, PCLS, TCLS)
  656. batch_metrics.append((correct.cpu().numpy(), pred[:, 4].cpu().numpy(), pred[:, -1].cpu().numpy(), target_class))
  657. return batch_metrics, batch_images_counter
  658. class AnchorGenerator:
  659. logger = get_logger(__name__)
  660. @staticmethod
  661. def _metric(objects, anchors):
  662. """ measure how 'far' each object is from the closest anchor
  663. :returns a matrix n by number of objects and the measurements to the closest anchor for each object
  664. """
  665. r = objects[:, None] / anchors[None]
  666. matrix = np.amin(np.minimum(r, 1. / r), axis=2)
  667. return matrix, matrix.max(1)
  668. @staticmethod
  669. def _anchor_fitness(objects, anchors, thresh):
  670. """ how well the anchors fit the objects"""
  671. _, best = AnchorGenerator._metric(objects, anchors)
  672. return (best * (best > thresh)).mean() # fitness
  673. @staticmethod
  674. def _print_results(objects, anchors, thresh, num_anchors, img_size):
  675. # SORT SMALL TO LARGE (BY AREA)
  676. anchors = anchors[np.argsort(anchors.prod(1))]
  677. x, best = AnchorGenerator._metric(objects, anchors)
  678. best_possible_recall = (best > thresh).mean()
  679. anchors_above_thesh = (x > thresh).mean() * num_anchors
  680. AnchorGenerator.logger.info(
  681. f'thr={thresh:.2f}: {best_possible_recall:.4f} best possible recall, {anchors_above_thesh:.2f} anchors past thr')
  682. AnchorGenerator.logger.info(f'num_anchors={num_anchors}, img_size={img_size}')
  683. AnchorGenerator.logger.info(
  684. f' metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, past_thr={x[x > thresh].mean():.3f}-mean: ')
  685. for i, mean in enumerate(anchors):
  686. print('%i,%i' % (round(mean[0]), round(mean[1])),
  687. end=', ' if i < len(anchors) - 1 else '\n') # use in *.cfg
  688. @staticmethod
  689. def _plot_object_distribution(objects, anchors):
  690. selected = np.random.choice(objects.shape[0], size=objects.shape[0] // 50, replace=False)
  691. distance_matrix = np.sqrt(np.power(objects[:, :, None] - anchors[:, :, None].T, 2).sum(1))
  692. labels = np.argmin(distance_matrix, axis=1)
  693. plt.scatter(objects[selected, 0], objects[selected, 1], c=labels[selected], marker='.')
  694. plt.scatter(anchors[:, 0], anchors[:, 1], marker='P')
  695. plt.show()
  696. @staticmethod
  697. def _generate_anchors(dataset, num_anchors=9, thresh=0.25, gen=1000):
  698. """ Creates kmeans-evolved anchors from training dataset
  699. Based on the implementation by Ultralytics for Yolo V5
  700. :param dataset: a loaded dataset (must be with cached labels and "train_sample_loading_method":'rectangular')
  701. :param num_anchors: number of anchors
  702. :param thresh: anchor-label wh ratio threshold used to asses if a label can be detected by an anchor.
  703. it means that the aspect ratio of the object is not more than thres from the aspect ratio of the anchor.
  704. :param gen: generations to evolve anchors using genetic algorithm. after kmeans, this algorithm iteratively
  705. make minor random changes in the anchors and if a change imporve the anchors-data fit it evolves the
  706. anchors.
  707. :returns anchors array num_anchors by 2 (x,y) normalized to image size
  708. """
  709. _prefix = 'Anchors Generator: '
  710. img_size = dataset.img_size
  711. assert dataset.cache_labels, "dataset labels have to be cached before generating anchors"
  712. image_shapes = np.array(
  713. [dataset.exif_size(Image.open(f)) for f in tqdm(dataset.img_files, desc='Reading image shapes')])
  714. # Get label wh
  715. shapes = img_size * image_shapes / image_shapes.max(1, keepdims=True)
  716. objects_wh = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)])
  717. # Filter
  718. i = (objects_wh < 3.0).any(1).sum()
  719. if i:
  720. AnchorGenerator.logger.warning(
  721. f'Extremely small objects found. {i} of {len(objects_wh)} labels are < 3 pixels in size.')
  722. object_wh_filtered = objects_wh[(objects_wh >= 2.0).any(1)]
  723. # Kmeans calculation
  724. AnchorGenerator.logger.info(f'Running kmeans for {num_anchors} anchors on {len(object_wh_filtered)} points...')
  725. mean_wh = object_wh_filtered.std(0) # sigmas for whitening
  726. anchors, dist = kmeans(object_wh_filtered / mean_wh, num_anchors, iter=30) # points, mean distance
  727. # MEANS WHERE NORMALIZED. SCALE THEM BACK TO IMAGE SIZE
  728. anchors *= mean_wh
  729. AnchorGenerator.logger.info('Initial results')
  730. AnchorGenerator._print_results(objects_wh, anchors, thresh, num_anchors, img_size)
  731. AnchorGenerator._plot_object_distribution(objects_wh, anchors)
  732. # EVOLVE
  733. fitness, generations, mutation_prob, sigma = AnchorGenerator._anchor_fitness(object_wh_filtered, anchors,
  734. thresh), anchors.shape, 0.9, 0.1
  735. progress_bar = tqdm(range(gen), desc=f'{_prefix}Evolving anchors with Genetic Algorithm:')
  736. for _ in progress_bar:
  737. v = np.ones(generations)
  738. while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
  739. v = ((np.random.random(generations) < mutation_prob) * np.random.random() * np.random.randn(
  740. *generations) * sigma + 1).clip(0.3, 3.0)
  741. evolved_anchors = (anchors * v).clip(min=2.0)
  742. evolved_anchors_fitness = AnchorGenerator._anchor_fitness(object_wh_filtered, evolved_anchors, thresh)
  743. if evolved_anchors_fitness > fitness:
  744. fitness, anchors = evolved_anchors_fitness, evolved_anchors.copy()
  745. progress_bar.desc = f'{_prefix}Evolving anchors with Genetic Algorithm: fitness = {fitness:.4f}'
  746. AnchorGenerator.logger.info('Final results')
  747. AnchorGenerator._print_results(objects_wh, anchors, thresh, num_anchors, img_size)
  748. AnchorGenerator._plot_object_distribution(objects_wh, anchors)
  749. anchors = anchors[np.argsort(anchors.prod(1))]
  750. anchors_list = np.round(anchors.reshape((3, -1))).astype(np.int32).tolist()
  751. return anchors_list
  752. @staticmethod
  753. def __call__(dataset, num_anchors=9, thresh=0.25, gen=1000):
  754. return AnchorGenerator._generate_anchors(dataset, num_anchors, thresh, gen)
  755. def plot_coco_datasaet_images_with_detections(data_loader, num_images_to_plot=1):
  756. """
  757. plot_coco_images
  758. :param data_loader:
  759. :param num_images_to_plot:
  760. :return:
  761. # """
  762. images_counter = 0
  763. # PLOT ONE image AND ONE GROUND_TRUTH bbox
  764. for imgs, targets in data_loader:
  765. # PLOTS TRAINING IMAGES OVERLAID WITH TARGETS
  766. imgs = imgs.cpu().numpy()
  767. targets = targets.cpu().numpy()
  768. fig = plt.figure(figsize=(10, 10))
  769. batch_size, _, h, w = imgs.shape
  770. # LIMIT PLOT TO 16 IMAGES
  771. batch_size = min(batch_size, 16)
  772. # NUMBER OF SUBPLOTS
  773. ns = np.ceil(batch_size ** 0.5)
  774. for i in range(batch_size):
  775. boxes = convert_xywh_bbox_to_xyxy(torch.from_numpy(targets[targets[:, 0] == i, 2:6])).cpu().detach().numpy().T
  776. boxes[[0, 2]] *= w
  777. boxes[[1, 3]] *= h
  778. plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0))
  779. plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-')
  780. plt.axis('off')
  781. fig.tight_layout()
  782. plt.show()
  783. plt.close()
  784. images_counter += 1
  785. if images_counter == num_images_to_plot:
  786. break
  787. def undo_image_preprocessing(im_tensor: torch.Tensor) -> np.ndarray:
  788. """
  789. :param im_tensor: images in a batch after preprocessing for inference, RGB, (B, C, H, W)
  790. :return: images in a batch in cv2 format, BGR, (B, H, W, C)
  791. """
  792. im_np = im_tensor.cpu().numpy()
  793. im_np = im_np[:, ::-1, :, :].transpose(0, 2, 3, 1)
  794. im_np *= 255.
  795. return np.ascontiguousarray(im_np, dtype=np.uint8)
  796. class DetectionVisualization:
  797. @staticmethod
  798. def _generate_color_mapping(num_classes: int) -> List[Tuple[int]]:
  799. """
  800. Generate a unique BGR color for each class
  801. """
  802. cmap = plt.cm.get_cmap('gist_rainbow', num_classes)
  803. colors = [cmap(i, bytes=True)[:3][::-1] for i in range(num_classes)]
  804. return [tuple(int(v) for v in c) for c in colors]
  805. @staticmethod
  806. def _draw_box_title(color_mapping: List[Tuple[int]], class_names: List[str], box_thickness: int,
  807. image_np: np.ndarray, x1: int, y1: int, x2: int, y2: int, class_id: int,
  808. pred_conf: float = None):
  809. color = color_mapping[class_id]
  810. class_name = class_names[class_id]
  811. # Draw the box
  812. image_np = cv2.rectangle(image_np, (x1, y1), (x2, y2), color, box_thickness)
  813. # Caption with class name and confidence if given
  814. text_color = (255, 255, 255) # white
  815. title = f'{class_name} {str(round(pred_conf, 2)) if pred_conf is not None else ""}'
  816. image_np = cv2.rectangle(image_np, (x1, y1 - 15), (x1 + len(title) * 10, y1), color, cv2.FILLED)
  817. image_np = cv2.putText(image_np, title, (x1, y1 - box_thickness), 2, .5, text_color, 1, lineType=cv2.LINE_AA)
  818. return image_np
  819. @staticmethod
  820. def _visualize_image(image_np: np.ndarray, pred_boxes: np.ndarray, target_boxes: np.ndarray,
  821. class_names: List[str], box_thickness: int, gt_alpha: float, image_scale: float,
  822. checkpoint_dir: str, image_name: str):
  823. image_np = cv2.resize(image_np, (0, 0), fx=image_scale, fy=image_scale, interpolation=cv2.INTER_NEAREST)
  824. color_mapping = DetectionVisualization._generate_color_mapping(len(class_names))
  825. # Draw predictions
  826. pred_boxes[:, :4] *= image_scale
  827. for box in pred_boxes:
  828. image_np = DetectionVisualization._draw_box_title(color_mapping, class_names, box_thickness,
  829. image_np, *box[:4].astype(int),
  830. class_id=int(box[5]), pred_conf=box[4])
  831. # Draw ground truths
  832. target_boxes_image = np.zeros_like(image_np, np.uint8)
  833. for box in target_boxes:
  834. target_boxes_image = DetectionVisualization._draw_box_title(color_mapping, class_names, box_thickness,
  835. target_boxes_image, *box[2:],
  836. class_id=box[1])
  837. # Transparent overlay of ground truth boxes
  838. mask = target_boxes_image.astype(bool)
  839. image_np[mask] = cv2.addWeighted(image_np, 1 - gt_alpha, target_boxes_image, gt_alpha, 0)[mask]
  840. if checkpoint_dir is None:
  841. return image_np
  842. else:
  843. cv2.imwrite(os.path.join(checkpoint_dir, str(image_name) + '.jpg'), image_np)
  844. @staticmethod
  845. def _scaled_ccwh_to_xyxy(target_boxes: np.ndarray, h: int, w: int, image_scale: float) -> np.ndarray:
  846. """
  847. Modifies target_boxes inplace
  848. :param target_boxes: (c1, c2, w, h) boxes in [0, 1] range
  849. :param h: image height
  850. :param w: image width
  851. :param image_scale: desired scale for the boxes w.r.t. w and h
  852. :return: targets in (x1, y1, x2, y2) format
  853. in range [0, w * self.image_scale] [0, h * self.image_scale]
  854. """
  855. # unscale
  856. target_boxes[:, 2:] *= np.array([[w, h, w, h]])
  857. # x1 = c1 - w // 2; y1 = c2 - h // 2
  858. target_boxes[:, 2] -= target_boxes[:, 4] // 2
  859. target_boxes[:, 3] -= target_boxes[:, 5] // 2
  860. # x2 = w + x1; y2 = h + y1
  861. target_boxes[:, 4] += target_boxes[:, 2]
  862. target_boxes[:, 5] += target_boxes[:, 3]
  863. target_boxes[:, 2:] *= image_scale
  864. target_boxes = target_boxes.astype(int)
  865. return target_boxes
  866. @staticmethod
  867. def visualize_batch(image_tensor: torch.Tensor, pred_boxes: List[torch.Tensor], target_boxes: torch.Tensor,
  868. batch_name: Union[int, str], class_names: List[str], checkpoint_dir: str = None,
  869. undo_preprocessing_func: Callable[[torch.Tensor], np.ndarray] = undo_image_preprocessing,
  870. box_thickness: int = 2, image_scale: float = 1., gt_alpha: float = .4):
  871. """
  872. A helper function to visualize detections predicted by a network:
  873. saves images into a given path with a name that is {batch_name}_{imade_idx_in_the_batch}.jpg, one batch per call.
  874. Colors are generated on the fly: uniformly sampled from color wheel to support all given classes.
  875. Adjustable:
  876. * Ground truth box transparency;
  877. * Box width;
  878. * Image size (larger or smaller than what's provided)
  879. :param image_tensor: rgb images, (B, H, W, 3)
  880. :param pred_boxes: boxes after NMS for each image in a batch, each (Num_boxes, 6),
  881. values on dim 1 are: x1, y1, x2, y2, confidence, class
  882. :param target_boxes: (Num_targets, 6), values on dim 1 are: image id in a batch, class, x y w h
  883. (coordinates scaled to [0, 1])
  884. :param batch_name: id of the current batch to use for image naming
  885. :param class_names: names of all classes, each on its own index
  886. :param checkpoint_dir: a path where images with boxes will be saved. if None, the result images will
  887. be returns as a list of numpy image arrays
  888. :param undo_preprocessing_func: a function to convert preprocessed images tensor into a batch of cv2-like images
  889. :param box_thickness: box line thickness in px
  890. :param image_scale: scale of an image w.r.t. given image size,
  891. e.g. incoming images are (320x320), use scale = 2. to preview in (640x640)
  892. :param gt_alpha: a value in [0., 1.] transparency on ground truth boxes,
  893. 0 for invisible, 1 for fully opaque
  894. """
  895. image_np = undo_preprocessing_func(image_tensor.detach())
  896. targets = DetectionVisualization._scaled_ccwh_to_xyxy(target_boxes.detach().cpu().numpy(), *image_np.shape[1:3],
  897. image_scale)
  898. out_images = []
  899. for i in range(image_np.shape[0]):
  900. preds = pred_boxes[i].detach().cpu().numpy() if pred_boxes[i] is not None else np.empty((0, 6))
  901. targets_cur = targets[targets[:, 0] == i]
  902. image_name = '_'.join([str(batch_name), str(i)])
  903. res_image = DetectionVisualization._visualize_image(image_np[i], preds, targets_cur, class_names, box_thickness, gt_alpha, image_scale, checkpoint_dir, image_name)
  904. if res_image is not None:
  905. out_images.append(res_image)
  906. return out_images
  907. class Anchors(nn.Module):
  908. """
  909. A wrapper function to hold the anchors used by detection models such as Yolo
  910. """
  911. def __init__(self, anchors_list: List[List], strides: List[int]):
  912. """
  913. :param anchors_list: of the shape [[w1,h1,w2,h2,w3,h3], [w4,h4,w5,h5,w6,h6] .... where each sublist holds
  914. the width and height of the anchors of a specific detection layer.
  915. i.e. for a model with 3 detection layers, each containing 5 anchors the format will be a of 3 sublists of 10 numbers each
  916. The width and height are in pixels (not relative to image size)
  917. :param strides: a list containing the stride of the layers from which the detection heads are fed.
  918. i.e. if the firs detection head is connected to the backbone after the input dimensions were reduces by 8, the first number will be 8
  919. """
  920. super().__init__()
  921. self._check_all_lists(anchors_list)
  922. self._check_all_len_equal_and_even(anchors_list)
  923. self._stride = nn.Parameter(torch.Tensor(strides).float(), requires_grad=False)
  924. anchors = torch.Tensor(anchors_list).float().view(len(anchors_list), -1, 2)
  925. self._anchors = nn.Parameter(anchors / self._stride.view(-1, 1, 1), requires_grad=False)
  926. self._anchor_grid = nn.Parameter(anchors.clone().view(len(anchors_list), 1, -1, 1, 1, 2), requires_grad=False)
  927. @staticmethod
  928. def _check_all_lists(anchors: list) -> bool:
  929. for a in anchors:
  930. if not isinstance(a, (list, ListConfig)):
  931. raise RuntimeError('All objects of anchors_list must be lists')
  932. @staticmethod
  933. def _check_all_len_equal_and_even(anchors: list) -> bool:
  934. len_of_first = len(anchors[0])
  935. for a in anchors:
  936. if len(a) % 2 == 1 or len(a) != len_of_first:
  937. raise RuntimeError('All objects of anchors_list must be of the same even length')
  938. @property
  939. def stride(self) -> nn.Parameter:
  940. return self._stride
  941. @property
  942. def anchors(self) -> nn.Parameter:
  943. return self._anchors
  944. @property
  945. def anchor_grid(self) -> nn.Parameter:
  946. return self._anchor_grid
  947. @property
  948. def detection_layers_num(self) -> int:
  949. return self._anchors.shape[0]
  950. @property
  951. def num_anchors(self) -> int:
  952. return self._anchors.shape[1]
Tip!

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

Comments

Loading...