approx_max_iou_assigner.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import Optional, Union
  3. import torch
  4. from mmengine.config import ConfigDict
  5. from mmengine.structures import InstanceData
  6. from mmdet.registry import TASK_UTILS
  7. from .assign_result import AssignResult
  8. from .max_iou_assigner import MaxIoUAssigner
  9. @TASK_UTILS.register_module()
  10. class ApproxMaxIoUAssigner(MaxIoUAssigner):
  11. """Assign a corresponding gt bbox or background to each bbox.
  12. Each proposals will be assigned with an integer indicating the ground truth
  13. index. (semi-positive index: gt label (0-based), -1: background)
  14. - -1: negative sample, no assigned gt
  15. - semi-positive integer: positive sample, index (0-based) of assigned gt
  16. Args:
  17. pos_iou_thr (float): IoU threshold for positive bboxes.
  18. neg_iou_thr (float or tuple): IoU threshold for negative bboxes.
  19. min_pos_iou (float): Minimum iou for a bbox to be considered as a
  20. positive bbox. Positive samples can have smaller IoU than
  21. pos_iou_thr due to the 4th step (assign max IoU sample to each gt).
  22. gt_max_assign_all (bool): Whether to assign all bboxes with the same
  23. highest overlap with some gt to that gt.
  24. ignore_iof_thr (float): IoF threshold for ignoring bboxes (if
  25. `gt_bboxes_ignore` is specified). Negative values mean not
  26. ignoring any bboxes.
  27. ignore_wrt_candidates (bool): Whether to compute the iof between
  28. `bboxes` and `gt_bboxes_ignore`, or the contrary.
  29. match_low_quality (bool): Whether to allow quality matches. This is
  30. usually allowed for RPN and single stage detectors, but not allowed
  31. in the second stage.
  32. gpu_assign_thr (int): The upper bound of the number of GT for GPU
  33. assign. When the number of gt is above this threshold, will assign
  34. on CPU device. Negative values mean not assign on CPU.
  35. iou_calculator (:obj:`ConfigDict` or dict): Config of overlaps
  36. Calculator.
  37. """
  38. def __init__(
  39. self,
  40. pos_iou_thr: float,
  41. neg_iou_thr: Union[float, tuple],
  42. min_pos_iou: float = .0,
  43. gt_max_assign_all: bool = True,
  44. ignore_iof_thr: float = -1,
  45. ignore_wrt_candidates: bool = True,
  46. match_low_quality: bool = True,
  47. gpu_assign_thr: int = -1,
  48. iou_calculator: Union[ConfigDict, dict] = dict(type='BboxOverlaps2D')
  49. ) -> None:
  50. self.pos_iou_thr = pos_iou_thr
  51. self.neg_iou_thr = neg_iou_thr
  52. self.min_pos_iou = min_pos_iou
  53. self.gt_max_assign_all = gt_max_assign_all
  54. self.ignore_iof_thr = ignore_iof_thr
  55. self.ignore_wrt_candidates = ignore_wrt_candidates
  56. self.gpu_assign_thr = gpu_assign_thr
  57. self.match_low_quality = match_low_quality
  58. self.iou_calculator = TASK_UTILS.build(iou_calculator)
  59. def assign(self,
  60. pred_instances: InstanceData,
  61. gt_instances: InstanceData,
  62. gt_instances_ignore: Optional[InstanceData] = None,
  63. **kwargs) -> AssignResult:
  64. """Assign gt to approxs.
  65. This method assign a gt bbox to each group of approxs (bboxes),
  66. each group of approxs is represent by a base approx (bbox) and
  67. will be assigned with -1, or a semi-positive number.
  68. background_label (-1) means negative sample,
  69. semi-positive number is the index (0-based) of assigned gt.
  70. The assignment is done in following steps, the order matters.
  71. 1. assign every bbox to background_label (-1)
  72. 2. use the max IoU of each group of approxs to assign
  73. 2. assign proposals whose iou with all gts < neg_iou_thr to background
  74. 3. for each bbox, if the iou with its nearest gt >= pos_iou_thr,
  75. assign it to that bbox
  76. 4. for each gt bbox, assign its nearest proposals (may be more than
  77. one) to itself
  78. Args:
  79. pred_instances (:obj:`InstanceData`): Instances of model
  80. predictions. It includes ``priors``, and the priors can
  81. be anchors or points, or the bboxes predicted by the
  82. previous stage, has shape (n, 4). ``approxs`` means the
  83. group of approxs aligned with ``priors``, has shape
  84. (n, num_approxs, 4).
  85. gt_instances (:obj:`InstanceData`): Ground truth of instance
  86. annotations. It usually includes ``bboxes``, with shape (k, 4),
  87. and ``labels``, with shape (k, ).
  88. gt_instances_ignore (:obj:`InstanceData`, optional): Instances
  89. to be ignored during training. It includes ``bboxes``
  90. attribute data that is ignored during training and testing.
  91. Defaults to None.
  92. Returns:
  93. :obj:`AssignResult`: The assign result.
  94. """
  95. squares = pred_instances.priors
  96. approxs = pred_instances.approxs
  97. gt_bboxes = gt_instances.bboxes
  98. gt_labels = gt_instances.labels
  99. gt_bboxes_ignore = None if gt_instances_ignore is None else \
  100. gt_instances_ignore.get('bboxes', None)
  101. approxs_per_octave = approxs.size(1)
  102. num_squares = squares.size(0)
  103. num_gts = gt_bboxes.size(0)
  104. if num_squares == 0 or num_gts == 0:
  105. # No predictions and/or truth, return empty assignment
  106. overlaps = approxs.new(num_gts, num_squares)
  107. assign_result = self.assign_wrt_overlaps(overlaps, gt_labels)
  108. return assign_result
  109. # re-organize anchors by approxs_per_octave x num_squares
  110. approxs = torch.transpose(approxs, 0, 1).contiguous().view(-1, 4)
  111. assign_on_cpu = True if (self.gpu_assign_thr > 0) and (
  112. num_gts > self.gpu_assign_thr) else False
  113. # compute overlap and assign gt on CPU when number of GT is large
  114. if assign_on_cpu:
  115. device = approxs.device
  116. approxs = approxs.cpu()
  117. gt_bboxes = gt_bboxes.cpu()
  118. if gt_bboxes_ignore is not None:
  119. gt_bboxes_ignore = gt_bboxes_ignore.cpu()
  120. if gt_labels is not None:
  121. gt_labels = gt_labels.cpu()
  122. all_overlaps = self.iou_calculator(approxs, gt_bboxes)
  123. overlaps, _ = all_overlaps.view(approxs_per_octave, num_squares,
  124. num_gts).max(dim=0)
  125. overlaps = torch.transpose(overlaps, 0, 1)
  126. if (self.ignore_iof_thr > 0 and gt_bboxes_ignore is not None
  127. and gt_bboxes_ignore.numel() > 0 and squares.numel() > 0):
  128. if self.ignore_wrt_candidates:
  129. ignore_overlaps = self.iou_calculator(
  130. squares, gt_bboxes_ignore, mode='iof')
  131. ignore_max_overlaps, _ = ignore_overlaps.max(dim=1)
  132. else:
  133. ignore_overlaps = self.iou_calculator(
  134. gt_bboxes_ignore, squares, mode='iof')
  135. ignore_max_overlaps, _ = ignore_overlaps.max(dim=0)
  136. overlaps[:, ignore_max_overlaps > self.ignore_iof_thr] = -1
  137. assign_result = self.assign_wrt_overlaps(overlaps, gt_labels)
  138. if assign_on_cpu:
  139. assign_result.gt_inds = assign_result.gt_inds.to(device)
  140. assign_result.max_overlaps = assign_result.max_overlaps.to(device)
  141. if assign_result.labels is not None:
  142. assign_result.labels = assign_result.labels.to(device)
  143. return assign_result