atss_assigner.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 numpy as np
  18. from paddlex.ppdet.utils.logger import setup_logger
  19. logger = setup_logger(__name__)
  20. def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6):
  21. """Calculate overlap between two set of bboxes.
  22. If ``is_aligned `` is ``False``, then calculate the overlaps between each
  23. bbox of bboxes1 and bboxes2, otherwise the overlaps between each aligned
  24. pair of bboxes1 and bboxes2.
  25. Args:
  26. bboxes1 (Tensor): shape (B, m, 4) in <x1, y1, x2, y2> format or empty.
  27. bboxes2 (Tensor): shape (B, n, 4) in <x1, y1, x2, y2> format or empty.
  28. B indicates the batch dim, in shape (B1, B2, ..., Bn).
  29. If ``is_aligned `` is ``True``, then m and n must be equal.
  30. mode (str): "iou" (intersection over union) or "iof" (intersection over
  31. foreground).
  32. is_aligned (bool, optional): If True, then m and n must be equal.
  33. Default False.
  34. eps (float, optional): A value added to the denominator for numerical
  35. stability. Default 1e-6.
  36. Returns:
  37. Tensor: shape (m, n) if ``is_aligned `` is False else shape (m,)
  38. """
  39. assert mode in ['iou', 'iof', 'giou'], 'Unsupported mode {}'.format(mode)
  40. # Either the boxes are empty or the length of boxes's last dimenstion is 4
  41. assert (bboxes1.shape[-1] == 4 or bboxes1.shape[0] == 0)
  42. assert (bboxes2.shape[-1] == 4 or bboxes2.shape[0] == 0)
  43. # Batch dim must be the same
  44. # Batch dim: (B1, B2, ... Bn)
  45. assert bboxes1.shape[:-2] == bboxes2.shape[:-2]
  46. batch_shape = bboxes1.shape[:-2]
  47. rows = bboxes1.shape[-2] if bboxes1.shape[0] > 0 else 0
  48. cols = bboxes2.shape[-2] if bboxes2.shape[0] > 0 else 0
  49. if is_aligned:
  50. assert rows == cols
  51. if rows * cols == 0:
  52. if is_aligned:
  53. return np.random.random(batch_shape + (rows, ))
  54. else:
  55. return np.random.random(batch_shape + (rows, cols))
  56. area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (
  57. bboxes1[..., 3] - bboxes1[..., 1])
  58. area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (
  59. bboxes2[..., 3] - bboxes2[..., 1])
  60. if is_aligned:
  61. lt = np.maximum(bboxes1[..., :2], bboxes2[..., :2]) # [B, rows, 2]
  62. rb = np.minimum(bboxes1[..., 2:], bboxes2[..., 2:]) # [B, rows, 2]
  63. wh = (rb - lt).clip(min=0) # [B, rows, 2]
  64. overlap = wh[..., 0] * wh[..., 1]
  65. if mode in ['iou', 'giou']:
  66. union = area1 + area2 - overlap
  67. else:
  68. union = area1
  69. if mode == 'giou':
  70. enclosed_lt = np.minimum(bboxes1[..., :2], bboxes2[..., :2])
  71. enclosed_rb = np.maximum(bboxes1[..., 2:], bboxes2[..., 2:])
  72. else:
  73. lt = np.maximum(bboxes1[..., :, None, :2],
  74. bboxes2[..., None, :, :2]) # [B, rows, cols, 2]
  75. rb = np.minimum(bboxes1[..., :, None, 2:],
  76. bboxes2[..., None, :, 2:]) # [B, rows, cols, 2]
  77. wh = (rb - lt).clip(min=0) # [B, rows, cols, 2]
  78. overlap = wh[..., 0] * wh[..., 1]
  79. if mode in ['iou', 'giou']:
  80. union = area1[..., None] + area2[..., None, :] - overlap
  81. else:
  82. union = area1[..., None]
  83. if mode == 'giou':
  84. enclosed_lt = np.minimum(bboxes1[..., :, None, :2],
  85. bboxes2[..., None, :, :2])
  86. enclosed_rb = np.maximum(bboxes1[..., :, None, 2:],
  87. bboxes2[..., None, :, 2:])
  88. eps = np.array([eps])
  89. union = np.maximum(union, eps)
  90. ious = overlap / union
  91. if mode in ['iou', 'iof']:
  92. return ious
  93. # calculate gious
  94. enclose_wh = (enclosed_rb - enclosed_lt).clip(min=0)
  95. enclose_area = enclose_wh[..., 0] * enclose_wh[..., 1]
  96. enclose_area = np.maximum(enclose_area, eps)
  97. gious = ious - (enclose_area - union) / enclose_area
  98. return gious
  99. def topk_(input, k, axis=1, largest=True):
  100. x = -input if largest else input
  101. if axis == 0:
  102. row_index = np.arange(input.shape[1 - axis])
  103. topk_index = np.argpartition(x, k, axis=axis)[0:k, :]
  104. topk_data = x[topk_index, row_index]
  105. topk_index_sort = np.argsort(topk_data, axis=axis)
  106. topk_data_sort = topk_data[topk_index_sort, row_index]
  107. topk_index_sort = topk_index[0:k, :][topk_index_sort, row_index]
  108. else:
  109. column_index = np.arange(x.shape[1 - axis])[:, None]
  110. topk_index = np.argpartition(x, k, axis=axis)[:, 0:k]
  111. topk_data = x[column_index, topk_index]
  112. topk_data = -topk_data if largest else topk_data
  113. topk_index_sort = np.argsort(topk_data, axis=axis)
  114. topk_data_sort = topk_data[column_index, topk_index_sort]
  115. topk_index_sort = topk_index[:, 0:k][column_index, topk_index_sort]
  116. return topk_data_sort, topk_index_sort
  117. class ATSSAssigner(object):
  118. """Assign a corresponding gt bbox or background to each bbox.
  119. Each proposals will be assigned with `0` or a positive integer
  120. indicating the ground truth index.
  121. - 0: negative sample, no assigned gt
  122. - positive integer: positive sample, index (1-based) of assigned gt
  123. Args:
  124. topk (float): number of bbox selected in each level
  125. """
  126. def __init__(self, topk=9):
  127. self.topk = topk
  128. def __call__(self,
  129. bboxes,
  130. num_level_bboxes,
  131. gt_bboxes,
  132. gt_bboxes_ignore=None,
  133. gt_labels=None):
  134. """Assign gt to bboxes.
  135. The assignment is done in following steps
  136. 1. compute iou between all bbox (bbox of all pyramid levels) and gt
  137. 2. compute center distance between all bbox and gt
  138. 3. on each pyramid level, for each gt, select k bbox whose center
  139. are closest to the gt center, so we total select k*l bbox as
  140. candidates for each gt
  141. 4. get corresponding iou for the these candidates, and compute the
  142. mean and std, set mean + std as the iou threshold
  143. 5. select these candidates whose iou are greater than or equal to
  144. the threshold as postive
  145. 6. limit the positive sample's center in gt
  146. Args:
  147. bboxes (np.array): Bounding boxes to be assigned, shape(n, 4).
  148. num_level_bboxes (List): num of bboxes in each level
  149. gt_bboxes (np.array): Groundtruth boxes, shape (k, 4).
  150. gt_bboxes_ignore (np.array, optional): Ground truth bboxes that are
  151. labelled as `ignored`, e.g., crowd boxes in COCO.
  152. gt_labels (np.array, optional): Label of gt_bboxes, shape (k, ).
  153. """
  154. bboxes = bboxes[:, :4]
  155. num_gt, num_bboxes = gt_bboxes.shape[0], bboxes.shape[0]
  156. # assign 0 by default
  157. assigned_gt_inds = np.zeros((num_bboxes, ), dtype=np.int64)
  158. if num_gt == 0 or num_bboxes == 0:
  159. # No ground truth or boxes, return empty assignment
  160. max_overlaps = np.zeros((num_bboxes, ))
  161. if num_gt == 0:
  162. # No truth, assign everything to background
  163. assigned_gt_inds[:] = 0
  164. if not np.any(gt_labels):
  165. assigned_labels = None
  166. else:
  167. assigned_labels = -np.ones((num_bboxes, ), dtype=np.int64)
  168. return assigned_gt_inds, max_overlaps
  169. # compute iou between all bbox and gt
  170. overlaps = bbox_overlaps(bboxes, gt_bboxes)
  171. # compute center distance between all bbox and gt
  172. gt_cx = (gt_bboxes[:, 0] + gt_bboxes[:, 2]) / 2.0
  173. gt_cy = (gt_bboxes[:, 1] + gt_bboxes[:, 3]) / 2.0
  174. gt_points = np.stack((gt_cx, gt_cy), axis=1)
  175. bboxes_cx = (bboxes[:, 0] + bboxes[:, 2]) / 2.0
  176. bboxes_cy = (bboxes[:, 1] + bboxes[:, 3]) / 2.0
  177. bboxes_points = np.stack((bboxes_cx, bboxes_cy), axis=1)
  178. distances = np.sqrt(
  179. np.power((bboxes_points[:, None, :] - gt_points[None, :, :]), 2)
  180. .sum(-1))
  181. # Selecting candidates based on the center distance
  182. candidate_idxs = []
  183. start_idx = 0
  184. for bboxes_per_level in num_level_bboxes:
  185. # on each pyramid level, for each gt,
  186. # select k bbox whose center are closest to the gt center
  187. end_idx = start_idx + bboxes_per_level
  188. distances_per_level = distances[start_idx:end_idx, :]
  189. selectable_k = min(self.topk, bboxes_per_level)
  190. _, topk_idxs_per_level = topk_(
  191. distances_per_level, selectable_k, axis=0, largest=False)
  192. candidate_idxs.append(topk_idxs_per_level + start_idx)
  193. start_idx = end_idx
  194. candidate_idxs = np.concatenate(candidate_idxs, axis=0)
  195. # get corresponding iou for the these candidates, and compute the
  196. # mean and std, set mean + std as the iou threshold
  197. candidate_overlaps = overlaps[candidate_idxs, np.arange(num_gt)]
  198. overlaps_mean_per_gt = candidate_overlaps.mean(0)
  199. overlaps_std_per_gt = candidate_overlaps.std(0)
  200. overlaps_thr_per_gt = overlaps_mean_per_gt + overlaps_std_per_gt
  201. is_pos = candidate_overlaps >= overlaps_thr_per_gt[None, :]
  202. # limit the positive sample's center in gt
  203. for gt_idx in range(num_gt):
  204. candidate_idxs[:, gt_idx] += gt_idx * num_bboxes
  205. ep_bboxes_cx = np.broadcast_to(
  206. bboxes_cx.reshape(1, -1), [num_gt, num_bboxes]).reshape(-1)
  207. ep_bboxes_cy = np.broadcast_to(
  208. bboxes_cy.reshape(1, -1), [num_gt, num_bboxes]).reshape(-1)
  209. candidate_idxs = candidate_idxs.reshape(-1)
  210. # calculate the left, top, right, bottom distance between positive
  211. # bbox center and gt side
  212. l_ = ep_bboxes_cx[candidate_idxs].reshape(-1, num_gt) - gt_bboxes[:, 0]
  213. t_ = ep_bboxes_cy[candidate_idxs].reshape(-1, num_gt) - gt_bboxes[:, 1]
  214. r_ = gt_bboxes[:, 2] - ep_bboxes_cx[candidate_idxs].reshape(-1, num_gt)
  215. b_ = gt_bboxes[:, 3] - ep_bboxes_cy[candidate_idxs].reshape(-1, num_gt)
  216. is_in_gts = np.stack([l_, t_, r_, b_], axis=1).min(axis=1) > 0.01
  217. is_pos = is_pos & is_in_gts
  218. # if an anchor box is assigned to multiple gts,
  219. # the one with the highest IoU will be selected.
  220. overlaps_inf = -np.inf * np.ones_like(overlaps).T.reshape(-1)
  221. index = candidate_idxs.reshape(-1)[is_pos.reshape(-1)]
  222. overlaps_inf[index] = overlaps.T.reshape(-1)[index]
  223. overlaps_inf = overlaps_inf.reshape(num_gt, -1).T
  224. max_overlaps = overlaps_inf.max(axis=1)
  225. argmax_overlaps = overlaps_inf.argmax(axis=1)
  226. assigned_gt_inds[max_overlaps !=
  227. -np.inf] = argmax_overlaps[max_overlaps !=
  228. -np.inf] + 1
  229. return assigned_gt_inds, max_overlaps