anchor_generator.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # The code is based on
  15. # https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/anchor_generator.py
  16. import math
  17. import paddle
  18. import paddle.nn as nn
  19. import numpy as np
  20. from ppdet.core.workspace import register
  21. __all__ = ['AnchorGenerator', 'RetinaAnchorGenerator', 'S2ANetAnchorGenerator']
  22. @register
  23. class AnchorGenerator(nn.Layer):
  24. """
  25. Generate anchors according to the feature maps
  26. Args:
  27. anchor_sizes (list[float] | list[list[float]]): The anchor sizes at
  28. each feature point. list[float] means all feature levels share the
  29. same sizes. list[list[float]] means the anchor sizes for
  30. each level. The sizes stand for the scale of input size.
  31. aspect_ratios (list[float] | list[list[float]]): The aspect ratios at
  32. each feature point. list[float] means all feature levels share the
  33. same ratios. list[list[float]] means the aspect ratios for
  34. each level.
  35. strides (list[float]): The strides of feature maps which generate
  36. anchors
  37. offset (float): The offset of the coordinate of anchors, default 0.
  38. """
  39. def __init__(self,
  40. anchor_sizes=[32, 64, 128, 256, 512],
  41. aspect_ratios=[0.5, 1.0, 2.0],
  42. strides=[16.0],
  43. variance=[1.0, 1.0, 1.0, 1.0],
  44. offset=0.):
  45. super(AnchorGenerator, self).__init__()
  46. self.anchor_sizes = anchor_sizes
  47. self.aspect_ratios = aspect_ratios
  48. self.strides = strides
  49. self.variance = variance
  50. self.cell_anchors = self._calculate_anchors(len(strides))
  51. self.offset = offset
  52. def _broadcast_params(self, params, num_features):
  53. if not isinstance(params[0], (list, tuple)): # list[float]
  54. return [params] * num_features
  55. if len(params) == 1:
  56. return list(params) * num_features
  57. return params
  58. def generate_cell_anchors(self, sizes, aspect_ratios):
  59. anchors = []
  60. for size in sizes:
  61. area = size**2.0
  62. for aspect_ratio in aspect_ratios:
  63. w = math.sqrt(area / aspect_ratio)
  64. h = aspect_ratio * w
  65. x0, y0, x1, y1 = -w / 2.0, -h / 2.0, w / 2.0, h / 2.0
  66. anchors.append([x0, y0, x1, y1])
  67. return paddle.to_tensor(anchors, dtype='float32')
  68. def _calculate_anchors(self, num_features):
  69. sizes = self._broadcast_params(self.anchor_sizes, num_features)
  70. aspect_ratios = self._broadcast_params(self.aspect_ratios, num_features)
  71. cell_anchors = [
  72. self.generate_cell_anchors(s, a)
  73. for s, a in zip(sizes, aspect_ratios)
  74. ]
  75. [
  76. self.register_buffer(
  77. t.name, t, persistable=False) for t in cell_anchors
  78. ]
  79. return cell_anchors
  80. def _create_grid_offsets(self, size, stride, offset):
  81. grid_height, grid_width = size[0], size[1]
  82. shifts_x = paddle.arange(
  83. offset * stride, grid_width * stride, step=stride, dtype='float32')
  84. shifts_y = paddle.arange(
  85. offset * stride, grid_height * stride, step=stride, dtype='float32')
  86. shift_y, shift_x = paddle.meshgrid(shifts_y, shifts_x)
  87. shift_x = paddle.reshape(shift_x, [-1])
  88. shift_y = paddle.reshape(shift_y, [-1])
  89. return shift_x, shift_y
  90. def _grid_anchors(self, grid_sizes):
  91. anchors = []
  92. for size, stride, base_anchors in zip(grid_sizes, self.strides,
  93. self.cell_anchors):
  94. shift_x, shift_y = self._create_grid_offsets(size, stride,
  95. self.offset)
  96. shifts = paddle.stack((shift_x, shift_y, shift_x, shift_y), axis=1)
  97. shifts = paddle.reshape(shifts, [-1, 1, 4])
  98. base_anchors = paddle.reshape(base_anchors, [1, -1, 4])
  99. anchors.append(paddle.reshape(shifts + base_anchors, [-1, 4]))
  100. return anchors
  101. def forward(self, input):
  102. grid_sizes = [paddle.shape(feature_map)[-2:] for feature_map in input]
  103. anchors_over_all_feature_maps = self._grid_anchors(grid_sizes)
  104. return anchors_over_all_feature_maps
  105. @property
  106. def num_anchors(self):
  107. """
  108. Returns:
  109. int: number of anchors at every pixel
  110. location, on that feature map.
  111. For example, if at every pixel we use anchors of 3 aspect
  112. ratios and 5 sizes, the number of anchors is 15.
  113. For FPN models, `num_anchors` on every feature map is the same.
  114. """
  115. return len(self.cell_anchors[0])
  116. @register
  117. class RetinaAnchorGenerator(AnchorGenerator):
  118. def __init__(self,
  119. octave_base_scale=4,
  120. scales_per_octave=3,
  121. aspect_ratios=[0.5, 1.0, 2.0],
  122. strides=[8.0, 16.0, 32.0, 64.0, 128.0],
  123. variance=[1.0, 1.0, 1.0, 1.0],
  124. offset=0.0):
  125. anchor_sizes = []
  126. for s in strides:
  127. anchor_sizes.append([
  128. s * octave_base_scale * 2**(i/scales_per_octave) \
  129. for i in range(scales_per_octave)])
  130. super(RetinaAnchorGenerator, self).__init__(
  131. anchor_sizes=anchor_sizes,
  132. aspect_ratios=aspect_ratios,
  133. strides=strides,
  134. variance=variance,
  135. offset=offset)
  136. @register
  137. class S2ANetAnchorGenerator(nn.Layer):
  138. """
  139. AnchorGenerator by paddle
  140. """
  141. def __init__(self, base_size, scales, ratios, scale_major=True, ctr=None):
  142. super(S2ANetAnchorGenerator, self).__init__()
  143. self.base_size = base_size
  144. self.scales = paddle.to_tensor(scales)
  145. self.ratios = paddle.to_tensor(ratios)
  146. self.scale_major = scale_major
  147. self.ctr = ctr
  148. self.base_anchors = self.gen_base_anchors()
  149. @property
  150. def num_base_anchors(self):
  151. return self.base_anchors.shape[0]
  152. def gen_base_anchors(self):
  153. w = self.base_size
  154. h = self.base_size
  155. if self.ctr is None:
  156. x_ctr = 0.5 * (w - 1)
  157. y_ctr = 0.5 * (h - 1)
  158. else:
  159. x_ctr, y_ctr = self.ctr
  160. h_ratios = paddle.sqrt(self.ratios)
  161. w_ratios = 1 / h_ratios
  162. if self.scale_major:
  163. ws = (w * w_ratios[:] * self.scales[:]).reshape([-1])
  164. hs = (h * h_ratios[:] * self.scales[:]).reshape([-1])
  165. else:
  166. ws = (w * self.scales[:] * w_ratios[:]).reshape([-1])
  167. hs = (h * self.scales[:] * h_ratios[:]).reshape([-1])
  168. base_anchors = paddle.stack(
  169. [
  170. x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1),
  171. x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1)
  172. ],
  173. axis=-1)
  174. base_anchors = paddle.round(base_anchors)
  175. return base_anchors
  176. def _meshgrid(self, x, y, row_major=True):
  177. yy, xx = paddle.meshgrid(y, x)
  178. yy = yy.reshape([-1])
  179. xx = xx.reshape([-1])
  180. if row_major:
  181. return xx, yy
  182. else:
  183. return yy, xx
  184. def forward(self, featmap_size, stride=16):
  185. # featmap_size*stride project it to original area
  186. feat_h = featmap_size[0]
  187. feat_w = featmap_size[1]
  188. shift_x = paddle.arange(0, feat_w, 1, 'int32') * stride
  189. shift_y = paddle.arange(0, feat_h, 1, 'int32') * stride
  190. shift_xx, shift_yy = self._meshgrid(shift_x, shift_y)
  191. shifts = paddle.stack([shift_xx, shift_yy, shift_xx, shift_yy], axis=-1)
  192. all_anchors = self.base_anchors[:, :] + shifts[:, :]
  193. all_anchors = all_anchors.cast(paddle.float32).reshape(
  194. [feat_h * feat_w, 4])
  195. all_anchors = self.rect2rbox(all_anchors)
  196. return all_anchors
  197. def valid_flags(self, featmap_size, valid_size):
  198. feat_h, feat_w = featmap_size
  199. valid_h, valid_w = valid_size
  200. assert valid_h <= feat_h and valid_w <= feat_w
  201. valid_x = paddle.zeros([feat_w], dtype='int32')
  202. valid_y = paddle.zeros([feat_h], dtype='int32')
  203. valid_x[:valid_w] = 1
  204. valid_y[:valid_h] = 1
  205. valid_xx, valid_yy = self._meshgrid(valid_x, valid_y)
  206. valid = valid_xx & valid_yy
  207. valid = paddle.reshape(valid, [-1, 1])
  208. valid = paddle.expand(valid, [-1, self.num_base_anchors]).reshape([-1])
  209. return valid
  210. def rect2rbox(self, bboxes):
  211. """
  212. :param bboxes: shape (L, 4) (xmin, ymin, xmax, ymax)
  213. :return: dbboxes: shape (L, 5) (x_ctr, y_ctr, w, h, angle)
  214. """
  215. x1, y1, x2, y2 = paddle.split(bboxes, 4, axis=-1)
  216. x_ctr = (x1 + x2) / 2.0
  217. y_ctr = (y1 + y2) / 2.0
  218. edges1 = paddle.abs(x2 - x1)
  219. edges2 = paddle.abs(y2 - y1)
  220. rbox_w = paddle.maximum(edges1, edges2)
  221. rbox_h = paddle.minimum(edges1, edges2)
  222. # set angle
  223. inds = edges1 < edges2
  224. inds = paddle.cast(inds, paddle.float32)
  225. rboxes_angle = inds * np.pi / 2.0
  226. rboxes = paddle.concat(
  227. (x_ctr, y_ctr, rbox_w, rbox_h, rboxes_angle), axis=-1)
  228. return rboxes