anchor_generator.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. import math
  15. import paddle
  16. import paddle.nn as nn
  17. from paddlex.ppdet.core.workspace import register
  18. @register
  19. class AnchorGenerator(nn.Layer):
  20. """
  21. Generate anchors according to the feature maps
  22. Args:
  23. anchor_sizes (list[float] | list[list[float]]): The anchor sizes at
  24. each feature point. list[float] means all feature levels share the
  25. same sizes. list[list[float]] means the anchor sizes for
  26. each level. The sizes stand for the scale of input size.
  27. aspect_ratios (list[float] | list[list[float]]): The aspect ratios at
  28. each feature point. list[float] means all feature levels share the
  29. same ratios. list[list[float]] means the aspect ratios for
  30. each level.
  31. strides (list[float]): The strides of feature maps which generate
  32. anchors
  33. offset (float): The offset of the coordinate of anchors, default 0.
  34. """
  35. def __init__(self,
  36. anchor_sizes=[32, 64, 128, 256, 512],
  37. aspect_ratios=[0.5, 1.0, 2.0],
  38. strides=[16.0],
  39. variance=[1.0, 1.0, 1.0, 1.0],
  40. offset=0.):
  41. super(AnchorGenerator, self).__init__()
  42. self.anchor_sizes = anchor_sizes
  43. self.aspect_ratios = aspect_ratios
  44. self.strides = strides
  45. self.variance = variance
  46. self.cell_anchors = self._calculate_anchors(len(strides))
  47. self.offset = offset
  48. def _broadcast_params(self, params, num_features):
  49. if not isinstance(params[0], (list, tuple)): # list[float]
  50. return [params] * num_features
  51. if len(params) == 1:
  52. return list(params) * num_features
  53. return params
  54. def generate_cell_anchors(self, sizes, aspect_ratios):
  55. anchors = []
  56. for size in sizes:
  57. area = size**2.0
  58. for aspect_ratio in aspect_ratios:
  59. w = math.sqrt(area / aspect_ratio)
  60. h = aspect_ratio * w
  61. x0, y0, x1, y1 = -w / 2.0, -h / 2.0, w / 2.0, h / 2.0
  62. anchors.append([x0, y0, x1, y1])
  63. return paddle.to_tensor(anchors, dtype='float32')
  64. def _calculate_anchors(self, num_features):
  65. sizes = self._broadcast_params(self.anchor_sizes, num_features)
  66. aspect_ratios = self._broadcast_params(self.aspect_ratios,
  67. num_features)
  68. cell_anchors = [
  69. self.generate_cell_anchors(s, a)
  70. for s, a in zip(sizes, aspect_ratios)
  71. ]
  72. [
  73. self.register_buffer(
  74. t.name, t, persistable=False) for t in cell_anchors
  75. ]
  76. return cell_anchors
  77. def _create_grid_offsets(self, size, stride, offset):
  78. grid_height, grid_width = size[0], size[1]
  79. shifts_x = paddle.arange(
  80. offset * stride, grid_width * stride, step=stride, dtype='float32')
  81. shifts_y = paddle.arange(
  82. offset * stride,
  83. grid_height * stride,
  84. step=stride,
  85. 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])