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

ssd_utils.py 6.8 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
  1. import itertools
  2. from math import sqrt
  3. import numpy as np
  4. import torch
  5. from torch.nn import functional as F
  6. from super_gradients.training.utils.detection_utils import non_max_suppression, NMS_Type, \
  7. matrix_non_max_suppression, DetectionPostPredictionCallback
  8. class DefaultBoxes(object):
  9. """
  10. Default Boxes, (aka: anchor boxes or priors boxes) used by SSD model
  11. """
  12. def __init__(self, fig_size, feat_size, steps, scales, aspect_ratios, scale_xy=0.1, scale_wh=0.2):
  13. self.feat_size = feat_size
  14. self.fig_size = fig_size
  15. self.scale_xy_ = scale_xy
  16. self.scale_wh_ = scale_wh
  17. # According to https://github.com/weiliu89/caffe
  18. # Calculation method slightly different from paper
  19. self.steps = steps
  20. self.scales = scales
  21. fk = fig_size / np.array(steps)
  22. self.aspect_ratios = aspect_ratios
  23. self.default_boxes = []
  24. # size of feature and number of feature
  25. for idx, sfeat in enumerate(self.feat_size):
  26. sk1 = scales[idx] / fig_size
  27. sk2 = scales[idx + 1] / fig_size
  28. sk3 = sqrt(sk1 * sk2)
  29. all_sizes = [(sk1, sk1), (sk3, sk3)]
  30. for alpha in aspect_ratios[idx]:
  31. w, h = sk1 * sqrt(alpha), sk1 / sqrt(alpha)
  32. all_sizes.append((w, h))
  33. all_sizes.append((h, w))
  34. for w, h in all_sizes:
  35. for i, j in itertools.product(range(sfeat), repeat=2):
  36. cx, cy = (j + 0.5) / fk[idx], (i + 0.5) / fk[idx]
  37. self.default_boxes.append((cx, cy, w, h))
  38. self.dboxes = torch.tensor(self.default_boxes, dtype=torch.float)
  39. self.dboxes.clamp_(min=0, max=1)
  40. # For IoU calculation
  41. self.dboxes_xyxy = self.dboxes.clone()
  42. self.dboxes_xyxy[:, 0] = self.dboxes[:, 0] - 0.5 * self.dboxes[:, 2]
  43. self.dboxes_xyxy[:, 1] = self.dboxes[:, 1] - 0.5 * self.dboxes[:, 3]
  44. self.dboxes_xyxy[:, 2] = self.dboxes[:, 0] + 0.5 * self.dboxes[:, 2]
  45. self.dboxes_xyxy[:, 3] = self.dboxes[:, 1] + 0.5 * self.dboxes[:, 3]
  46. @property
  47. def scale_xy(self):
  48. return self.scale_xy_
  49. @property
  50. def scale_wh(self):
  51. return self.scale_wh_
  52. def __call__(self, order="xyxy"):
  53. if order == "xyxy":
  54. return self.dboxes_xyxy
  55. if order == "xywh":
  56. return self.dboxes
  57. @staticmethod
  58. def dboxes300_coco():
  59. figsize = 300
  60. feat_size = [38, 19, 10, 5, 3, 1]
  61. steps = [8, 16, 32, 64, 100, 300]
  62. # use the scales here: https://github.com/amdegroot/ssd.pytorch/blob/master/data/config.py
  63. scales = [21, 45, 99, 153, 207, 261, 315]
  64. aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]]
  65. return DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)
  66. @staticmethod
  67. def dboxes300_coco_from19():
  68. """
  69. This dbox configuration is a bit different from the original dboxes300_coco
  70. It is suitable for a network taking the first skip connection from a 19x19 layer (instead of 38x38 in the
  71. original paper).
  72. This offers less coverage for small objects but more aspect ratios options to larger objects (the original
  73. paper supports object starting from size 21 pixels, while this config support objects starting from 60 pixels)
  74. """
  75. # https://github.com/qfgaohao/pytorch-ssd/blob/f61ab424d09bf3d4bb3925693579ac0a92541b0d/vision/ssd/config/mobilenetv1_ssd_config.py
  76. figsize = 300
  77. feat_size = [19, 10, 5, 3, 2, 1]
  78. steps = [16, 32, 64, 100, 150, 300]
  79. scales = [60, 105, 150, 195, 240, 285, 330]
  80. aspect_ratios = [[2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3]]
  81. return DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)
  82. @staticmethod
  83. def dboxes256_coco():
  84. figsize = 256
  85. feat_size = [32, 16, 8, 4, 2, 1]
  86. steps = [8, 16, 32, 64, 128, 256]
  87. # use the scales here: https://github.com/amdegroot/ssd.pytorch/blob/master/data/config.py
  88. scales = [18, 38, 84, 131, 1177, 223, 269]
  89. aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]]
  90. return DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)
  91. class SSDPostPredictCallback(DetectionPostPredictionCallback):
  92. """
  93. post prediction callback module to convert and filter predictions coming from the SSD net to a format
  94. used by all other detection models
  95. """
  96. def __init__(self, conf: float = 0.1, iou: float = 0.45, classes: list = None, max_predictions: int = 300,
  97. nms_type: NMS_Type = NMS_Type.ITERATIVE,
  98. dboxes: DefaultBoxes = DefaultBoxes.dboxes300_coco(), device='cuda'):
  99. """
  100. :param conf: confidence threshold
  101. :param iou: IoU threshold
  102. :param classes: (optional list) filter by class
  103. :param nms_type: the type of nms to use (iterative or matrix)
  104. """
  105. super(SSDPostPredictCallback, self).__init__()
  106. self.conf = conf
  107. self.iou = iou
  108. self.nms_type = nms_type
  109. self.classes = classes
  110. self.max_predictions = max_predictions
  111. self.dboxes_xywh = dboxes('xywh').to(device)
  112. self.scale_xy = dboxes.scale_xy
  113. self.scale_wh = dboxes.scale_wh
  114. self.img_size = dboxes.fig_size
  115. def forward(self, x, device=None):
  116. bboxes_in = x[0]
  117. scores_in = x[1]
  118. bboxes_in = bboxes_in.permute(0, 2, 1)
  119. scores_in = scores_in.permute(0, 2, 1)
  120. bboxes_in[:, :, :2] *= self.scale_xy
  121. bboxes_in[:, :, 2:] *= self.scale_wh
  122. # CONVERT RELATIVE LOCATIONS INTO ABSOLUTE LOCATION (OUTPUT LOCATIONS ARE RELATIVE TO THE DBOXES)
  123. bboxes_in[:, :, :2] = bboxes_in[:, :, :2] * self.dboxes_xywh[:, 2:] + self.dboxes_xywh[:, :2]
  124. bboxes_in[:, :, 2:] = bboxes_in[:, :, 2:].exp() * self.dboxes_xywh[:, 2:]
  125. scores_in = F.softmax(scores_in, dim=-1) # TODO softmax without first item?
  126. # REPLACE THE CONFIDENCE OF CLASS NONE WITH OBJECT CONFIDENCE
  127. # SSD DOES NOT OUTPUT OBJECT CONFIDENCE, REQUIRED FOR THE NMS
  128. scores_in[:, :, 0] = torch.max(scores_in[:, :, 1:], dim=2)[0]
  129. bboxes_in *= self.img_size
  130. nms_input = torch.cat((bboxes_in, scores_in), dim=2)
  131. if self.nms_type == NMS_Type.ITERATIVE:
  132. nms_res = non_max_suppression(nms_input, conf_thres=self.conf, iou_thres=self.iou,
  133. classes=self.classes)
  134. else:
  135. nms_res = matrix_non_max_suppression(nms_input, conf_thres=self.conf,
  136. max_num_of_detections=self.max_predictions)
  137. # NMS OUTPUT A 0-BASED CLASS LABEL, BUT SSD WORKS WITH 1-BASED CLASS LABEL
  138. for t in nms_res:
  139. if t is not None:
  140. t[:, 5] += 1
  141. return nms_res
Tip!

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

Comments

Loading...