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 48 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
  1. import math
  2. import os
  3. import pathlib
  4. from abc import ABC, abstractmethod
  5. from enum import Enum
  6. from typing import Callable, List, Union, Tuple, Optional, Dict
  7. import cv2
  8. from torch.utils.data._utils.collate import default_collate
  9. import matplotlib.pyplot as plt
  10. import torch
  11. import torchvision
  12. import numpy as np
  13. from torch import nn
  14. from omegaconf import ListConfig
  15. class DetectionTargetsFormat(Enum):
  16. """
  17. Enum class for the different detection output formats
  18. When NORMALIZED is not specified- the type refers to unnormalized image coordinates (of the bboxes).
  19. For example:
  20. LABEL_NORMALIZED_XYXY means [class_idx,x1,y1,x2,y2]
  21. """
  22. LABEL_XYXY = "LABEL_XYXY"
  23. XYXY_LABEL = "XYXY_LABEL"
  24. LABEL_NORMALIZED_XYXY = "LABEL_NORMALIZED_XYXY"
  25. NORMALIZED_XYXY_LABEL = "NORMALIZED_XYXY_LABEL"
  26. LABEL_CXCYWH = "LABEL_CXCYWH"
  27. CXCYWH_LABEL = "CXCYWH_LABEL"
  28. LABEL_NORMALIZED_CXCYWH = "LABEL_NORMALIZED_CXCYWH"
  29. NORMALIZED_CXCYWH_LABEL = "NORMALIZED_CXCYWH_LABEL"
  30. def _set_batch_labels_index(labels_batch):
  31. for i, labels in enumerate(labels_batch):
  32. labels[:, 0] = i
  33. return labels_batch
  34. def convert_xywh_bbox_to_xyxy(input_bbox: torch.Tensor):
  35. """
  36. Converts bounding box format from [x, y, w, h] to [x1, y1, x2, y2]
  37. :param input_bbox: input bbox either 2-dimensional (for all boxes of a single image) or 3-dimensional (for
  38. boxes of a batch of images)
  39. :return: Converted bbox in same dimensions as the original
  40. """
  41. need_squeeze = False
  42. # the input is always processed as a batch. in case it not a batch, it is unsqueezed, process and than squeeze back.
  43. if input_bbox.dim() < 3:
  44. need_squeeze = True
  45. input_bbox = input_bbox.unsqueeze(0)
  46. converted_bbox = torch.zeros_like(input_bbox) if isinstance(input_bbox, torch.Tensor) else np.zeros_like(input_bbox)
  47. converted_bbox[:, :, 0] = input_bbox[:, :, 0] - input_bbox[:, :, 2] / 2
  48. converted_bbox[:, :, 1] = input_bbox[:, :, 1] - input_bbox[:, :, 3] / 2
  49. converted_bbox[:, :, 2] = input_bbox[:, :, 0] + input_bbox[:, :, 2] / 2
  50. converted_bbox[:, :, 3] = input_bbox[:, :, 1] + input_bbox[:, :, 3] / 2
  51. # squeeze back if needed
  52. if need_squeeze:
  53. converted_bbox = converted_bbox[0]
  54. return converted_bbox
  55. 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):
  56. """
  57. Internal function for the use of calculate_bbox_iou_matrix and calculate_bbox_iou_elementwise functions
  58. DO NOT CALL THIS FUNCTIONS DIRECTLY - use one of the functions mentioned above
  59. """
  60. # Intersection area
  61. intersection_area = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
  62. (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
  63. # Union Area
  64. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
  65. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
  66. union_area = w1 * h1 + w2 * h2 - intersection_area + eps
  67. iou = intersection_area / union_area # iou
  68. if GIoU or DIoU or CIoU:
  69. cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
  70. ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
  71. # Generalized IoU https://arxiv.org/pdf/1902.09630.pdf
  72. if GIoU:
  73. c_area = cw * ch + eps # convex area
  74. iou -= (c_area - union_area) / c_area # GIoU
  75. # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  76. if DIoU or CIoU:
  77. # convex diagonal squared
  78. c2 = cw ** 2 + ch ** 2 + eps
  79. # centerpoint distance squared
  80. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
  81. if DIoU:
  82. iou -= rho2 / c2 # DIoU
  83. elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  84. v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
  85. with torch.no_grad():
  86. alpha = v / ((1 + eps) - iou + v)
  87. iou -= (rho2 / c2 + v * alpha) # CIoU
  88. return iou
  89. def calculate_bbox_iou_matrix(box1, box2, x1y1x2y2=True, GIoU: bool = False, DIoU=False, CIoU=False, eps=1e-9):
  90. """
  91. calculate iou matrix containing the iou of every couple iuo(i,j) where i is in box1 and j is in box2
  92. :param box1: a 2D tensor of boxes (shape N x 4)
  93. :param box2: a 2D tensor of boxes (shape M x 4)
  94. :param x1y1x2y2: boxes format is x1y1x2y2 (True) or xywh where xy is the center (False)
  95. :return: a 2D iou matrix (shape NxM)
  96. """
  97. if box1.dim() > 1:
  98. box1 = box1.T
  99. # Get the coordinates of bounding boxes
  100. if x1y1x2y2: # x1, y1, x2, y2 = box1
  101. b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
  102. b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]
  103. else: # x, y, w, h = box1
  104. b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
  105. b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
  106. b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
  107. b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
  108. b1_x1, b1_y1, b1_x2, b1_y2 = b1_x1.unsqueeze(1), b1_y1.unsqueeze(1), b1_x2.unsqueeze(1), b1_y2.unsqueeze(1)
  109. return _iou(CIoU, DIoU, GIoU, b1_x1, b1_x2, b1_y1, b1_y2, b2_x1, b2_x2, b2_y1, b2_y2, eps)
  110. def calc_bbox_iou_matrix(pred: torch.Tensor):
  111. """
  112. calculate iou for every pair of boxes in the boxes vector
  113. :param pred: a 3-dimensional tensor containing all boxes for a batch of images [N, num_boxes, 4], where
  114. each box format is [x1,y1,x2,y2]
  115. :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
  116. """
  117. box = pred[:, :, :4] #
  118. b1_x1, b1_y1 = box[:, :, 0].unsqueeze(1), box[:, :, 1].unsqueeze(1)
  119. b1_x2, b1_y2 = box[:, :, 2].unsqueeze(1), box[:, :, 3].unsqueeze(1)
  120. b2_x1 = b1_x1.transpose(2, 1)
  121. b2_x2 = b1_x2.transpose(2, 1)
  122. b2_y1 = b1_y1.transpose(2, 1)
  123. b2_y2 = b1_y2.transpose(2, 1)
  124. intersection_area = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
  125. (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
  126. # Union Area
  127. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
  128. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
  129. union_area = (w1 * h1 + 1e-16) + w2 * h2 - intersection_area
  130. ious = intersection_area / union_area
  131. return ious
  132. def change_bbox_bounds_for_image_size(boxes, img_shape):
  133. # CLIP BOUNDING XYXY BOUNDING BOXES TO IMAGE SHAPE (HEIGHT, WIDTH)
  134. boxes[:, [0, 2]] = boxes[:, [0, 2]].clamp(min=0, max=img_shape[1])
  135. boxes[:, [1, 3]] = boxes[:, [1, 3]].clamp(min=0, max=img_shape[0])
  136. return boxes
  137. class DetectionPostPredictionCallback(ABC, nn.Module):
  138. def __init__(self) -> None:
  139. super().__init__()
  140. @abstractmethod
  141. def forward(self, x, device: str):
  142. """
  143. :param x: the output of your model
  144. :param device: the device to move all output tensors into
  145. :return: a list with length batch_size, each item in the list is a detections
  146. with shape: nx6 (x1, y1, x2, y2, confidence, class) where x and y are in range [0,1]
  147. """
  148. raise NotImplementedError
  149. class IouThreshold(tuple, Enum):
  150. MAP_05 = (0.5, 0.5)
  151. MAP_05_TO_095 = (0.5, 0.95)
  152. def is_range(self):
  153. return self[0] != self[1]
  154. def to_tensor(self):
  155. if self.is_range():
  156. n_iou_thresh = int(round((self[1] - self[0]) / 0.05)) + 1
  157. return torch.linspace(self[0], self[1], n_iou_thresh)
  158. else:
  159. n_iou_thresh = 1
  160. return torch.tensor([self[0]])
  161. def box_iou(box1, box2):
  162. # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
  163. """
  164. Return intersection-over-union (Jaccard index) of boxes.
  165. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
  166. Arguments:
  167. box1 (Tensor[N, 4])
  168. box2 (Tensor[M, 4])
  169. Returns:
  170. iou (Tensor[N, M]): the NxM matrix containing the pairwise
  171. IoU values for every element in boxes1 and boxes2
  172. """
  173. def box_area(box):
  174. # box = 4xn
  175. return (box[2] - box[0]) * (box[3] - box[1])
  176. area1 = box_area(box1.T)
  177. area2 = box_area(box2.T)
  178. # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
  179. inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
  180. return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
  181. def non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6,
  182. multi_label_per_box: bool = True, with_confidence: bool = False):
  183. """
  184. Performs Non-Maximum Suppression (NMS) on inference results
  185. :param prediction: raw model prediction
  186. :param conf_thres: below the confidence threshold - prediction are discarded
  187. :param iou_thres: IoU threshold for the nms algorithm
  188. :param multi_label_per_box: whether to use re-use each box with all possible labels
  189. (instead of the maximum confidence all confidences above threshold
  190. will be sent to NMS); by default is set to True
  191. :param with_confidence: whether to multiply objectness score with class score.
  192. usually valid for Yolo models only.
  193. :return: (x1, y1, x2, y2, object_conf, class_conf, class)
  194. Returns:
  195. detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
  196. """
  197. candidates_above_thres = prediction[..., 4] > conf_thres # filter by confidence
  198. output = [None] * prediction.shape[0]
  199. for image_idx, pred in enumerate(prediction):
  200. pred = pred[candidates_above_thres[image_idx]] # confident
  201. if not pred.shape[0]: # If none remain process next image
  202. continue
  203. if with_confidence:
  204. pred[:, 5:] *= pred[:, 4:5] # multiply objectness score with class score
  205. box = convert_xywh_bbox_to_xyxy(pred[:, :4]) # xywh to xyxy
  206. # Detections matrix nx6 (xyxy, conf, cls)
  207. if multi_label_per_box: # try for all good confidence classes
  208. i, j = (pred[:, 5:] > conf_thres).nonzero(as_tuple=False).T
  209. pred = torch.cat((box[i], pred[i, j + 5, None], j[:, None].float()), 1)
  210. else: # best class only
  211. conf, j = pred[:, 5:].max(1, keepdim=True)
  212. pred = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
  213. if not pred.shape[0]: # If none remain process next image
  214. continue
  215. # Apply torch batched NMS algorithm
  216. boxes, scores, cls_idx = pred[:, :4], pred[:, 4], pred[:, 5]
  217. idx_to_keep = torchvision.ops.boxes.batched_nms(boxes, scores, cls_idx, iou_thres)
  218. output[image_idx] = pred[idx_to_keep]
  219. return output
  220. def matrix_non_max_suppression(pred, conf_thres: float = 0.1, kernel: str = 'gaussian',
  221. sigma: float = 3.0, max_num_of_detections: int = 500):
  222. """Performs Matrix Non-Maximum Suppression (NMS) on inference results
  223. https://arxiv.org/pdf/1912.04488.pdf
  224. :param pred: raw model prediction (in test mode) - a Tensor of shape [batch, num_predictions, 85]
  225. where each item format is (x, y, w, h, object_conf, class_conf, ... 80 classes score ...)
  226. :param conf_thres: below the confidence threshold - prediction are discarded
  227. :param kernel: type of kernel to use ['gaussian', 'linear']
  228. :param sigma: sigma for the gussian kernel
  229. :param max_num_of_detections: maximum number of boxes to output
  230. :return: list of (x1, y1, x2, y2, object_conf, class_conf, class)
  231. Returns:
  232. detections list with shape: (x1, y1, x2, y2, conf, cls)
  233. """
  234. # MULTIPLY CONF BY CLASS CONF TO GET COMBINED CONFIDENCE
  235. class_conf, class_pred = pred[:, :, 5:].max(2)
  236. pred[:, :, 4] *= class_conf
  237. # BOX (CENTER X, CENTER Y, WIDTH, HEIGHT) TO (X1, Y1, X2, Y2)
  238. pred[:, :, :4] = convert_xywh_bbox_to_xyxy(pred[:, :, :4])
  239. # DETECTIONS ORDERED AS (x1y1x2y2, obj_conf, class_conf, class_pred)
  240. pred = torch.cat((pred[:, :, :5], class_pred.unsqueeze(2)), 2)
  241. # SORT DETECTIONS BY DECREASING CONFIDENCE SCORES
  242. sort_ind = (-pred[:, :, 4]).argsort()
  243. pred = torch.stack([pred[i, sort_ind[i]] for i in range(pred.shape[0])])[:, 0:max_num_of_detections]
  244. ious = calc_bbox_iou_matrix(pred)
  245. ious = ious.triu(1)
  246. # CREATE A LABELS MASK, WE WANT ONLY BOXES WITH THE SAME LABEL TO AFFECT EACH OTHER
  247. labels = pred[:, :, 5:]
  248. labeles_matrix = (labels == labels.transpose(2, 1)).float().triu(1)
  249. ious *= labeles_matrix
  250. ious_cmax, _ = ious.max(1)
  251. ious_cmax = ious_cmax.unsqueeze(2).repeat(1, 1, max_num_of_detections)
  252. if kernel == 'gaussian':
  253. decay_matrix = torch.exp(-1 * sigma * (ious ** 2))
  254. compensate_matrix = torch.exp(-1 * sigma * (ious_cmax ** 2))
  255. decay, _ = (decay_matrix / compensate_matrix).min(dim=1)
  256. else:
  257. decay = (1 - ious) / (1 - ious_cmax)
  258. decay, _ = decay.min(dim=1)
  259. pred[:, :, 4] *= decay
  260. output = [pred[i, pred[i, :, 4] > conf_thres] for i in range(pred.shape[0])]
  261. return output
  262. class NMS_Type(str, Enum):
  263. """
  264. Type of non max suppression algorithm that can be used for post processing detection
  265. """
  266. ITERATIVE = 'iterative'
  267. MATRIX = 'matrix'
  268. def undo_image_preprocessing(im_tensor: torch.Tensor) -> np.ndarray:
  269. """
  270. :param im_tensor: images in a batch after preprocessing for inference, RGB, (B, C, H, W)
  271. :return: images in a batch in cv2 format, BGR, (B, H, W, C)
  272. """
  273. im_np = im_tensor.cpu().numpy()
  274. im_np = im_np[:, ::-1, :, :].transpose(0, 2, 3, 1)
  275. im_np *= 255.
  276. return np.ascontiguousarray(im_np, dtype=np.uint8)
  277. class DetectionVisualization:
  278. @staticmethod
  279. def _generate_color_mapping(num_classes: int) -> List[Tuple[int]]:
  280. """
  281. Generate a unique BGR color for each class
  282. """
  283. cmap = plt.cm.get_cmap('gist_rainbow', num_classes)
  284. colors = [cmap(i, bytes=True)[:3][::-1] for i in range(num_classes)]
  285. return [tuple(int(v) for v in c) for c in colors]
  286. @staticmethod
  287. def _draw_box_title(color_mapping: List[Tuple[int]], class_names: List[str], box_thickness: int,
  288. image_np: np.ndarray, x1: int, y1: int, x2: int, y2: int, class_id: int,
  289. pred_conf: float = None, is_target: bool = False):
  290. color = color_mapping[class_id]
  291. class_name = class_names[class_id]
  292. # Draw the box
  293. image_np = cv2.rectangle(image_np, (x1, y1), (x2, y2), color, box_thickness)
  294. # Caption with class name and confidence if given
  295. text_color = (255, 255, 255) # white
  296. if is_target:
  297. title = f'[GT] {class_name}'
  298. if not is_target:
  299. title = f'[Pred] {class_name} {str(round(pred_conf, 2)) if pred_conf is not None else ""}'
  300. image_np = cv2.rectangle(image_np, (x1, y1 - 15), (x1 + len(title) * 10, y1), color, cv2.FILLED)
  301. image_np = cv2.putText(image_np, title, (x1, y1 - box_thickness), 2, .5, text_color, 1, lineType=cv2.LINE_AA)
  302. return image_np
  303. @staticmethod
  304. def _visualize_image(image_np: np.ndarray, pred_boxes: np.ndarray, target_boxes: np.ndarray,
  305. class_names: List[str], box_thickness: int, gt_alpha: float, image_scale: float,
  306. checkpoint_dir: str, image_name: str):
  307. image_np = cv2.resize(image_np, (0, 0), fx=image_scale, fy=image_scale, interpolation=cv2.INTER_NEAREST)
  308. color_mapping = DetectionVisualization._generate_color_mapping(len(class_names))
  309. # Draw predictions
  310. pred_boxes[:, :4] *= image_scale
  311. for box in pred_boxes:
  312. image_np = DetectionVisualization._draw_box_title(color_mapping, class_names, box_thickness,
  313. image_np, *box[:4].astype(int),
  314. class_id=int(box[5]), pred_conf=box[4])
  315. # Draw ground truths
  316. target_boxes_image = np.zeros_like(image_np, np.uint8)
  317. for box in target_boxes:
  318. target_boxes_image = DetectionVisualization._draw_box_title(color_mapping, class_names, box_thickness,
  319. target_boxes_image, *box[2:],
  320. class_id=box[1], is_target=True)
  321. # Transparent overlay of ground truth boxes
  322. mask = target_boxes_image.astype(bool)
  323. image_np[mask] = cv2.addWeighted(image_np, 1 - gt_alpha, target_boxes_image, gt_alpha, 0)[mask]
  324. if checkpoint_dir is None:
  325. return image_np
  326. else:
  327. pathlib.Path(checkpoint_dir).mkdir(parents=True, exist_ok=True)
  328. cv2.imwrite(os.path.join(checkpoint_dir, str(image_name) + '.jpg'), image_np)
  329. @staticmethod
  330. def _scaled_ccwh_to_xyxy(target_boxes: np.ndarray, h: int, w: int, image_scale: float) -> np.ndarray:
  331. """
  332. Modifies target_boxes inplace
  333. :param target_boxes: (c1, c2, w, h) boxes in [0, 1] range
  334. :param h: image height
  335. :param w: image width
  336. :param image_scale: desired scale for the boxes w.r.t. w and h
  337. :return: targets in (x1, y1, x2, y2) format
  338. in range [0, w * self.image_scale] [0, h * self.image_scale]
  339. """
  340. # unscale
  341. target_boxes[:, 2:] *= np.array([[w, h, w, h]])
  342. # x1 = c1 - w // 2; y1 = c2 - h // 2
  343. target_boxes[:, 2] -= target_boxes[:, 4] // 2
  344. target_boxes[:, 3] -= target_boxes[:, 5] // 2
  345. # x2 = w + x1; y2 = h + y1
  346. target_boxes[:, 4] += target_boxes[:, 2]
  347. target_boxes[:, 5] += target_boxes[:, 3]
  348. target_boxes[:, 2:] *= image_scale
  349. target_boxes = target_boxes.astype(int)
  350. return target_boxes
  351. @staticmethod
  352. def visualize_batch(image_tensor: torch.Tensor, pred_boxes: List[torch.Tensor], target_boxes: torch.Tensor,
  353. batch_name: Union[int, str], class_names: List[str], checkpoint_dir: str = None,
  354. undo_preprocessing_func: Callable[[torch.Tensor], np.ndarray] = undo_image_preprocessing,
  355. box_thickness: int = 2, image_scale: float = 1., gt_alpha: float = .4):
  356. """
  357. A helper function to visualize detections predicted by a network:
  358. saves images into a given path with a name that is {batch_name}_{imade_idx_in_the_batch}.jpg, one batch per call.
  359. Colors are generated on the fly: uniformly sampled from color wheel to support all given classes.
  360. Adjustable:
  361. * Ground truth box transparency;
  362. * Box width;
  363. * Image size (larger or smaller than what's provided)
  364. :param image_tensor: rgb images, (B, H, W, 3)
  365. :param pred_boxes: boxes after NMS for each image in a batch, each (Num_boxes, 6),
  366. values on dim 1 are: x1, y1, x2, y2, confidence, class
  367. :param target_boxes: (Num_targets, 6), values on dim 1 are: image id in a batch, class, x y w h
  368. (coordinates scaled to [0, 1])
  369. :param batch_name: id of the current batch to use for image naming
  370. :param class_names: names of all classes, each on its own index
  371. :param checkpoint_dir: a path where images with boxes will be saved. if None, the result images will
  372. be returns as a list of numpy image arrays
  373. :param undo_preprocessing_func: a function to convert preprocessed images tensor into a batch of cv2-like images
  374. :param box_thickness: box line thickness in px
  375. :param image_scale: scale of an image w.r.t. given image size,
  376. e.g. incoming images are (320x320), use scale = 2. to preview in (640x640)
  377. :param gt_alpha: a value in [0., 1.] transparency on ground truth boxes,
  378. 0 for invisible, 1 for fully opaque
  379. """
  380. image_np = undo_preprocessing_func(image_tensor.detach())
  381. targets = DetectionVisualization._scaled_ccwh_to_xyxy(target_boxes.detach().cpu().numpy(), *image_np.shape[1:3],
  382. image_scale)
  383. out_images = []
  384. for i in range(image_np.shape[0]):
  385. preds = pred_boxes[i].detach().cpu().numpy() if pred_boxes[i] is not None else np.empty((0, 6))
  386. targets_cur = targets[targets[:, 0] == i]
  387. image_name = '_'.join([str(batch_name), str(i)])
  388. res_image = DetectionVisualization._visualize_image(image_np[i], preds, targets_cur, class_names, box_thickness, gt_alpha, image_scale,
  389. checkpoint_dir, image_name)
  390. if res_image is not None:
  391. out_images.append(res_image)
  392. return out_images
  393. class Anchors(nn.Module):
  394. """
  395. A wrapper function to hold the anchors used by detection models such as Yolo
  396. """
  397. def __init__(self, anchors_list: List[List], strides: List[int]):
  398. """
  399. :param anchors_list: of the shape [[w1,h1,w2,h2,w3,h3], [w4,h4,w5,h5,w6,h6] .... where each sublist holds
  400. the width and height of the anchors of a specific detection layer.
  401. 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
  402. The width and height are in pixels (not relative to image size)
  403. :param strides: a list containing the stride of the layers from which the detection heads are fed.
  404. 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
  405. """
  406. super().__init__()
  407. self.__anchors_list = anchors_list
  408. self.__strides = strides
  409. self._check_all_lists(anchors_list)
  410. self._check_all_len_equal_and_even(anchors_list)
  411. self._stride = nn.Parameter(torch.Tensor(strides).float(), requires_grad=False)
  412. anchors = torch.Tensor(anchors_list).float().view(len(anchors_list), -1, 2)
  413. self._anchors = nn.Parameter(anchors / self._stride.view(-1, 1, 1), requires_grad=False)
  414. self._anchor_grid = nn.Parameter(anchors.clone().view(len(anchors_list), 1, -1, 1, 1, 2), requires_grad=False)
  415. @staticmethod
  416. def _check_all_lists(anchors: list) -> bool:
  417. for a in anchors:
  418. if not isinstance(a, (list, ListConfig)):
  419. raise RuntimeError('All objects of anchors_list must be lists')
  420. @staticmethod
  421. def _check_all_len_equal_and_even(anchors: list) -> bool:
  422. len_of_first = len(anchors[0])
  423. for a in anchors:
  424. if len(a) % 2 == 1 or len(a) != len_of_first:
  425. raise RuntimeError('All objects of anchors_list must be of the same even length')
  426. @property
  427. def stride(self) -> nn.Parameter:
  428. return self._stride
  429. @property
  430. def anchors(self) -> nn.Parameter:
  431. return self._anchors
  432. @property
  433. def anchor_grid(self) -> nn.Parameter:
  434. return self._anchor_grid
  435. @property
  436. def detection_layers_num(self) -> int:
  437. return self._anchors.shape[0]
  438. @property
  439. def num_anchors(self) -> int:
  440. return self._anchors.shape[1]
  441. def __repr__(self):
  442. return f"anchors_list: {self.__anchors_list} strides: {self.__strides}"
  443. def xyxy2cxcywh(bboxes):
  444. """
  445. Transforms bboxes from xyxy format to centerized xy wh format
  446. :param bboxes: array, shaped (nboxes, 4)
  447. :return: modified bboxes
  448. """
  449. bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]
  450. bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]
  451. bboxes[:, 0] = bboxes[:, 0] + bboxes[:, 2] * 0.5
  452. bboxes[:, 1] = bboxes[:, 1] + bboxes[:, 3] * 0.5
  453. return bboxes
  454. def cxcywh2xyxy(bboxes):
  455. """
  456. Transforms bboxes from centerized xy wh format to xyxy format
  457. :param bboxes: array, shaped (nboxes, 4)
  458. :return: modified bboxes
  459. """
  460. bboxes[:, 1] = bboxes[:, 1] - bboxes[:, 3] * 0.5
  461. bboxes[:, 0] = bboxes[:, 0] - bboxes[:, 2] * 0.5
  462. bboxes[:, 3] = bboxes[:, 3] + bboxes[:, 1]
  463. bboxes[:, 2] = bboxes[:, 2] + bboxes[:, 0]
  464. return bboxes
  465. def get_mosaic_coordinate(mosaic_index, xc, yc, w, h, input_h, input_w):
  466. """
  467. Returns the mosaic coordinates of final mosaic image according to mosaic image index.
  468. :param mosaic_index: (int) mosaic image index
  469. :param xc: (int) center x coordinate of the entire mosaic grid.
  470. :param yc: (int) center y coordinate of the entire mosaic grid.
  471. :param w: (int) width of bbox
  472. :param h: (int) height of bbox
  473. :param input_h: (int) image input height (should be 1/2 of the final mosaic output image height).
  474. :param input_w: (int) image input width (should be 1/2 of the final mosaic output image width).
  475. :return: (x1, y1, x2, y2), (x1s, y1s, x2s, y2s) where (x1, y1, x2, y2) are the coordinates in the final mosaic
  476. output image, and (x1s, y1s, x2s, y2s) are the coordinates in the placed image.
  477. """
  478. # index0 to top left part of image
  479. if mosaic_index == 0:
  480. x1, y1, x2, y2 = max(xc - w, 0), max(yc - h, 0), xc, yc
  481. small_coord = w - (x2 - x1), h - (y2 - y1), w, h
  482. # index1 to top right part of image
  483. elif mosaic_index == 1:
  484. x1, y1, x2, y2 = xc, max(yc - h, 0), min(xc + w, input_w * 2), yc
  485. small_coord = 0, h - (y2 - y1), min(w, x2 - x1), h
  486. # index2 to bottom left part of image
  487. elif mosaic_index == 2:
  488. x1, y1, x2, y2 = max(xc - w, 0), yc, xc, min(input_h * 2, yc + h)
  489. small_coord = w - (x2 - x1), 0, w, min(y2 - y1, h)
  490. # index2 to bottom right part of image
  491. elif mosaic_index == 3:
  492. x1, y1, x2, y2 = xc, yc, min(xc + w, input_w * 2), min(input_h * 2, yc + h) # noqa
  493. small_coord = 0, 0, min(w, x2 - x1), min(y2 - y1, h)
  494. return (x1, y1, x2, y2), small_coord
  495. def adjust_box_anns(bbox, scale_ratio, padw, padh, w_max, h_max):
  496. """
  497. Adjusts the bbox annotations of rescaled, padded image.
  498. :param bbox: (np.array) bbox to modify.
  499. :param scale_ratio: (float) scale ratio between rescale output image and original one.
  500. :param padw: (int) width padding size.
  501. :param padh: (int) height padding size.
  502. :param w_max: (int) width border.
  503. :param h_max: (int) height border
  504. :return: modified bbox (np.array)
  505. """
  506. bbox[:, 0::2] = np.clip(bbox[:, 0::2] * scale_ratio + padw, 0, w_max)
  507. bbox[:, 1::2] = np.clip(bbox[:, 1::2] * scale_ratio + padh, 0, h_max)
  508. return bbox
  509. class DetectionCollateFN:
  510. """
  511. Collate function for Yolox training
  512. """
  513. def __call__(self, data) -> Tuple[torch.Tensor, torch.Tensor]:
  514. batch = default_collate(data)
  515. ims, targets = batch[0:2]
  516. return ims, self._format_targets(targets)
  517. def _format_targets(self, targets: torch.Tensor) -> torch.Tensor:
  518. nlabel = (targets.sum(dim=2) > 0).sum(dim=1) # number of label per image
  519. targets_merged = []
  520. for i in range(targets.shape[0]):
  521. targets_im = targets[i, :nlabel[i]]
  522. batch_column = targets.new_ones((targets_im.shape[0], 1)) * i
  523. targets_merged.append(torch.cat((batch_column, targets_im), 1))
  524. return torch.cat(targets_merged, 0)
  525. class CrowdDetectionCollateFN(DetectionCollateFN):
  526. """
  527. Collate function for Yolox training with additional_batch_items that includes crowd targets
  528. """
  529. def __call__(self, data) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, torch.Tensor]]:
  530. batch = default_collate(data)
  531. ims, targets, crowd_targets = batch[0:3]
  532. return ims, self._format_targets(targets), {"crowd_targets": self._format_targets(crowd_targets)}
  533. def compute_box_area(box: torch.Tensor) -> torch.Tensor:
  534. """Compute the area of one or many boxes.
  535. :param box: One or many boxes, shape = (4, ?), each box in format (x1, y1, x2, y2)
  536. Returns:
  537. Area of every box, shape = (1, ?)
  538. """
  539. # box = 4xn
  540. return (box[2] - box[0]) * (box[3] - box[1])
  541. def crowd_ioa(det_box: torch.Tensor, crowd_box: torch.Tensor) -> torch.Tensor:
  542. """
  543. Return intersection-over-detection_area of boxes, used for crowd ground truths.
  544. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
  545. Arguments:
  546. det_box (Tensor[N, 4])
  547. crowd_box (Tensor[M, 4])
  548. Returns:
  549. crowd_ioa (Tensor[N, M]): the NxM matrix containing the pairwise
  550. IoA values for every element in det_box and crowd_box
  551. """
  552. det_area = compute_box_area(det_box.T)
  553. # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
  554. inter = (torch.min(det_box[:, None, 2:], crowd_box[:, 2:]) - torch.max(det_box[:, None, :2], crowd_box[:, :2])) \
  555. .clamp(0).prod(2)
  556. return inter / det_area[:, None] # crowd_ioa = inter / det_area
  557. def compute_detection_matching(
  558. output: torch.Tensor,
  559. targets: torch.Tensor,
  560. height: int,
  561. width: int,
  562. iou_thresholds: torch.Tensor,
  563. denormalize_targets: bool,
  564. device: str,
  565. crowd_targets: Optional[torch.Tensor] = None,
  566. top_k: int = 100,
  567. return_on_cpu: bool = True,
  568. ) -> List[Tuple]:
  569. """
  570. Match predictions (NMS output) and the targets (ground truth) with respect to IoU and confidence score.
  571. :param output: list (of length batch_size) of Tensors of shape (num_predictions, 6)
  572. format: (x1, y1, x2, y2, confidence, class_label) where x1,y1,x2,y2 are according to image size
  573. :param targets: targets for all images of shape (total_num_targets, 6)
  574. format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1]
  575. :param height: dimensions of the image
  576. :param width: dimensions of the image
  577. :param iou_thresholds: Threshold to compute the mAP
  578. :param device: Device
  579. :param crowd_targets: crowd targets for all images of shape (total_num_crowd_targets, 6)
  580. format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1]
  581. :param top_k: Number of predictions to keep per class, ordered by confidence score
  582. :param denormalize_targets: If True, denormalize the targets and crowd_targets
  583. :param return_on_cpu: If True, the output will be returned on "CPU", otherwise it will be returned on "device"
  584. :return: list of the following tensors, for every image:
  585. :preds_matched: Tensor of shape (num_img_predictions, n_iou_thresholds)
  586. True when prediction (i) is matched with a target with respect to the (j)th IoU threshold
  587. :preds_to_ignore: Tensor of shape (num_img_predictions, n_iou_thresholds)
  588. True when prediction (i) is matched with a crowd target with respect to the (j)th IoU threshold
  589. :preds_scores: Tensor of shape (num_img_predictions), confidence score for every prediction
  590. :preds_cls: Tensor of shape (num_img_predictions), predicted class for every prediction
  591. :targets_cls: Tensor of shape (num_img_targets), ground truth class for every target
  592. """
  593. output = map(lambda tensor: None if tensor is None else tensor.to(device), output)
  594. targets, iou_thresholds = targets.to(device), iou_thresholds.to(device)
  595. # If crowd_targets is not provided, we patch it with an empty tensor
  596. crowd_targets = torch.zeros(size=(0, 6), device=device) if crowd_targets is None else crowd_targets.to(device)
  597. batch_metrics = []
  598. for img_i, img_preds in enumerate(output):
  599. # If img_preds is None (not prediction for this image), we patch it with an empty tensor
  600. img_preds = img_preds if img_preds is not None else torch.zeros(size=(0, 6), device=device)
  601. img_targets = targets[targets[:, 0] == img_i, 1:]
  602. img_crowd_targets = crowd_targets[crowd_targets[:, 0] == img_i, 1:]
  603. img_matching_tensors = compute_img_detection_matching(
  604. preds=img_preds,
  605. targets=img_targets,
  606. crowd_targets=img_crowd_targets,
  607. denormalize_targets=denormalize_targets,
  608. height=height,
  609. width=width,
  610. device=device,
  611. iou_thresholds=iou_thresholds,
  612. top_k=top_k,
  613. return_on_cpu=return_on_cpu
  614. )
  615. batch_metrics.append(img_matching_tensors)
  616. return batch_metrics
  617. def compute_img_detection_matching(
  618. preds: torch.Tensor,
  619. targets: torch.Tensor,
  620. crowd_targets: torch.Tensor,
  621. height: int,
  622. width: int,
  623. iou_thresholds: torch.Tensor,
  624. device: str,
  625. denormalize_targets: bool,
  626. top_k: int = 100,
  627. return_on_cpu: bool = True
  628. ) -> Tuple:
  629. """
  630. Match predictions (NMS output) and the targets (ground truth) with respect to IoU and confidence score
  631. for a given image.
  632. :param preds: Tensor of shape (num_img_predictions, 6)
  633. format: (x1, y1, x2, y2, confidence, class_label) where x1,y1,x2,y2 are according to image size
  634. :param targets: targets for this image of shape (num_img_targets, 6)
  635. format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1]
  636. :param height: dimensions of the image
  637. :param width: dimensions of the image
  638. :param iou_thresholds: Threshold to compute the mAP
  639. :param device:
  640. :param crowd_targets: crowd targets for all images of shape (total_num_crowd_targets, 6)
  641. format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1]
  642. :param top_k: Number of predictions to keep per class, ordered by confidence score
  643. :param device: Device
  644. :param denormalize_targets: If True, denormalize the targets and crowd_targets
  645. :param return_on_cpu: If True, the output will be returned on "CPU", otherwise it will be returned on "device"
  646. :return:
  647. :preds_matched: Tensor of shape (num_img_predictions, n_iou_thresholds)
  648. True when prediction (i) is matched with a target with respect to the (j)th IoU threshold
  649. :preds_to_ignore: Tensor of shape (num_img_predictions, n_iou_thresholds)
  650. True when prediction (i) is matched with a crowd target with respect to the (j)th IoU threshold
  651. :preds_scores: Tensor of shape (num_img_predictions), confidence score for every prediction
  652. :preds_cls: Tensor of shape (num_img_predictions), predicted class for every prediction
  653. :targets_cls: Tensor of shape (num_img_targets), ground truth class for every target
  654. """
  655. num_iou_thresholds = len(iou_thresholds)
  656. if preds is None or len(preds) == 0:
  657. if return_on_cpu:
  658. device = "cpu"
  659. preds_matched = torch.zeros((0, num_iou_thresholds), dtype=torch.bool, device=device)
  660. preds_to_ignore = torch.zeros((0, num_iou_thresholds), dtype=torch.bool, device=device)
  661. preds_scores = torch.tensor([], dtype=torch.float32, device=device)
  662. preds_cls = torch.tensor([], dtype=torch.float32, device=device)
  663. targets_cls = targets[:, 0].to(device=device)
  664. return preds_matched, preds_to_ignore, preds_scores, preds_cls, targets_cls
  665. preds_matched = torch.zeros(len(preds), num_iou_thresholds, dtype=torch.bool, device=device)
  666. targets_matched = torch.zeros(len(targets), num_iou_thresholds, dtype=torch.bool, device=device)
  667. preds_to_ignore = torch.zeros(len(preds), num_iou_thresholds, dtype=torch.bool, device=device)
  668. preds_cls, preds_box, preds_scores = preds[:, -1], preds[:, 0:4], preds[:, 4]
  669. targets_cls, targets_box = targets[:, 0], targets[:, 1:5]
  670. crowd_targets_cls, crowd_target_box = crowd_targets[:, 0], crowd_targets[:, 1:5]
  671. # Ignore all but the predictions that were top_k for their class
  672. preds_idx_to_use = get_top_k_idx_per_cls(preds_scores, preds_cls, top_k)
  673. preds_to_ignore[:, :] = True
  674. preds_to_ignore[preds_idx_to_use] = False
  675. if len(targets) > 0 or len(crowd_targets) > 0:
  676. # CHANGE bboxes TO FIT THE IMAGE SIZE
  677. change_bbox_bounds_for_image_size(preds, (height, width))
  678. # if target_format == "xywh":
  679. targets_box = convert_xywh_bbox_to_xyxy(targets_box) # cxcywh2xyxy
  680. crowd_target_box = convert_xywh_bbox_to_xyxy(crowd_target_box) # convert_xywh_bbox_to_xyxy
  681. if denormalize_targets:
  682. targets_box[:, [0, 2]] *= width
  683. targets_box[:, [1, 3]] *= height
  684. crowd_target_box[:, [0, 2]] *= width
  685. crowd_target_box[:, [1, 3]] *= height
  686. if len(targets) > 0:
  687. # shape = (n_preds x n_targets)
  688. iou = box_iou(preds_box[preds_idx_to_use], targets_box)
  689. # Fill IoU values at index (i, j) with 0 when the prediction (i) and target(j) are of different class
  690. # Filling with 0 is equivalent to ignore these values since with want IoU > iou_threshold > 0
  691. cls_mismatch = (preds_cls[preds_idx_to_use].view(-1, 1) != targets_cls.view(1, -1))
  692. iou[cls_mismatch] = 0
  693. # The matching priority is first detection confidence and then IoU value.
  694. # The detection is already sorted by confidence in NMS, so here for each prediction we order the targets by iou.
  695. sorted_iou, target_sorted = iou.sort(descending=True, stable=True)
  696. # Only iterate over IoU values higher than min threshold to speed up the process
  697. for pred_selected_i, target_sorted_i in (sorted_iou > iou_thresholds[0]).nonzero(as_tuple=False):
  698. # pred_selected_i and target_sorted_i are relative to filters/sorting, so we extract their absolute indexes
  699. pred_i = preds_idx_to_use[pred_selected_i]
  700. target_i = target_sorted[pred_selected_i, target_sorted_i]
  701. # Vector[j], True when IoU(pred_i, target_i) is above the (j)th threshold
  702. is_iou_above_threshold = sorted_iou[pred_selected_i, target_sorted_i] > iou_thresholds
  703. # Vector[j], True when both pred_i and target_i are not matched yet for the (j)th threshold
  704. are_candidates_free = torch.logical_and(~preds_matched[pred_i, :], ~targets_matched[target_i, :])
  705. # Vector[j], True when (pred_i, target_i) can be matched for the (j)th threshold
  706. are_candidates_good = torch.logical_and(is_iou_above_threshold, are_candidates_free)
  707. # For every threshold (j) where target_i and pred_i can be matched together ( are_candidates_good[j]==True )
  708. # fill the matching placeholders with True
  709. targets_matched[target_i, are_candidates_good] = True
  710. preds_matched[pred_i, are_candidates_good] = True
  711. # When all the targets are matched with a prediction for every IoU Threshold, stop.
  712. if targets_matched.all():
  713. break
  714. # Crowd targets can be matched with many predictions.
  715. # Therefore, for every prediction we just need to check if it has IoA large enough with any crowd target.
  716. if len(crowd_targets) > 0:
  717. # shape = (n_preds_to_use x n_crowd_targets)
  718. ioa = crowd_ioa(preds_box[preds_idx_to_use], crowd_target_box)
  719. # Fill IoA values at index (i, j) with 0 when the prediction (i) and target(j) are of different class
  720. # Filling with 0 is equivalent to ignore these values since with want IoA > threshold > 0
  721. cls_mismatch = (preds_cls[preds_idx_to_use].view(-1, 1) != crowd_targets_cls.view(1, -1))
  722. ioa[cls_mismatch] = 0
  723. # For each prediction, we keep it's highest score with any crowd target (of same class)
  724. # shape = (n_preds_to_use)
  725. best_ioa, _ = ioa.max(1)
  726. # If a prediction has IoA higher than threshold (with any target of same class), then there is a match
  727. # shape = (n_preds_to_use x iou_thresholds)
  728. is_matching_with_crowd = (best_ioa.view(-1, 1) > iou_thresholds.view(1, -1))
  729. preds_to_ignore[preds_idx_to_use] = torch.logical_or(preds_to_ignore[preds_idx_to_use], is_matching_with_crowd)
  730. if return_on_cpu:
  731. preds_matched = preds_matched.to("cpu")
  732. preds_to_ignore = preds_to_ignore.to("cpu")
  733. preds_scores = preds_scores.to("cpu")
  734. preds_cls = preds_cls.to("cpu")
  735. targets_cls = targets_cls.to("cpu")
  736. return preds_matched, preds_to_ignore, preds_scores, preds_cls, targets_cls
  737. def get_top_k_idx_per_cls(preds_scores: torch.Tensor, preds_cls: torch.Tensor, top_k: int):
  738. """Get the indexes of all the top k predictions for every class
  739. :param preds_scores: The confidence scores, vector of shape (n_pred)
  740. :param preds_cls: The predicted class, vector of shape (n_pred)
  741. :param top_k: Number of predictions to keep per class, ordered by confidence score
  742. :return top_k_idx: Indexes of the top k predictions. length <= (k * n_unique_class)
  743. """
  744. n_unique_cls = torch.max(preds_cls)
  745. mask = (preds_cls.view(-1, 1) == torch.arange(n_unique_cls + 1, device=preds_scores.device).view(1, -1))
  746. preds_scores_per_cls = preds_scores.view(-1, 1) * mask
  747. sorted_scores_per_cls, sorting_idx = preds_scores_per_cls.sort(0, descending=True)
  748. idx_with_satisfying_scores = sorted_scores_per_cls[:top_k, :].nonzero(as_tuple=False)
  749. top_k_idx = sorting_idx[idx_with_satisfying_scores.split(1, dim=1)]
  750. return top_k_idx.view(-1)
  751. def compute_detection_metrics(
  752. preds_matched: torch.Tensor,
  753. preds_to_ignore: torch.Tensor,
  754. preds_scores: torch.Tensor,
  755. preds_cls: torch.Tensor,
  756. targets_cls: torch.Tensor,
  757. device: str,
  758. recall_thresholds: Optional[torch.Tensor] = None,
  759. score_threshold: Optional[float] = 0.1,
  760. ) -> Tuple:
  761. """
  762. Compute the list of precision, recall, MaP and f1 for every recall IoU threshold and for every class.
  763. :param preds_matched: Tensor of shape (num_predictions, n_iou_thresholds)
  764. True when prediction (i) is matched with a target with respect to the (j)th IoU threshold
  765. :param preds_to_ignore Tensor of shape (num_predictions, n_iou_thresholds)
  766. True when prediction (i) is matched with a crowd target with respect to the (j)th IoU threshold
  767. :param preds_scores: Tensor of shape (num_predictions), confidence score for every prediction
  768. :param preds_cls: Tensor of shape (num_predictions), predicted class for every prediction
  769. :param targets_cls: Tensor of shape (num_targets), ground truth class for every target box to be detected
  770. :param recall_thresholds: Recall thresholds used to compute MaP.
  771. :param score_threshold: Minimum confidence score to consider a prediction for the computation of
  772. precision, recall and f1 (not MaP)
  773. :param device: Device
  774. :return:
  775. :ap, precision, recall, f1: Tensors of shape (n_class, nb_iou_thrs)
  776. :unique_classes: Vector with all unique target classes
  777. """
  778. preds_matched, preds_to_ignore = preds_matched.to(device), preds_to_ignore.to(device)
  779. preds_scores, preds_cls, targets_cls = preds_scores.to(device), preds_cls.to(device), targets_cls.to(device)
  780. recall_thresholds = torch.linspace(0, 1, 101, device=device) if recall_thresholds is None else recall_thresholds.to(device)
  781. unique_classes = torch.unique(targets_cls)
  782. n_class, nb_iou_thrs = len(unique_classes), preds_matched.shape[-1]
  783. ap = torch.zeros((n_class, nb_iou_thrs), device=device)
  784. precision = torch.zeros((n_class, nb_iou_thrs), device=device)
  785. recall = torch.zeros((n_class, nb_iou_thrs), device=device)
  786. for cls_i, cls in enumerate(unique_classes):
  787. cls_preds_idx, cls_targets_idx = (preds_cls == cls), (targets_cls == cls)
  788. cls_ap, cls_precision, cls_recall = compute_detection_metrics_per_cls(
  789. preds_matched=preds_matched[cls_preds_idx],
  790. preds_to_ignore=preds_to_ignore[cls_preds_idx],
  791. preds_scores=preds_scores[cls_preds_idx],
  792. n_targets=cls_targets_idx.sum(),
  793. recall_thresholds=recall_thresholds,
  794. score_threshold=score_threshold,
  795. device=device
  796. )
  797. ap[cls_i, :] = cls_ap
  798. precision[cls_i, :] = cls_precision
  799. recall[cls_i, :] = cls_recall
  800. f1 = 2 * precision * recall / (precision + recall + 1e-16)
  801. return ap, precision, recall, f1, unique_classes
  802. def compute_detection_metrics_per_cls(
  803. preds_matched: torch.Tensor,
  804. preds_to_ignore: torch.Tensor,
  805. preds_scores: torch.Tensor,
  806. n_targets: int,
  807. recall_thresholds: torch.Tensor,
  808. score_threshold: float,
  809. device: str,
  810. ):
  811. """
  812. Compute the list of precision, recall and MaP of a given class for every recall IoU threshold.
  813. :param preds_matched: Tensor of shape (num_predictions, n_iou_thresholds)
  814. True when prediction (i) is matched with a target
  815. with respect to the(j)th IoU threshold
  816. :param preds_to_ignore Tensor of shape (num_predictions, n_iou_thresholds)
  817. True when prediction (i) is matched with a crowd target
  818. with respect to the (j)th IoU threshold
  819. :param preds_scores: Tensor of shape (num_predictions), confidence score for every prediction
  820. :param n_targets: Number of target boxes of this class
  821. :param recall_thresholds: Tensor of shape (max_n_rec_thresh) list of recall thresholds used to compute MaP
  822. :param score_threshold: Minimum confidence score to consider a prediction for the computation of
  823. precision and recall (not MaP)
  824. :param device: Device
  825. :return ap, precision, recall: Tensors of shape (nb_iou_thrs)
  826. """
  827. nb_iou_thrs = preds_matched.shape[-1]
  828. tps = preds_matched
  829. fps = torch.logical_and(torch.logical_not(preds_matched), torch.logical_not(preds_to_ignore))
  830. if len(tps) == 0:
  831. return 0, 0, torch.zeros(nb_iou_thrs, device=device)
  832. # Sort by decreasing score
  833. dtype = torch.uint8 if preds_scores.is_cuda and preds_scores.dtype is torch.bool else preds_scores.dtype
  834. sort_ind = torch.argsort(preds_scores.to(dtype), descending=True)
  835. tps = tps[sort_ind, :]
  836. fps = fps[sort_ind, :]
  837. preds_scores = preds_scores[sort_ind]
  838. # Rolling sum over the predictions
  839. rolling_tps = torch.cumsum(tps, axis=0, dtype=torch.float)
  840. rolling_fps = torch.cumsum(fps, axis=0, dtype=torch.float)
  841. rolling_recalls = rolling_tps / n_targets
  842. rolling_precisions = rolling_tps / (rolling_tps + rolling_fps + torch.finfo(torch.float64).eps)
  843. # Reversed cummax to only have decreasing values
  844. rolling_precisions = rolling_precisions.flip(0).cummax(0).values.flip(0)
  845. # ==================
  846. # RECALL & PRECISION
  847. # We want the rolling precision/recall at index i so that: preds_scores[i-1] >= score_threshold > preds_scores[i]
  848. # Note: torch.searchsorted works on increasing sequence and preds_scores is decreasing, so we work with "-"
  849. lowest_score_above_threshold = torch.searchsorted(-preds_scores, -score_threshold, right=False)
  850. if lowest_score_above_threshold == 0: # Here score_threshold > preds_scores[0], so no pred is above the threshold
  851. recall = 0
  852. precision = 0 # the precision is not really defined when no pred but we need to give it a value
  853. else:
  854. recall = rolling_recalls[lowest_score_above_threshold - 1]
  855. precision = rolling_precisions[lowest_score_above_threshold - 1]
  856. # ==================
  857. # AVERAGE PRECISION
  858. # shape = (nb_iou_thrs, n_recall_thresholds)
  859. recall_thresholds = recall_thresholds.view(1, -1).repeat(nb_iou_thrs, 1)
  860. # We want the index i so that: rolling_recalls[i-1] < recall_thresholds[k] <= rolling_recalls[i]
  861. # Note: when recall_thresholds[k] > max(rolling_recalls), i = len(rolling_recalls)
  862. # Note2: we work with transpose (.T) to apply torch.searchsorted on first dim instead of the last one
  863. recall_threshold_idx = torch.searchsorted(rolling_recalls.T, recall_thresholds, right=False).T
  864. # When recall_thresholds[k] > max(rolling_recalls), rolling_precisions[i] is not defined, and we want precision = 0
  865. rolling_precisions = torch.cat((rolling_precisions, torch.zeros(1, nb_iou_thrs, device=device)), dim=0)
  866. # shape = (n_recall_thresholds, nb_iou_thrs)
  867. sampled_precision_points = torch.gather(input=rolling_precisions, index=recall_threshold_idx, dim=0)
  868. # Average over the recall_thresholds
  869. ap = sampled_precision_points.mean(0)
  870. return ap, precision, recall
Tip!

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

Comments

Loading...