utils.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # Copyright (c) 2021 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. import paddle.nn.functional as F
  19. __all__ = [
  20. 'pad_gt', 'gather_topk_anchors', 'check_points_inside_bboxes',
  21. 'compute_max_iou_anchor', 'compute_max_iou_gt',
  22. 'generate_anchors_for_grid_cell'
  23. ]
  24. def pad_gt(gt_labels, gt_bboxes, gt_scores=None):
  25. r""" Pad 0 in gt_labels and gt_bboxes.
  26. Args:
  27. gt_labels (Tensor|List[Tensor], int64): Label of gt_bboxes,
  28. shape is [B, n, 1] or [[n_1, 1], [n_2, 1], ...], here n = sum(n_i)
  29. gt_bboxes (Tensor|List[Tensor], float32): Ground truth bboxes,
  30. shape is [B, n, 4] or [[n_1, 4], [n_2, 4], ...], here n = sum(n_i)
  31. gt_scores (Tensor|List[Tensor]|None, float32): Score of gt_bboxes,
  32. shape is [B, n, 1] or [[n_1, 4], [n_2, 4], ...], here n = sum(n_i)
  33. Returns:
  34. pad_gt_labels (Tensor, int64): shape[B, n, 1]
  35. pad_gt_bboxes (Tensor, float32): shape[B, n, 4]
  36. pad_gt_scores (Tensor, float32): shape[B, n, 1]
  37. pad_gt_mask (Tensor, float32): shape[B, n, 1], 1 means bbox, 0 means no bbox
  38. """
  39. if isinstance(gt_labels, paddle.Tensor) and isinstance(gt_bboxes,
  40. paddle.Tensor):
  41. assert gt_labels.ndim == gt_bboxes.ndim and \
  42. gt_bboxes.ndim == 3
  43. pad_gt_mask = (
  44. gt_bboxes.sum(axis=-1, keepdim=True) > 0).astype(gt_bboxes.dtype)
  45. if gt_scores is None:
  46. gt_scores = pad_gt_mask.clone()
  47. assert gt_labels.ndim == gt_scores.ndim
  48. return gt_labels, gt_bboxes, gt_scores, pad_gt_mask
  49. elif isinstance(gt_labels, list) and isinstance(gt_bboxes, list):
  50. assert len(gt_labels) == len(gt_bboxes), \
  51. 'The number of `gt_labels` and `gt_bboxes` is not equal. '
  52. num_max_boxes = max([len(a) for a in gt_bboxes])
  53. batch_size = len(gt_bboxes)
  54. # pad label and bbox
  55. pad_gt_labels = paddle.zeros(
  56. [batch_size, num_max_boxes, 1], dtype=gt_labels[0].dtype)
  57. pad_gt_bboxes = paddle.zeros(
  58. [batch_size, num_max_boxes, 4], dtype=gt_bboxes[0].dtype)
  59. pad_gt_scores = paddle.zeros(
  60. [batch_size, num_max_boxes, 1], dtype=gt_bboxes[0].dtype)
  61. pad_gt_mask = paddle.zeros(
  62. [batch_size, num_max_boxes, 1], dtype=gt_bboxes[0].dtype)
  63. for i, (label, bbox) in enumerate(zip(gt_labels, gt_bboxes)):
  64. if len(label) > 0 and len(bbox) > 0:
  65. pad_gt_labels[i, :len(label)] = label
  66. pad_gt_bboxes[i, :len(bbox)] = bbox
  67. pad_gt_mask[i, :len(bbox)] = 1.
  68. if gt_scores is not None:
  69. pad_gt_scores[i, :len(gt_scores[i])] = gt_scores[i]
  70. if gt_scores is None:
  71. pad_gt_scores = pad_gt_mask.clone()
  72. return pad_gt_labels, pad_gt_bboxes, pad_gt_scores, pad_gt_mask
  73. else:
  74. raise ValueError('The input `gt_labels` or `gt_bboxes` is invalid! ')
  75. def gather_topk_anchors(metrics, topk, largest=True, topk_mask=None, eps=1e-9):
  76. r"""
  77. Args:
  78. metrics (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  79. topk (int): The number of top elements to look for along the axis.
  80. largest (bool) : largest is a flag, if set to true,
  81. algorithm will sort by descending order, otherwise sort by
  82. ascending order. Default: True
  83. topk_mask (Tensor, bool|None): shape[B, n, topk], ignore bbox mask,
  84. Default: None
  85. eps (float): Default: 1e-9
  86. Returns:
  87. is_in_topk (Tensor, float32): shape[B, n, L], value=1. means selected
  88. """
  89. num_anchors = metrics.shape[-1]
  90. topk_metrics, topk_idxs = paddle.topk(
  91. metrics, topk, axis=-1, largest=largest)
  92. if topk_mask is None:
  93. topk_mask = (topk_metrics.max(axis=-1, keepdim=True) > eps).tile(
  94. [1, 1, topk])
  95. topk_idxs = paddle.where(topk_mask, topk_idxs, paddle.zeros_like(topk_idxs))
  96. is_in_topk = F.one_hot(topk_idxs, num_anchors).sum(axis=-2)
  97. is_in_topk = paddle.where(is_in_topk > 1,
  98. paddle.zeros_like(is_in_topk), is_in_topk)
  99. return is_in_topk.astype(metrics.dtype)
  100. def check_points_inside_bboxes(points,
  101. bboxes,
  102. center_radius_tensor=None,
  103. eps=1e-9):
  104. r"""
  105. Args:
  106. points (Tensor, float32): shape[L, 2], "xy" format, L: num_anchors
  107. bboxes (Tensor, float32): shape[B, n, 4], "xmin, ymin, xmax, ymax" format
  108. center_radius_tensor (Tensor, float32): shape [L, 1]. Default: None.
  109. eps (float): Default: 1e-9
  110. Returns:
  111. is_in_bboxes (Tensor, float32): shape[B, n, L], value=1. means selected
  112. """
  113. points = points.unsqueeze([0, 1])
  114. x, y = points.chunk(2, axis=-1)
  115. xmin, ymin, xmax, ymax = bboxes.unsqueeze(2).chunk(4, axis=-1)
  116. # check whether `points` is in `bboxes`
  117. l = x - xmin
  118. t = y - ymin
  119. r = xmax - x
  120. b = ymax - y
  121. delta_ltrb = paddle.concat([l, t, r, b], axis=-1)
  122. is_in_bboxes = (delta_ltrb.min(axis=-1) > eps)
  123. if center_radius_tensor is not None:
  124. # check whether `points` is in `center_radius`
  125. center_radius_tensor = center_radius_tensor.unsqueeze([0, 1])
  126. cx = (xmin + xmax) * 0.5
  127. cy = (ymin + ymax) * 0.5
  128. l = x - (cx - center_radius_tensor)
  129. t = y - (cy - center_radius_tensor)
  130. r = (cx + center_radius_tensor) - x
  131. b = (cy + center_radius_tensor) - y
  132. delta_ltrb_c = paddle.concat([l, t, r, b], axis=-1)
  133. is_in_center = (delta_ltrb_c.min(axis=-1) > eps)
  134. return (paddle.logical_and(is_in_bboxes, is_in_center),
  135. paddle.logical_or(is_in_bboxes, is_in_center))
  136. return is_in_bboxes.astype(bboxes.dtype)
  137. def compute_max_iou_anchor(ious):
  138. r"""
  139. For each anchor, find the GT with the largest IOU.
  140. Args:
  141. ious (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  142. Returns:
  143. is_max_iou (Tensor, float32): shape[B, n, L], value=1. means selected
  144. """
  145. num_max_boxes = ious.shape[-2]
  146. max_iou_index = ious.argmax(axis=-2)
  147. is_max_iou = F.one_hot(max_iou_index, num_max_boxes).transpose([0, 2, 1])
  148. return is_max_iou.astype(ious.dtype)
  149. def compute_max_iou_gt(ious):
  150. r"""
  151. For each GT, find the anchor with the largest IOU.
  152. Args:
  153. ious (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  154. Returns:
  155. is_max_iou (Tensor, float32): shape[B, n, L], value=1. means selected
  156. """
  157. num_anchors = ious.shape[-1]
  158. max_iou_index = ious.argmax(axis=-1)
  159. is_max_iou = F.one_hot(max_iou_index, num_anchors)
  160. return is_max_iou.astype(ious.dtype)
  161. def generate_anchors_for_grid_cell(feats,
  162. fpn_strides,
  163. grid_cell_size=5.0,
  164. grid_cell_offset=0.5):
  165. r"""
  166. Like ATSS, generate anchors based on grid size.
  167. Args:
  168. feats (List[Tensor]): shape[s, (b, c, h, w)]
  169. fpn_strides (tuple|list): shape[s], stride for each scale feature
  170. grid_cell_size (float): anchor size
  171. grid_cell_offset (float): The range is between 0 and 1.
  172. Returns:
  173. anchors (Tensor): shape[l, 4], "xmin, ymin, xmax, ymax" format.
  174. anchor_points (Tensor): shape[l, 2], "x, y" format.
  175. num_anchors_list (List[int]): shape[s], contains [s_1, s_2, ...].
  176. stride_tensor (Tensor): shape[l, 1], contains the stride for each scale.
  177. """
  178. assert len(feats) == len(fpn_strides)
  179. anchors = []
  180. anchor_points = []
  181. num_anchors_list = []
  182. stride_tensor = []
  183. for feat, stride in zip(feats, fpn_strides):
  184. _, _, h, w = feat.shape
  185. cell_half_size = grid_cell_size * stride * 0.5
  186. shift_x = (paddle.arange(end=w) + grid_cell_offset) * stride
  187. shift_y = (paddle.arange(end=h) + grid_cell_offset) * stride
  188. shift_y, shift_x = paddle.meshgrid(shift_y, shift_x)
  189. anchor = paddle.stack(
  190. [
  191. shift_x - cell_half_size, shift_y - cell_half_size,
  192. shift_x + cell_half_size, shift_y + cell_half_size
  193. ],
  194. axis=-1).astype(feat.dtype)
  195. anchor_point = paddle.stack(
  196. [shift_x, shift_y], axis=-1).astype(feat.dtype)
  197. anchors.append(anchor.reshape([-1, 4]))
  198. anchor_points.append(anchor_point.reshape([-1, 2]))
  199. num_anchors_list.append(len(anchors[-1]))
  200. stride_tensor.append(
  201. paddle.full(
  202. [num_anchors_list[-1], 1], stride, dtype=feat.dtype))
  203. anchors = paddle.concat(anchors)
  204. anchors.stop_gradient = True
  205. anchor_points = paddle.concat(anchor_points)
  206. anchor_points.stop_gradient = True
  207. stride_tensor = paddle.concat(stride_tensor)
  208. stride_tensor.stop_gradient = True
  209. return anchors, anchor_points, num_anchors_list, stride_tensor