region_assigner.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import List, Optional, Tuple
  3. import torch
  4. from mmengine.structures import InstanceData
  5. from torch import Tensor
  6. from mmdet.registry import TASK_UTILS
  7. from ..prior_generators import anchor_inside_flags
  8. from .assign_result import AssignResult
  9. from .base_assigner import BaseAssigner
  10. def calc_region(
  11. bbox: Tensor,
  12. ratio: float,
  13. stride: int,
  14. featmap_size: Optional[Tuple[int, int]] = None) -> Tuple[Tensor]:
  15. """Calculate region of the box defined by the ratio, the ratio is from the
  16. center of the box to every edge."""
  17. # project bbox on the feature
  18. f_bbox = bbox / stride
  19. x1 = torch.round((1 - ratio) * f_bbox[0] + ratio * f_bbox[2])
  20. y1 = torch.round((1 - ratio) * f_bbox[1] + ratio * f_bbox[3])
  21. x2 = torch.round(ratio * f_bbox[0] + (1 - ratio) * f_bbox[2])
  22. y2 = torch.round(ratio * f_bbox[1] + (1 - ratio) * f_bbox[3])
  23. if featmap_size is not None:
  24. x1 = x1.clamp(min=0, max=featmap_size[1])
  25. y1 = y1.clamp(min=0, max=featmap_size[0])
  26. x2 = x2.clamp(min=0, max=featmap_size[1])
  27. y2 = y2.clamp(min=0, max=featmap_size[0])
  28. return (x1, y1, x2, y2)
  29. def anchor_ctr_inside_region_flags(anchors: Tensor, stride: int,
  30. region: Tuple[Tensor]) -> Tensor:
  31. """Get the flag indicate whether anchor centers are inside regions."""
  32. x1, y1, x2, y2 = region
  33. f_anchors = anchors / stride
  34. x = (f_anchors[:, 0] + f_anchors[:, 2]) * 0.5
  35. y = (f_anchors[:, 1] + f_anchors[:, 3]) * 0.5
  36. flags = (x >= x1) & (x <= x2) & (y >= y1) & (y <= y2)
  37. return flags
  38. @TASK_UTILS.register_module()
  39. class RegionAssigner(BaseAssigner):
  40. """Assign a corresponding gt bbox or background to each bbox.
  41. Each proposals will be assigned with `-1`, `0`, or a positive integer
  42. indicating the ground truth index.
  43. - -1: don't care
  44. - 0: negative sample, no assigned gt
  45. - positive integer: positive sample, index (1-based) of assigned gt
  46. Args:
  47. center_ratio (float): ratio of the region in the center of the bbox to
  48. define positive sample.
  49. ignore_ratio (float): ratio of the region to define ignore samples.
  50. """
  51. def __init__(self,
  52. center_ratio: float = 0.2,
  53. ignore_ratio: float = 0.5) -> None:
  54. self.center_ratio = center_ratio
  55. self.ignore_ratio = ignore_ratio
  56. def assign(self,
  57. pred_instances: InstanceData,
  58. gt_instances: InstanceData,
  59. img_meta: dict,
  60. featmap_sizes: List[Tuple[int, int]],
  61. num_level_anchors: List[int],
  62. anchor_scale: int,
  63. anchor_strides: List[int],
  64. gt_instances_ignore: Optional[InstanceData] = None,
  65. allowed_border: int = 0) -> AssignResult:
  66. """Assign gt to anchors.
  67. This method assign a gt bbox to every bbox (proposal/anchor), each bbox
  68. will be assigned with -1, 0, or a positive number. -1 means don't care,
  69. 0 means negative sample, positive number is the index (1-based) of
  70. assigned gt.
  71. The assignment is done in following steps, and the order matters.
  72. 1. Assign every anchor to 0 (negative)
  73. 2. (For each gt_bboxes) Compute ignore flags based on ignore_region
  74. then assign -1 to anchors w.r.t. ignore flags
  75. 3. (For each gt_bboxes) Compute pos flags based on center_region then
  76. assign gt_bboxes to anchors w.r.t. pos flags
  77. 4. (For each gt_bboxes) Compute ignore flags based on adjacent anchor
  78. level then assign -1 to anchors w.r.t. ignore flags
  79. 5. Assign anchor outside of image to -1
  80. Args:
  81. pred_instances (:obj:`InstanceData`): Instances of model
  82. predictions. It includes ``priors``, and the priors can
  83. be anchors or points, or the bboxes predicted by the
  84. previous stage, has shape (n, 4). The bboxes predicted by
  85. the current model or stage will be named ``bboxes``,
  86. ``labels``, and ``scores``, the same as the ``InstanceData``
  87. in other places.
  88. gt_instances (:obj:`InstanceData`): Ground truth of instance
  89. annotations. It usually includes ``bboxes``, with shape (k, 4),
  90. and ``labels``, with shape (k, ).
  91. img_meta (dict): Meta info of image.
  92. featmap_sizes (list[tuple[int, int]]): Feature map size each level.
  93. num_level_anchors (list[int]): The number of anchors in each level.
  94. anchor_scale (int): Scale of the anchor.
  95. anchor_strides (list[int]): Stride of the anchor.
  96. gt_instances_ignore (:obj:`InstanceData`, optional): Instances
  97. to be ignored during training. It includes ``bboxes``
  98. attribute data that is ignored during training and testing.
  99. Defaults to None.
  100. allowed_border (int, optional): The border to allow the valid
  101. anchor. Defaults to 0.
  102. Returns:
  103. :obj:`AssignResult`: The assign result.
  104. """
  105. if gt_instances_ignore is not None:
  106. raise NotImplementedError
  107. num_gts = len(gt_instances)
  108. num_bboxes = len(pred_instances)
  109. gt_bboxes = gt_instances.bboxes
  110. gt_labels = gt_instances.labels
  111. flat_anchors = pred_instances.priors
  112. flat_valid_flags = pred_instances.valid_flags
  113. mlvl_anchors = torch.split(flat_anchors, num_level_anchors)
  114. if num_gts == 0 or num_bboxes == 0:
  115. # No ground truth or boxes, return empty assignment
  116. max_overlaps = gt_bboxes.new_zeros((num_bboxes, ))
  117. assigned_gt_inds = gt_bboxes.new_zeros((num_bboxes, ),
  118. dtype=torch.long)
  119. assigned_labels = gt_bboxes.new_full((num_bboxes, ),
  120. -1,
  121. dtype=torch.long)
  122. return AssignResult(
  123. num_gts=num_gts,
  124. gt_inds=assigned_gt_inds,
  125. max_overlaps=max_overlaps,
  126. labels=assigned_labels)
  127. num_lvls = len(mlvl_anchors)
  128. r1 = (1 - self.center_ratio) / 2
  129. r2 = (1 - self.ignore_ratio) / 2
  130. scale = torch.sqrt((gt_bboxes[:, 2] - gt_bboxes[:, 0]) *
  131. (gt_bboxes[:, 3] - gt_bboxes[:, 1]))
  132. min_anchor_size = scale.new_full(
  133. (1, ), float(anchor_scale * anchor_strides[0]))
  134. target_lvls = torch.floor(
  135. torch.log2(scale) - torch.log2(min_anchor_size) + 0.5)
  136. target_lvls = target_lvls.clamp(min=0, max=num_lvls - 1).long()
  137. # 1. assign 0 (negative) by default
  138. mlvl_assigned_gt_inds = []
  139. mlvl_ignore_flags = []
  140. for lvl in range(num_lvls):
  141. assigned_gt_inds = gt_bboxes.new_full((num_level_anchors[lvl], ),
  142. 0,
  143. dtype=torch.long)
  144. ignore_flags = torch.zeros_like(assigned_gt_inds)
  145. mlvl_assigned_gt_inds.append(assigned_gt_inds)
  146. mlvl_ignore_flags.append(ignore_flags)
  147. for gt_id in range(num_gts):
  148. lvl = target_lvls[gt_id].item()
  149. featmap_size = featmap_sizes[lvl]
  150. stride = anchor_strides[lvl]
  151. anchors = mlvl_anchors[lvl]
  152. gt_bbox = gt_bboxes[gt_id, :4]
  153. # Compute regions
  154. ignore_region = calc_region(gt_bbox, r2, stride, featmap_size)
  155. ctr_region = calc_region(gt_bbox, r1, stride, featmap_size)
  156. # 2. Assign -1 to ignore flags
  157. ignore_flags = anchor_ctr_inside_region_flags(
  158. anchors, stride, ignore_region)
  159. mlvl_assigned_gt_inds[lvl][ignore_flags] = -1
  160. # 3. Assign gt_bboxes to pos flags
  161. pos_flags = anchor_ctr_inside_region_flags(anchors, stride,
  162. ctr_region)
  163. mlvl_assigned_gt_inds[lvl][pos_flags] = gt_id + 1
  164. # 4. Assign -1 to ignore adjacent lvl
  165. if lvl > 0:
  166. d_lvl = lvl - 1
  167. d_anchors = mlvl_anchors[d_lvl]
  168. d_featmap_size = featmap_sizes[d_lvl]
  169. d_stride = anchor_strides[d_lvl]
  170. d_ignore_region = calc_region(gt_bbox, r2, d_stride,
  171. d_featmap_size)
  172. ignore_flags = anchor_ctr_inside_region_flags(
  173. d_anchors, d_stride, d_ignore_region)
  174. mlvl_ignore_flags[d_lvl][ignore_flags] = 1
  175. if lvl < num_lvls - 1:
  176. u_lvl = lvl + 1
  177. u_anchors = mlvl_anchors[u_lvl]
  178. u_featmap_size = featmap_sizes[u_lvl]
  179. u_stride = anchor_strides[u_lvl]
  180. u_ignore_region = calc_region(gt_bbox, r2, u_stride,
  181. u_featmap_size)
  182. ignore_flags = anchor_ctr_inside_region_flags(
  183. u_anchors, u_stride, u_ignore_region)
  184. mlvl_ignore_flags[u_lvl][ignore_flags] = 1
  185. # 4. (cont.) Assign -1 to ignore adjacent lvl
  186. for lvl in range(num_lvls):
  187. ignore_flags = mlvl_ignore_flags[lvl]
  188. mlvl_assigned_gt_inds[lvl][ignore_flags == 1] = -1
  189. # 5. Assign -1 to anchor outside of image
  190. flat_assigned_gt_inds = torch.cat(mlvl_assigned_gt_inds)
  191. assert (flat_assigned_gt_inds.shape[0] == flat_anchors.shape[0] ==
  192. flat_valid_flags.shape[0])
  193. inside_flags = anchor_inside_flags(flat_anchors, flat_valid_flags,
  194. img_meta['img_shape'],
  195. allowed_border)
  196. outside_flags = ~inside_flags
  197. flat_assigned_gt_inds[outside_flags] = -1
  198. assigned_labels = torch.zeros_like(flat_assigned_gt_inds)
  199. pos_flags = flat_assigned_gt_inds > 0
  200. assigned_labels[pos_flags] = gt_labels[flat_assigned_gt_inds[pos_flags]
  201. - 1]
  202. return AssignResult(
  203. num_gts=num_gts,
  204. gt_inds=flat_assigned_gt_inds,
  205. max_overlaps=None,
  206. labels=assigned_labels)