maskiou_head.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import List, Tuple
  3. import numpy as np
  4. import torch
  5. import torch.nn as nn
  6. from mmcv.cnn import Conv2d, Linear, MaxPool2d
  7. from mmengine.config import ConfigDict
  8. from mmengine.model import BaseModule
  9. from mmengine.structures import InstanceData
  10. from torch import Tensor
  11. from torch.nn.modules.utils import _pair
  12. from mmdet.models.task_modules.samplers import SamplingResult
  13. from mmdet.registry import MODELS
  14. from mmdet.utils import ConfigType, InstanceList, OptMultiConfig
  15. @MODELS.register_module()
  16. class MaskIoUHead(BaseModule):
  17. """Mask IoU Head.
  18. This head predicts the IoU of predicted masks and corresponding gt masks.
  19. Args:
  20. num_convs (int): The number of convolution layers. Defaults to 4.
  21. num_fcs (int): The number of fully connected layers. Defaults to 2.
  22. roi_feat_size (int): RoI feature size. Default to 14.
  23. in_channels (int): The channel number of inputs features.
  24. Defaults to 256.
  25. conv_out_channels (int): The feature channels of convolution layers.
  26. Defaults to 256.
  27. fc_out_channels (int): The feature channels of fully connected layers.
  28. Defaults to 1024.
  29. num_classes (int): Number of categories excluding the background
  30. category. Defaults to 80.
  31. loss_iou (:obj:`ConfigDict` or dict): IoU loss.
  32. init_cfg (:obj:`ConfigDict` or dict or list[:obj:`ConfigDict` or \
  33. dict], optional): Initialization config dict.
  34. """
  35. def __init__(
  36. self,
  37. num_convs: int = 4,
  38. num_fcs: int = 2,
  39. roi_feat_size: int = 14,
  40. in_channels: int = 256,
  41. conv_out_channels: int = 256,
  42. fc_out_channels: int = 1024,
  43. num_classes: int = 80,
  44. loss_iou: ConfigType = dict(type='MSELoss', loss_weight=0.5),
  45. init_cfg: OptMultiConfig = [
  46. dict(type='Kaiming', override=dict(name='convs')),
  47. dict(type='Caffe2Xavier', override=dict(name='fcs')),
  48. dict(type='Normal', std=0.01, override=dict(name='fc_mask_iou'))
  49. ]
  50. ) -> None:
  51. super().__init__(init_cfg=init_cfg)
  52. self.in_channels = in_channels
  53. self.conv_out_channels = conv_out_channels
  54. self.fc_out_channels = fc_out_channels
  55. self.num_classes = num_classes
  56. self.convs = nn.ModuleList()
  57. for i in range(num_convs):
  58. if i == 0:
  59. # concatenation of mask feature and mask prediction
  60. in_channels = self.in_channels + 1
  61. else:
  62. in_channels = self.conv_out_channels
  63. stride = 2 if i == num_convs - 1 else 1
  64. self.convs.append(
  65. Conv2d(
  66. in_channels,
  67. self.conv_out_channels,
  68. 3,
  69. stride=stride,
  70. padding=1))
  71. roi_feat_size = _pair(roi_feat_size)
  72. pooled_area = (roi_feat_size[0] // 2) * (roi_feat_size[1] // 2)
  73. self.fcs = nn.ModuleList()
  74. for i in range(num_fcs):
  75. in_channels = (
  76. self.conv_out_channels *
  77. pooled_area if i == 0 else self.fc_out_channels)
  78. self.fcs.append(Linear(in_channels, self.fc_out_channels))
  79. self.fc_mask_iou = Linear(self.fc_out_channels, self.num_classes)
  80. self.relu = nn.ReLU()
  81. self.max_pool = MaxPool2d(2, 2)
  82. self.loss_iou = MODELS.build(loss_iou)
  83. def forward(self, mask_feat: Tensor, mask_preds: Tensor) -> Tensor:
  84. """Forward function.
  85. Args:
  86. mask_feat (Tensor): Mask features from upstream models.
  87. mask_preds (Tensor): Mask predictions from mask head.
  88. Returns:
  89. Tensor: Mask IoU predictions.
  90. """
  91. mask_preds = mask_preds.sigmoid()
  92. mask_pred_pooled = self.max_pool(mask_preds.unsqueeze(1))
  93. x = torch.cat((mask_feat, mask_pred_pooled), 1)
  94. for conv in self.convs:
  95. x = self.relu(conv(x))
  96. x = x.flatten(1)
  97. for fc in self.fcs:
  98. x = self.relu(fc(x))
  99. mask_iou = self.fc_mask_iou(x)
  100. return mask_iou
  101. def loss_and_target(self, mask_iou_pred: Tensor, mask_preds: Tensor,
  102. mask_targets: Tensor,
  103. sampling_results: List[SamplingResult],
  104. batch_gt_instances: InstanceList,
  105. rcnn_train_cfg: ConfigDict) -> dict:
  106. """Calculate the loss and targets of MaskIoUHead.
  107. Args:
  108. mask_iou_pred (Tensor): Mask IoU predictions results, has shape
  109. (num_pos, num_classes)
  110. mask_preds (Tensor): Mask predictions from mask head, has shape
  111. (num_pos, mask_size, mask_size).
  112. mask_targets (Tensor): The ground truth masks assigned with
  113. predictions, has shape
  114. (num_pos, mask_size, mask_size).
  115. sampling_results (List[obj:SamplingResult]): Assign results of
  116. all images in a batch after sampling.
  117. batch_gt_instances (list[:obj:`InstanceData`]): Batch of
  118. gt_instance. It includes ``masks`` inside.
  119. rcnn_train_cfg (obj:`ConfigDict`): `train_cfg` of RCNN.
  120. Returns:
  121. dict: A dictionary of loss and targets components.
  122. The targets are only used for cascade rcnn.
  123. """
  124. mask_iou_targets = self.get_targets(
  125. sampling_results=sampling_results,
  126. batch_gt_instances=batch_gt_instances,
  127. mask_preds=mask_preds,
  128. mask_targets=mask_targets,
  129. rcnn_train_cfg=rcnn_train_cfg)
  130. pos_inds = mask_iou_targets > 0
  131. if pos_inds.sum() > 0:
  132. loss_mask_iou = self.loss_iou(mask_iou_pred[pos_inds],
  133. mask_iou_targets[pos_inds])
  134. else:
  135. loss_mask_iou = mask_iou_pred.sum() * 0
  136. return dict(loss_mask_iou=loss_mask_iou)
  137. def get_targets(self, sampling_results: List[SamplingResult],
  138. batch_gt_instances: InstanceList, mask_preds: Tensor,
  139. mask_targets: Tensor,
  140. rcnn_train_cfg: ConfigDict) -> Tensor:
  141. """Compute target of mask IoU.
  142. Mask IoU target is the IoU of the predicted mask (inside a bbox) and
  143. the gt mask of corresponding gt mask (the whole instance).
  144. The intersection area is computed inside the bbox, and the gt mask area
  145. is computed with two steps, firstly we compute the gt area inside the
  146. bbox, then divide it by the area ratio of gt area inside the bbox and
  147. the gt area of the whole instance.
  148. Args:
  149. sampling_results (list[:obj:`SamplingResult`]): sampling results.
  150. batch_gt_instances (list[:obj:`InstanceData`]): Batch of
  151. gt_instance. It includes ``masks`` inside.
  152. mask_preds (Tensor): Predicted masks of each positive proposal,
  153. shape (num_pos, h, w).
  154. mask_targets (Tensor): Gt mask of each positive proposal,
  155. binary map of the shape (num_pos, h, w).
  156. rcnn_train_cfg (obj:`ConfigDict`): Training config for R-CNN part.
  157. Returns:
  158. Tensor: mask iou target (length == num positive).
  159. """
  160. pos_proposals = [res.pos_priors for res in sampling_results]
  161. pos_assigned_gt_inds = [
  162. res.pos_assigned_gt_inds for res in sampling_results
  163. ]
  164. gt_masks = [res.masks for res in batch_gt_instances]
  165. # compute the area ratio of gt areas inside the proposals and
  166. # the whole instance
  167. area_ratios = map(self._get_area_ratio, pos_proposals,
  168. pos_assigned_gt_inds, gt_masks)
  169. area_ratios = torch.cat(list(area_ratios))
  170. assert mask_targets.size(0) == area_ratios.size(0)
  171. mask_preds = (mask_preds > rcnn_train_cfg.mask_thr_binary).float()
  172. mask_pred_areas = mask_preds.sum((-1, -2))
  173. # mask_preds and mask_targets are binary maps
  174. overlap_areas = (mask_preds * mask_targets).sum((-1, -2))
  175. # compute the mask area of the whole instance
  176. gt_full_areas = mask_targets.sum((-1, -2)) / (area_ratios + 1e-7)
  177. mask_iou_targets = overlap_areas / (
  178. mask_pred_areas + gt_full_areas - overlap_areas)
  179. return mask_iou_targets
  180. def _get_area_ratio(self, pos_proposals: Tensor,
  181. pos_assigned_gt_inds: Tensor,
  182. gt_masks: InstanceData) -> Tensor:
  183. """Compute area ratio of the gt mask inside the proposal and the gt
  184. mask of the corresponding instance.
  185. Args:
  186. pos_proposals (Tensor): Positive proposals, has shape (num_pos, 4).
  187. pos_assigned_gt_inds (Tensor): positive proposals assigned ground
  188. truth index.
  189. gt_masks (BitmapMask or PolygonMask): Gt masks (the whole instance)
  190. of each image, with the same shape of the input image.
  191. Returns:
  192. Tensor: The area ratio of the gt mask inside the proposal and the
  193. gt mask of the corresponding instance.
  194. """
  195. num_pos = pos_proposals.size(0)
  196. if num_pos > 0:
  197. area_ratios = []
  198. proposals_np = pos_proposals.cpu().numpy()
  199. pos_assigned_gt_inds = pos_assigned_gt_inds.cpu().numpy()
  200. # compute mask areas of gt instances (batch processing for speedup)
  201. gt_instance_mask_area = gt_masks.areas
  202. for i in range(num_pos):
  203. gt_mask = gt_masks[pos_assigned_gt_inds[i]]
  204. # crop the gt mask inside the proposal
  205. bbox = proposals_np[i, :].astype(np.int32)
  206. gt_mask_in_proposal = gt_mask.crop(bbox)
  207. ratio = gt_mask_in_proposal.areas[0] / (
  208. gt_instance_mask_area[pos_assigned_gt_inds[i]] + 1e-7)
  209. area_ratios.append(ratio)
  210. area_ratios = torch.from_numpy(np.stack(area_ratios)).float().to(
  211. pos_proposals.device)
  212. else:
  213. area_ratios = pos_proposals.new_zeros((0, ))
  214. return area_ratios
  215. def predict_by_feat(self, mask_iou_preds: Tuple[Tensor],
  216. results_list: InstanceList) -> InstanceList:
  217. """Predict the mask iou and calculate it into ``results.scores``.
  218. Args:
  219. mask_iou_preds (Tensor): Mask IoU predictions results, has shape
  220. (num_proposals, num_classes)
  221. results_list (list[:obj:`InstanceData`]): Detection results of
  222. each image.
  223. Returns:
  224. list[:obj:`InstanceData`]: Detection results of each image
  225. after the post process. Each item usually contains following keys.
  226. - scores (Tensor): Classification scores, has a shape
  227. (num_instance, )
  228. - labels (Tensor): Labels of bboxes, has a shape
  229. (num_instances, ).
  230. - bboxes (Tensor): Has a shape (num_instances, 4),
  231. the last dimension 4 arrange as (x1, y1, x2, y2).
  232. - masks (Tensor): Has a shape (num_instances, H, W).
  233. """
  234. assert len(mask_iou_preds) == len(results_list)
  235. for results, mask_iou_pred in zip(results_list, mask_iou_preds):
  236. labels = results.labels
  237. scores = results.scores
  238. results.scores = scores * mask_iou_pred[range(labels.size(0)),
  239. labels]
  240. return results_list