multi_instance_roi_head.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import List, Tuple
  3. from torch import Tensor
  4. from mmdet.registry import MODELS
  5. from mmdet.structures import DetDataSample
  6. from mmdet.structures.bbox import bbox2roi
  7. from mmdet.utils import ConfigType, InstanceList
  8. from ..task_modules.samplers import SamplingResult
  9. from ..utils import empty_instances, unpack_gt_instances
  10. from .standard_roi_head import StandardRoIHead
  11. @MODELS.register_module()
  12. class MultiInstanceRoIHead(StandardRoIHead):
  13. """The roi head for Multi-instance prediction."""
  14. def __init__(self, num_instance: int = 2, *args, **kwargs) -> None:
  15. self.num_instance = num_instance
  16. super().__init__(*args, **kwargs)
  17. def init_bbox_head(self, bbox_roi_extractor: ConfigType,
  18. bbox_head: ConfigType) -> None:
  19. """Initialize box head and box roi extractor.
  20. Args:
  21. bbox_roi_extractor (dict or ConfigDict): Config of box
  22. roi extractor.
  23. bbox_head (dict or ConfigDict): Config of box in box head.
  24. """
  25. self.bbox_roi_extractor = MODELS.build(bbox_roi_extractor)
  26. self.bbox_head = MODELS.build(bbox_head)
  27. def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict:
  28. """Box head forward function used in both training and testing.
  29. Args:
  30. x (tuple[Tensor]): List of multi-level img features.
  31. rois (Tensor): RoIs with the shape (n, 5) where the first
  32. column indicates batch id of each RoI.
  33. Returns:
  34. dict[str, Tensor]: Usually returns a dictionary with keys:
  35. - `cls_score` (Tensor): Classification scores.
  36. - `bbox_pred` (Tensor): Box energies / deltas.
  37. - `cls_score_ref` (Tensor): The cls_score after refine model.
  38. - `bbox_pred_ref` (Tensor): The bbox_pred after refine model.
  39. - `bbox_feats` (Tensor): Extract bbox RoI features.
  40. """
  41. # TODO: a more flexible way to decide which feature maps to use
  42. bbox_feats = self.bbox_roi_extractor(
  43. x[:self.bbox_roi_extractor.num_inputs], rois)
  44. bbox_results = self.bbox_head(bbox_feats)
  45. if self.bbox_head.with_refine:
  46. bbox_results = dict(
  47. cls_score=bbox_results[0],
  48. bbox_pred=bbox_results[1],
  49. cls_score_ref=bbox_results[2],
  50. bbox_pred_ref=bbox_results[3],
  51. bbox_feats=bbox_feats)
  52. else:
  53. bbox_results = dict(
  54. cls_score=bbox_results[0],
  55. bbox_pred=bbox_results[1],
  56. bbox_feats=bbox_feats)
  57. return bbox_results
  58. def bbox_loss(self, x: Tuple[Tensor],
  59. sampling_results: List[SamplingResult]) -> dict:
  60. """Perform forward propagation and loss calculation of the bbox head on
  61. the features of the upstream network.
  62. Args:
  63. x (tuple[Tensor]): List of multi-level img features.
  64. sampling_results (list["obj:`SamplingResult`]): Sampling results.
  65. Returns:
  66. dict[str, Tensor]: Usually returns a dictionary with keys:
  67. - `cls_score` (Tensor): Classification scores.
  68. - `bbox_pred` (Tensor): Box energies / deltas.
  69. - `bbox_feats` (Tensor): Extract bbox RoI features.
  70. - `loss_bbox` (dict): A dictionary of bbox loss components.
  71. """
  72. rois = bbox2roi([res.priors for res in sampling_results])
  73. bbox_results = self._bbox_forward(x, rois)
  74. # If there is a refining process, add refine loss.
  75. if 'cls_score_ref' in bbox_results:
  76. bbox_loss_and_target = self.bbox_head.loss_and_target(
  77. cls_score=bbox_results['cls_score'],
  78. bbox_pred=bbox_results['bbox_pred'],
  79. rois=rois,
  80. sampling_results=sampling_results,
  81. rcnn_train_cfg=self.train_cfg)
  82. bbox_results.update(loss_bbox=bbox_loss_and_target['loss_bbox'])
  83. bbox_loss_and_target_ref = self.bbox_head.loss_and_target(
  84. cls_score=bbox_results['cls_score_ref'],
  85. bbox_pred=bbox_results['bbox_pred_ref'],
  86. rois=rois,
  87. sampling_results=sampling_results,
  88. rcnn_train_cfg=self.train_cfg)
  89. bbox_results['loss_bbox']['loss_rcnn_emd_ref'] = \
  90. bbox_loss_and_target_ref['loss_bbox']['loss_rcnn_emd']
  91. else:
  92. bbox_loss_and_target = self.bbox_head.loss_and_target(
  93. cls_score=bbox_results['cls_score'],
  94. bbox_pred=bbox_results['bbox_pred'],
  95. rois=rois,
  96. sampling_results=sampling_results,
  97. rcnn_train_cfg=self.train_cfg)
  98. bbox_results.update(loss_bbox=bbox_loss_and_target['loss_bbox'])
  99. return bbox_results
  100. def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList,
  101. batch_data_samples: List[DetDataSample]) -> dict:
  102. """Perform forward propagation and loss calculation of the detection
  103. roi on the features of the upstream network.
  104. Args:
  105. x (tuple[Tensor]): List of multi-level img features.
  106. rpn_results_list (list[:obj:`InstanceData`]): List of region
  107. proposals.
  108. batch_data_samples (list[:obj:`DetDataSample`]): The batch
  109. data samples. It usually includes information such
  110. as `gt_instance` or `gt_panoptic_seg` or `gt_sem_seg`.
  111. Returns:
  112. dict[str, Tensor]: A dictionary of loss components
  113. """
  114. assert len(rpn_results_list) == len(batch_data_samples)
  115. outputs = unpack_gt_instances(batch_data_samples)
  116. batch_gt_instances, batch_gt_instances_ignore, _ = outputs
  117. sampling_results = []
  118. for i in range(len(batch_data_samples)):
  119. # rename rpn_results.bboxes to rpn_results.priors
  120. rpn_results = rpn_results_list[i]
  121. rpn_results.priors = rpn_results.pop('bboxes')
  122. assign_result = self.bbox_assigner.assign(
  123. rpn_results, batch_gt_instances[i],
  124. batch_gt_instances_ignore[i])
  125. sampling_result = self.bbox_sampler.sample(
  126. assign_result,
  127. rpn_results,
  128. batch_gt_instances[i],
  129. batch_gt_instances_ignore=batch_gt_instances_ignore[i])
  130. sampling_results.append(sampling_result)
  131. losses = dict()
  132. # bbox head loss
  133. if self.with_bbox:
  134. bbox_results = self.bbox_loss(x, sampling_results)
  135. losses.update(bbox_results['loss_bbox'])
  136. return losses
  137. def predict_bbox(self,
  138. x: Tuple[Tensor],
  139. batch_img_metas: List[dict],
  140. rpn_results_list: InstanceList,
  141. rcnn_test_cfg: ConfigType,
  142. rescale: bool = False) -> InstanceList:
  143. """Perform forward propagation of the bbox head and predict detection
  144. results on the features of the upstream network.
  145. Args:
  146. x (tuple[Tensor]): Feature maps of all scale level.
  147. batch_img_metas (list[dict]): List of image information.
  148. rpn_results_list (list[:obj:`InstanceData`]): List of region
  149. proposals.
  150. rcnn_test_cfg (obj:`ConfigDict`): `test_cfg` of R-CNN.
  151. rescale (bool): If True, return boxes in original image space.
  152. Defaults to False.
  153. Returns:
  154. list[:obj:`InstanceData`]: Detection results of each image
  155. after the post process.
  156. Each item usually contains following keys.
  157. - scores (Tensor): Classification scores, has a shape
  158. (num_instance, )
  159. - labels (Tensor): Labels of bboxes, has a shape
  160. (num_instances, ).
  161. - bboxes (Tensor): Has a shape (num_instances, 4),
  162. the last dimension 4 arrange as (x1, y1, x2, y2).
  163. """
  164. proposals = [res.bboxes for res in rpn_results_list]
  165. rois = bbox2roi(proposals)
  166. if rois.shape[0] == 0:
  167. return empty_instances(
  168. batch_img_metas, rois.device, task_type='bbox')
  169. bbox_results = self._bbox_forward(x, rois)
  170. # split batch bbox prediction back to each image
  171. if 'cls_score_ref' in bbox_results:
  172. cls_scores = bbox_results['cls_score_ref']
  173. bbox_preds = bbox_results['bbox_pred_ref']
  174. else:
  175. cls_scores = bbox_results['cls_score']
  176. bbox_preds = bbox_results['bbox_pred']
  177. num_proposals_per_img = tuple(len(p) for p in proposals)
  178. rois = rois.split(num_proposals_per_img, 0)
  179. cls_scores = cls_scores.split(num_proposals_per_img, 0)
  180. if bbox_preds is not None:
  181. bbox_preds = bbox_preds.split(num_proposals_per_img, 0)
  182. else:
  183. bbox_preds = (None, ) * len(proposals)
  184. result_list = self.bbox_head.predict_by_feat(
  185. rois=rois,
  186. cls_scores=cls_scores,
  187. bbox_preds=bbox_preds,
  188. batch_img_metas=batch_img_metas,
  189. rcnn_test_cfg=rcnn_test_cfg,
  190. rescale=rescale)
  191. return result_list