utils.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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, float32): shape[B, n, 1], 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 = (
  94. topk_metrics.max(axis=-1, keepdim=True) > eps).astype(metrics.dtype)
  95. is_in_topk = F.one_hot(topk_idxs, num_anchors).sum(
  96. axis=-2).astype(metrics.dtype)
  97. return is_in_topk * topk_mask
  98. def check_points_inside_bboxes(points,
  99. bboxes,
  100. center_radius_tensor=None,
  101. eps=1e-9,
  102. sm_use=False):
  103. r"""
  104. Args:
  105. points (Tensor, float32): shape[L, 2], "xy" format, L: num_anchors
  106. bboxes (Tensor, float32): shape[B, n, 4], "xmin, ymin, xmax, ymax" format
  107. center_radius_tensor (Tensor, float32): shape [L, 1]. Default: None.
  108. eps (float): Default: 1e-9
  109. Returns:
  110. is_in_bboxes (Tensor, float32): shape[B, n, L], value=1. means selected
  111. """
  112. points = points.unsqueeze([0, 1])
  113. x, y = points.chunk(2, axis=-1)
  114. xmin, ymin, xmax, ymax = bboxes.unsqueeze(2).chunk(4, axis=-1)
  115. # check whether `points` is in `bboxes`
  116. l = x - xmin
  117. t = y - ymin
  118. r = xmax - x
  119. b = ymax - y
  120. delta_ltrb = paddle.concat([l, t, r, b], axis=-1)
  121. is_in_bboxes = (delta_ltrb.min(axis=-1) > eps)
  122. if center_radius_tensor is not None:
  123. # check whether `points` is in `center_radius`
  124. center_radius_tensor = center_radius_tensor.unsqueeze([0, 1])
  125. cx = (xmin + xmax) * 0.5
  126. cy = (ymin + ymax) * 0.5
  127. l = x - (cx - center_radius_tensor)
  128. t = y - (cy - center_radius_tensor)
  129. r = (cx + center_radius_tensor) - x
  130. b = (cy + center_radius_tensor) - y
  131. delta_ltrb_c = paddle.concat([l, t, r, b], axis=-1)
  132. is_in_center = (delta_ltrb_c.min(axis=-1) > eps)
  133. if sm_use:
  134. return is_in_bboxes.astype(bboxes.dtype), is_in_center.astype(
  135. bboxes.dtype)
  136. else:
  137. return (paddle.logical_and(is_in_bboxes, is_in_center),
  138. paddle.logical_or(is_in_bboxes, is_in_center))
  139. return is_in_bboxes.astype(bboxes.dtype)
  140. def compute_max_iou_anchor(ious):
  141. r"""
  142. For each anchor, find the GT with the largest IOU.
  143. Args:
  144. ious (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  145. Returns:
  146. is_max_iou (Tensor, float32): shape[B, n, L], value=1. means selected
  147. """
  148. num_max_boxes = ious.shape[-2]
  149. max_iou_index = ious.argmax(axis=-2)
  150. is_max_iou = F.one_hot(max_iou_index, num_max_boxes).transpose([0, 2, 1])
  151. return is_max_iou.astype(ious.dtype)
  152. def compute_max_iou_gt(ious):
  153. r"""
  154. For each GT, find the anchor with the largest IOU.
  155. Args:
  156. ious (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  157. Returns:
  158. is_max_iou (Tensor, float32): shape[B, n, L], value=1. means selected
  159. """
  160. num_anchors = ious.shape[-1]
  161. max_iou_index = ious.argmax(axis=-1)
  162. is_max_iou = F.one_hot(max_iou_index, num_anchors)
  163. return is_max_iou.astype(ious.dtype)
  164. def generate_anchors_for_grid_cell(feats,
  165. fpn_strides,
  166. grid_cell_size=5.0,
  167. grid_cell_offset=0.5,
  168. dtype='float32'):
  169. r"""
  170. Like ATSS, generate anchors based on grid size.
  171. Args:
  172. feats (List[Tensor]): shape[s, (b, c, h, w)]
  173. fpn_strides (tuple|list): shape[s], stride for each scale feature
  174. grid_cell_size (float): anchor size
  175. grid_cell_offset (float): The range is between 0 and 1.
  176. Returns:
  177. anchors (Tensor): shape[l, 4], "xmin, ymin, xmax, ymax" format.
  178. anchor_points (Tensor): shape[l, 2], "x, y" format.
  179. num_anchors_list (List[int]): shape[s], contains [s_1, s_2, ...].
  180. stride_tensor (Tensor): shape[l, 1], contains the stride for each scale.
  181. """
  182. assert len(feats) == len(fpn_strides)
  183. anchors = []
  184. anchor_points = []
  185. num_anchors_list = []
  186. stride_tensor = []
  187. for feat, stride in zip(feats, fpn_strides):
  188. _, _, h, w = feat.shape
  189. cell_half_size = grid_cell_size * stride * 0.5
  190. shift_x = (paddle.arange(end=w) + grid_cell_offset) * stride
  191. shift_y = (paddle.arange(end=h) + grid_cell_offset) * stride
  192. shift_y, shift_x = paddle.meshgrid(shift_y, shift_x)
  193. anchor = paddle.stack(
  194. [
  195. shift_x - cell_half_size, shift_y - cell_half_size,
  196. shift_x + cell_half_size, shift_y + cell_half_size
  197. ],
  198. axis=-1).astype(dtype)
  199. anchor_point = paddle.stack([shift_x, shift_y], axis=-1).astype(dtype)
  200. anchors.append(anchor.reshape([-1, 4]))
  201. anchor_points.append(anchor_point.reshape([-1, 2]))
  202. num_anchors_list.append(len(anchors[-1]))
  203. stride_tensor.append(
  204. paddle.full(
  205. [num_anchors_list[-1], 1], stride, dtype=dtype))
  206. anchors = paddle.concat(anchors)
  207. anchors.stop_gradient = True
  208. anchor_points = paddle.concat(anchor_points)
  209. anchor_points.stop_gradient = True
  210. stride_tensor = paddle.concat(stride_tensor)
  211. stride_tensor.stop_gradient = True
  212. return anchors, anchor_points, num_anchors_list, stride_tensor