atss_assigner.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. # The code is based on:
  15. # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/assigners/atss_assigner.py
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import numpy as np
  20. from ppdet.utils.logger import setup_logger
  21. logger = setup_logger(__name__)
  22. def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6):
  23. """Calculate overlap between two set of bboxes.
  24. If ``is_aligned `` is ``False``, then calculate the overlaps between each
  25. bbox of bboxes1 and bboxes2, otherwise the overlaps between each aligned
  26. pair of bboxes1 and bboxes2.
  27. Args:
  28. bboxes1 (Tensor): shape (B, m, 4) in <x1, y1, x2, y2> format or empty.
  29. bboxes2 (Tensor): shape (B, n, 4) in <x1, y1, x2, y2> format or empty.
  30. B indicates the batch dim, in shape (B1, B2, ..., Bn).
  31. If ``is_aligned `` is ``True``, then m and n must be equal.
  32. mode (str): "iou" (intersection over union) or "iof" (intersection over
  33. foreground).
  34. is_aligned (bool, optional): If True, then m and n must be equal.
  35. Default False.
  36. eps (float, optional): A value added to the denominator for numerical
  37. stability. Default 1e-6.
  38. Returns:
  39. Tensor: shape (m, n) if ``is_aligned `` is False else shape (m,)
  40. """
  41. assert mode in ['iou', 'iof', 'giou', 'diou'], 'Unsupported mode {}'.format(
  42. mode)
  43. # Either the boxes are empty or the length of boxes's last dimenstion is 4
  44. assert (bboxes1.shape[-1] == 4 or bboxes1.shape[0] == 0)
  45. assert (bboxes2.shape[-1] == 4 or bboxes2.shape[0] == 0)
  46. # Batch dim must be the same
  47. # Batch dim: (B1, B2, ... Bn)
  48. assert bboxes1.shape[:-2] == bboxes2.shape[:-2]
  49. batch_shape = bboxes1.shape[:-2]
  50. rows = bboxes1.shape[-2] if bboxes1.shape[0] > 0 else 0
  51. cols = bboxes2.shape[-2] if bboxes2.shape[0] > 0 else 0
  52. if is_aligned:
  53. assert rows == cols
  54. if rows * cols == 0:
  55. if is_aligned:
  56. return np.random.random(batch_shape + (rows, ))
  57. else:
  58. return np.random.random(batch_shape + (rows, cols))
  59. area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (
  60. bboxes1[..., 3] - bboxes1[..., 1])
  61. area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (
  62. bboxes2[..., 3] - bboxes2[..., 1])
  63. if is_aligned:
  64. lt = np.maximum(bboxes1[..., :2], bboxes2[..., :2]) # [B, rows, 2]
  65. rb = np.minimum(bboxes1[..., 2:], bboxes2[..., 2:]) # [B, rows, 2]
  66. wh = (rb - lt).clip(min=0) # [B, rows, 2]
  67. overlap = wh[..., 0] * wh[..., 1]
  68. if mode in ['iou', 'giou']:
  69. union = area1 + area2 - overlap
  70. else:
  71. union = area1
  72. if mode == 'giou':
  73. enclosed_lt = np.minimum(bboxes1[..., :2], bboxes2[..., :2])
  74. enclosed_rb = np.maximum(bboxes1[..., 2:], bboxes2[..., 2:])
  75. if mode == 'diou':
  76. enclosed_lt = np.minimum(bboxes1[..., :2], bboxes2[..., :2])
  77. enclosed_rb = np.maximum(bboxes1[..., 2:], bboxes2[..., 2:])
  78. b1_x1, b1_y1 = bboxes1[..., 0], bboxes1[..., 1]
  79. b1_x2, b1_y2 = bboxes1[..., 2], bboxes1[..., 3]
  80. b2_x1, b2_y1 = bboxes2[..., 0], bboxes2[..., 1]
  81. b2_x2, b2_y2 = bboxes2[..., 2], bboxes2[..., 3]
  82. else:
  83. lt = np.maximum(bboxes1[..., :, None, :2],
  84. bboxes2[..., None, :, :2]) # [B, rows, cols, 2]
  85. rb = np.minimum(bboxes1[..., :, None, 2:],
  86. bboxes2[..., None, :, 2:]) # [B, rows, cols, 2]
  87. wh = (rb - lt).clip(min=0) # [B, rows, cols, 2]
  88. overlap = wh[..., 0] * wh[..., 1]
  89. if mode in ['iou', 'giou']:
  90. union = area1[..., None] + area2[..., None, :] - overlap
  91. else:
  92. union = area1[..., None]
  93. if mode == 'giou':
  94. enclosed_lt = np.minimum(bboxes1[..., :, None, :2],
  95. bboxes2[..., None, :, :2])
  96. enclosed_rb = np.maximum(bboxes1[..., :, None, 2:],
  97. bboxes2[..., None, :, 2:])
  98. if mode == 'diou':
  99. enclosed_lt = np.minimum(bboxes1[..., :, None, :2],
  100. bboxes2[..., None, :, :2])
  101. enclosed_rb = np.maximum(bboxes1[..., :, None, 2:],
  102. bboxes2[..., None, :, 2:])
  103. b1_x1, b1_y1 = bboxes1[..., :, None, 0], bboxes1[..., :, None, 1]
  104. b1_x2, b1_y2 = bboxes1[..., :, None, 2], bboxes1[..., :, None, 3]
  105. b2_x1, b2_y1 = bboxes2[..., None, :, 0], bboxes2[..., None, :, 1]
  106. b2_x2, b2_y2 = bboxes2[..., None, :, 2], bboxes2[..., None, :, 3]
  107. eps = np.array([eps])
  108. union = np.maximum(union, eps)
  109. ious = overlap / union
  110. if mode in ['iou', 'iof']:
  111. return ious
  112. # calculate gious
  113. if mode in ['giou']:
  114. enclose_wh = (enclosed_rb - enclosed_lt).clip(min=0)
  115. enclose_area = enclose_wh[..., 0] * enclose_wh[..., 1]
  116. enclose_area = np.maximum(enclose_area, eps)
  117. gious = ious - (enclose_area - union) / enclose_area
  118. return gious
  119. if mode in ['diou']:
  120. left = ((b2_x1 + b2_x2) - (b1_x1 + b1_x2))**2 / 4
  121. right = ((b2_y1 + b2_y2) - (b1_y1 + b1_y2))**2 / 4
  122. rho2 = left + right
  123. enclose_wh = (enclosed_rb - enclosed_lt).clip(min=0)
  124. enclose_c = enclose_wh[..., 0]**2 + enclose_wh[..., 1]**2
  125. enclose_c = np.maximum(enclose_c, eps)
  126. dious = ious - rho2 / enclose_c
  127. return dious
  128. def topk_(input, k, axis=1, largest=True):
  129. x = -input if largest else input
  130. if axis == 0:
  131. row_index = np.arange(input.shape[1 - axis])
  132. if k == x.shape[0]: # argpartition requires index < len(input)
  133. topk_index = np.argpartition(x, k - 1, axis=axis)[0:k, :]
  134. else:
  135. topk_index = np.argpartition(x, k, axis=axis)[0:k, :]
  136. topk_data = x[topk_index, row_index]
  137. topk_index_sort = np.argsort(topk_data, axis=axis)
  138. topk_data_sort = topk_data[topk_index_sort, row_index]
  139. topk_index_sort = topk_index[0:k, :][topk_index_sort, row_index]
  140. else:
  141. column_index = np.arange(x.shape[1 - axis])[:, None]
  142. topk_index = np.argpartition(x, k, axis=axis)[:, 0:k]
  143. topk_data = x[column_index, topk_index]
  144. topk_data = -topk_data if largest else topk_data
  145. topk_index_sort = np.argsort(topk_data, axis=axis)
  146. topk_data_sort = topk_data[column_index, topk_index_sort]
  147. topk_index_sort = topk_index[:, 0:k][column_index, topk_index_sort]
  148. return topk_data_sort, topk_index_sort
  149. class ATSSAssigner(object):
  150. """Assign a corresponding gt bbox or background to each bbox.
  151. Each proposals will be assigned with `0` or a positive integer
  152. indicating the ground truth index.
  153. - 0: negative sample, no assigned gt
  154. - positive integer: positive sample, index (1-based) of assigned gt
  155. Args:
  156. topk (float): number of bbox selected in each level
  157. """
  158. def __init__(self, topk=9):
  159. self.topk = topk
  160. def __call__(self,
  161. bboxes,
  162. num_level_bboxes,
  163. gt_bboxes,
  164. gt_bboxes_ignore=None,
  165. gt_labels=None):
  166. """Assign gt to bboxes.
  167. The assignment is done in following steps
  168. 1. compute iou between all bbox (bbox of all pyramid levels) and gt
  169. 2. compute center distance between all bbox and gt
  170. 3. on each pyramid level, for each gt, select k bbox whose center
  171. are closest to the gt center, so we total select k*l bbox as
  172. candidates for each gt
  173. 4. get corresponding iou for the these candidates, and compute the
  174. mean and std, set mean + std as the iou threshold
  175. 5. select these candidates whose iou are greater than or equal to
  176. the threshold as postive
  177. 6. limit the positive sample's center in gt
  178. Args:
  179. bboxes (np.array): Bounding boxes to be assigned, shape(n, 4).
  180. num_level_bboxes (List): num of bboxes in each level
  181. gt_bboxes (np.array): Groundtruth boxes, shape (k, 4).
  182. gt_bboxes_ignore (np.array, optional): Ground truth bboxes that are
  183. labelled as `ignored`, e.g., crowd boxes in COCO.
  184. gt_labels (np.array, optional): Label of gt_bboxes, shape (k, ).
  185. """
  186. bboxes = bboxes[:, :4]
  187. num_gt, num_bboxes = gt_bboxes.shape[0], bboxes.shape[0]
  188. # assign 0 by default
  189. assigned_gt_inds = np.zeros((num_bboxes, ), dtype=np.int64)
  190. if num_gt == 0 or num_bboxes == 0:
  191. # No ground truth or boxes, return empty assignment
  192. max_overlaps = np.zeros((num_bboxes, ))
  193. if num_gt == 0:
  194. # No truth, assign everything to background
  195. assigned_gt_inds[:] = 0
  196. if not np.any(gt_labels):
  197. assigned_labels = None
  198. else:
  199. assigned_labels = -np.ones((num_bboxes, ), dtype=np.int64)
  200. return assigned_gt_inds, max_overlaps
  201. # compute iou between all bbox and gt
  202. overlaps = bbox_overlaps(bboxes, gt_bboxes)
  203. # compute center distance between all bbox and gt
  204. gt_cx = (gt_bboxes[:, 0] + gt_bboxes[:, 2]) / 2.0
  205. gt_cy = (gt_bboxes[:, 1] + gt_bboxes[:, 3]) / 2.0
  206. gt_points = np.stack((gt_cx, gt_cy), axis=1)
  207. bboxes_cx = (bboxes[:, 0] + bboxes[:, 2]) / 2.0
  208. bboxes_cy = (bboxes[:, 1] + bboxes[:, 3]) / 2.0
  209. bboxes_points = np.stack((bboxes_cx, bboxes_cy), axis=1)
  210. distances = np.sqrt(
  211. np.power((bboxes_points[:, None, :] - gt_points[None, :, :]), 2)
  212. .sum(-1))
  213. # Selecting candidates based on the center distance
  214. candidate_idxs = []
  215. start_idx = 0
  216. for bboxes_per_level in num_level_bboxes:
  217. # on each pyramid level, for each gt,
  218. # select k bbox whose center are closest to the gt center
  219. end_idx = start_idx + bboxes_per_level
  220. distances_per_level = distances[start_idx:end_idx, :]
  221. selectable_k = min(self.topk, bboxes_per_level)
  222. _, topk_idxs_per_level = topk_(
  223. distances_per_level, selectable_k, axis=0, largest=False)
  224. candidate_idxs.append(topk_idxs_per_level + start_idx)
  225. start_idx = end_idx
  226. candidate_idxs = np.concatenate(candidate_idxs, axis=0)
  227. # get corresponding iou for the these candidates, and compute the
  228. # mean and std, set mean + std as the iou threshold
  229. candidate_overlaps = overlaps[candidate_idxs, np.arange(num_gt)]
  230. overlaps_mean_per_gt = candidate_overlaps.mean(0)
  231. overlaps_std_per_gt = candidate_overlaps.std(0)
  232. overlaps_thr_per_gt = overlaps_mean_per_gt + overlaps_std_per_gt
  233. is_pos = candidate_overlaps >= overlaps_thr_per_gt[None, :]
  234. # limit the positive sample's center in gt
  235. for gt_idx in range(num_gt):
  236. candidate_idxs[:, gt_idx] += gt_idx * num_bboxes
  237. ep_bboxes_cx = np.broadcast_to(
  238. bboxes_cx.reshape(1, -1), [num_gt, num_bboxes]).reshape(-1)
  239. ep_bboxes_cy = np.broadcast_to(
  240. bboxes_cy.reshape(1, -1), [num_gt, num_bboxes]).reshape(-1)
  241. candidate_idxs = candidate_idxs.reshape(-1)
  242. # calculate the left, top, right, bottom distance between positive
  243. # bbox center and gt side
  244. l_ = ep_bboxes_cx[candidate_idxs].reshape(-1, num_gt) - gt_bboxes[:, 0]
  245. t_ = ep_bboxes_cy[candidate_idxs].reshape(-1, num_gt) - gt_bboxes[:, 1]
  246. r_ = gt_bboxes[:, 2] - ep_bboxes_cx[candidate_idxs].reshape(-1, num_gt)
  247. b_ = gt_bboxes[:, 3] - ep_bboxes_cy[candidate_idxs].reshape(-1, num_gt)
  248. is_in_gts = np.stack([l_, t_, r_, b_], axis=1).min(axis=1) > 0.01
  249. is_pos = is_pos & is_in_gts
  250. # if an anchor box is assigned to multiple gts,
  251. # the one with the highest IoU will be selected.
  252. overlaps_inf = -np.inf * np.ones_like(overlaps).T.reshape(-1)
  253. index = candidate_idxs.reshape(-1)[is_pos.reshape(-1)]
  254. overlaps_inf[index] = overlaps.T.reshape(-1)[index]
  255. overlaps_inf = overlaps_inf.reshape(num_gt, -1).T
  256. max_overlaps = overlaps_inf.max(axis=1)
  257. argmax_overlaps = overlaps_inf.argmax(axis=1)
  258. assigned_gt_inds[max_overlaps !=
  259. -np.inf] = argmax_overlaps[max_overlaps != -np.inf] + 1
  260. return assigned_gt_inds, max_overlaps
  261. def get_vlr_region(self,
  262. bboxes,
  263. num_level_bboxes,
  264. gt_bboxes,
  265. gt_bboxes_ignore=None,
  266. gt_labels=None):
  267. """get vlr region for ld distillation.
  268. Args:
  269. bboxes (np.array): Bounding boxes to be assigned, shape(n, 4).
  270. num_level_bboxes (List): num of bboxes in each level
  271. gt_bboxes (np.array): Groundtruth boxes, shape (k, 4).
  272. gt_bboxes_ignore (np.array, optional): Ground truth bboxes that are
  273. labelled as `ignored`, e.g., crowd boxes in COCO.
  274. gt_labels (np.array, optional): Label of gt_bboxes, shape (k, ).
  275. """
  276. bboxes = bboxes[:, :4]
  277. num_gt, num_bboxes = gt_bboxes.shape[0], bboxes.shape[0]
  278. # compute iou between all bbox and gt
  279. overlaps = bbox_overlaps(bboxes, gt_bboxes)
  280. # compute diou between all bbox and gt
  281. diou = bbox_overlaps(bboxes, gt_bboxes, mode='diou')
  282. # assign 0 by default
  283. assigned_gt_inds = np.zeros((num_bboxes, ), dtype=np.int64)
  284. vlr_region_iou = (assigned_gt_inds + 0).astype(np.float32)
  285. if num_gt == 0 or num_bboxes == 0:
  286. # No ground truth or boxes, return empty assignment
  287. max_overlaps = np.zeros((num_bboxes, ))
  288. if num_gt == 0:
  289. # No truth, assign everything to background
  290. assigned_gt_inds[:] = 0
  291. if not np.any(gt_labels):
  292. assigned_labels = None
  293. else:
  294. assigned_labels = -np.ones((num_bboxes, ), dtype=np.int64)
  295. return assigned_gt_inds, max_overlaps
  296. # compute center distance between all bbox and gt
  297. gt_cx = (gt_bboxes[:, 0] + gt_bboxes[:, 2]) / 2.0
  298. gt_cy = (gt_bboxes[:, 1] + gt_bboxes[:, 3]) / 2.0
  299. gt_points = np.stack((gt_cx, gt_cy), axis=1)
  300. bboxes_cx = (bboxes[:, 0] + bboxes[:, 2]) / 2.0
  301. bboxes_cy = (bboxes[:, 1] + bboxes[:, 3]) / 2.0
  302. bboxes_points = np.stack((bboxes_cx, bboxes_cy), axis=1)
  303. distances = np.sqrt(
  304. np.power((bboxes_points[:, None, :] - gt_points[None, :, :]), 2)
  305. .sum(-1))
  306. # Selecting candidates based on the center distance
  307. candidate_idxs = []
  308. candidate_idxs_t = []
  309. start_idx = 0
  310. for bboxes_per_level in num_level_bboxes:
  311. # on each pyramid level, for each gt,
  312. # select k bbox whose center are closest to the gt center
  313. end_idx = start_idx + bboxes_per_level
  314. distances_per_level = distances[start_idx:end_idx, :]
  315. selectable_t = min(self.topk, bboxes_per_level)
  316. selectable_k = bboxes_per_level #k for all
  317. _, topt_idxs_per_level = topk_(
  318. distances_per_level, selectable_t, axis=0, largest=False)
  319. _, topk_idxs_per_level = topk_(
  320. distances_per_level, selectable_k, axis=0, largest=False)
  321. candidate_idxs_t.append(topt_idxs_per_level + start_idx)
  322. candidate_idxs.append(topk_idxs_per_level + start_idx)
  323. start_idx = end_idx
  324. candidate_idxs_t = np.concatenate(candidate_idxs_t, axis=0)
  325. candidate_idxs = np.concatenate(candidate_idxs, axis=0)
  326. # get corresponding iou for the these candidates, and compute the
  327. # mean and std, set mean + std as the iou threshold
  328. candidate_overlaps_t = overlaps[candidate_idxs_t, np.arange(num_gt)]
  329. # compute tdiou
  330. t_diou = diou[candidate_idxs, np.arange(num_gt)]
  331. overlaps_mean_per_gt = candidate_overlaps_t.mean(0)
  332. overlaps_std_per_gt = candidate_overlaps_t.std(
  333. 0, ddof=1) # NOTE: use Bessel correction
  334. overlaps_thr_per_gt = overlaps_mean_per_gt + overlaps_std_per_gt
  335. # compute region
  336. is_pos = (t_diou < overlaps_thr_per_gt[None, :]) & (
  337. t_diou >= 0.25 * overlaps_thr_per_gt[None, :])
  338. # limit the positive sample's center in gt
  339. for gt_idx in range(num_gt):
  340. candidate_idxs[:, gt_idx] += gt_idx * num_bboxes
  341. candidate_idxs = candidate_idxs.reshape(-1)
  342. # if an anchor box is assigned to multiple gts,
  343. # the one with the highest IoU will be selected.
  344. overlaps_inf = -np.inf * np.ones_like(overlaps).T.reshape(-1)
  345. index = candidate_idxs.reshape(-1)[is_pos.reshape(-1)]
  346. overlaps_inf[index] = overlaps.T.reshape(-1)[index]
  347. overlaps_inf = overlaps_inf.reshape(num_gt, -1).T
  348. max_overlaps = overlaps_inf.max(axis=1)
  349. argmax_overlaps = overlaps_inf.argmax(axis=1)
  350. overlaps_inf = -np.inf * np.ones_like(overlaps).T.reshape(-1)
  351. overlaps_inf = overlaps_inf.reshape(num_gt, -1).T
  352. assigned_gt_inds[max_overlaps !=
  353. -np.inf] = argmax_overlaps[max_overlaps != -np.inf] + 1
  354. vlr_region_iou[max_overlaps !=
  355. -np.inf] = max_overlaps[max_overlaps != -np.inf] + 0
  356. return vlr_region_iou