You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

maskiou_head.py 7.4 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import numpy as np
  3. import torch
  4. import torch.nn as nn
  5. from mmcv.cnn import Conv2d, Linear, MaxPool2d
  6. from mmcv.runner import BaseModule, force_fp32
  7. from torch.nn.modules.utils import _pair
  8. from mmdet.models.builder import HEADS, build_loss
  9. @HEADS.register_module()
  10. class MaskIoUHead(BaseModule):
  11. """Mask IoU Head.
  12. This head predicts the IoU of predicted masks and corresponding gt masks.
  13. """
  14. def __init__(self,
  15. num_convs=4,
  16. num_fcs=2,
  17. roi_feat_size=14,
  18. in_channels=256,
  19. conv_out_channels=256,
  20. fc_out_channels=1024,
  21. num_classes=80,
  22. loss_iou=dict(type='MSELoss', loss_weight=0.5),
  23. init_cfg=[
  24. dict(type='Kaiming', override=dict(name='convs')),
  25. dict(type='Caffe2Xavier', override=dict(name='fcs')),
  26. dict(
  27. type='Normal',
  28. std=0.01,
  29. override=dict(name='fc_mask_iou'))
  30. ]):
  31. super(MaskIoUHead, self).__init__(init_cfg)
  32. self.in_channels = in_channels
  33. self.conv_out_channels = conv_out_channels
  34. self.fc_out_channels = fc_out_channels
  35. self.num_classes = num_classes
  36. self.fp16_enabled = False
  37. self.convs = nn.ModuleList()
  38. for i in range(num_convs):
  39. if i == 0:
  40. # concatenation of mask feature and mask prediction
  41. in_channels = self.in_channels + 1
  42. else:
  43. in_channels = self.conv_out_channels
  44. stride = 2 if i == num_convs - 1 else 1
  45. self.convs.append(
  46. Conv2d(
  47. in_channels,
  48. self.conv_out_channels,
  49. 3,
  50. stride=stride,
  51. padding=1))
  52. roi_feat_size = _pair(roi_feat_size)
  53. pooled_area = (roi_feat_size[0] // 2) * (roi_feat_size[1] // 2)
  54. self.fcs = nn.ModuleList()
  55. for i in range(num_fcs):
  56. in_channels = (
  57. self.conv_out_channels *
  58. pooled_area if i == 0 else self.fc_out_channels)
  59. self.fcs.append(Linear(in_channels, self.fc_out_channels))
  60. self.fc_mask_iou = Linear(self.fc_out_channels, self.num_classes)
  61. self.relu = nn.ReLU()
  62. self.max_pool = MaxPool2d(2, 2)
  63. self.loss_iou = build_loss(loss_iou)
  64. def forward(self, mask_feat, mask_pred):
  65. mask_pred = mask_pred.sigmoid()
  66. mask_pred_pooled = self.max_pool(mask_pred.unsqueeze(1))
  67. x = torch.cat((mask_feat, mask_pred_pooled), 1)
  68. for conv in self.convs:
  69. x = self.relu(conv(x))
  70. x = x.flatten(1)
  71. for fc in self.fcs:
  72. x = self.relu(fc(x))
  73. mask_iou = self.fc_mask_iou(x)
  74. return mask_iou
  75. @force_fp32(apply_to=('mask_iou_pred', ))
  76. def loss(self, mask_iou_pred, mask_iou_targets):
  77. pos_inds = mask_iou_targets > 0
  78. if pos_inds.sum() > 0:
  79. loss_mask_iou = self.loss_iou(mask_iou_pred[pos_inds],
  80. mask_iou_targets[pos_inds])
  81. else:
  82. loss_mask_iou = mask_iou_pred.sum() * 0
  83. return dict(loss_mask_iou=loss_mask_iou)
  84. @force_fp32(apply_to=('mask_pred', ))
  85. def get_targets(self, sampling_results, gt_masks, mask_pred, mask_targets,
  86. rcnn_train_cfg):
  87. """Compute target of mask IoU.
  88. Mask IoU target is the IoU of the predicted mask (inside a bbox) and
  89. the gt mask of corresponding gt mask (the whole instance).
  90. The intersection area is computed inside the bbox, and the gt mask area
  91. is computed with two steps, firstly we compute the gt area inside the
  92. bbox, then divide it by the area ratio of gt area inside the bbox and
  93. the gt area of the whole instance.
  94. Args:
  95. sampling_results (list[:obj:`SamplingResult`]): sampling results.
  96. gt_masks (BitmapMask | PolygonMask): Gt masks (the whole instance)
  97. of each image, with the same shape of the input image.
  98. mask_pred (Tensor): Predicted masks of each positive proposal,
  99. shape (num_pos, h, w).
  100. mask_targets (Tensor): Gt mask of each positive proposal,
  101. binary map of the shape (num_pos, h, w).
  102. rcnn_train_cfg (dict): Training config for R-CNN part.
  103. Returns:
  104. Tensor: mask iou target (length == num positive).
  105. """
  106. pos_proposals = [res.pos_bboxes for res in sampling_results]
  107. pos_assigned_gt_inds = [
  108. res.pos_assigned_gt_inds for res in sampling_results
  109. ]
  110. # compute the area ratio of gt areas inside the proposals and
  111. # the whole instance
  112. area_ratios = map(self._get_area_ratio, pos_proposals,
  113. pos_assigned_gt_inds, gt_masks)
  114. area_ratios = torch.cat(list(area_ratios))
  115. assert mask_targets.size(0) == area_ratios.size(0)
  116. mask_pred = (mask_pred > rcnn_train_cfg.mask_thr_binary).float()
  117. mask_pred_areas = mask_pred.sum((-1, -2))
  118. # mask_pred and mask_targets are binary maps
  119. overlap_areas = (mask_pred * mask_targets).sum((-1, -2))
  120. # compute the mask area of the whole instance
  121. gt_full_areas = mask_targets.sum((-1, -2)) / (area_ratios + 1e-7)
  122. mask_iou_targets = overlap_areas / (
  123. mask_pred_areas + gt_full_areas - overlap_areas)
  124. return mask_iou_targets
  125. def _get_area_ratio(self, pos_proposals, pos_assigned_gt_inds, gt_masks):
  126. """Compute area ratio of the gt mask inside the proposal and the gt
  127. mask of the corresponding instance."""
  128. num_pos = pos_proposals.size(0)
  129. if num_pos > 0:
  130. area_ratios = []
  131. proposals_np = pos_proposals.cpu().numpy()
  132. pos_assigned_gt_inds = pos_assigned_gt_inds.cpu().numpy()
  133. # compute mask areas of gt instances (batch processing for speedup)
  134. gt_instance_mask_area = gt_masks.areas
  135. for i in range(num_pos):
  136. gt_mask = gt_masks[pos_assigned_gt_inds[i]]
  137. # crop the gt mask inside the proposal
  138. bbox = proposals_np[i, :].astype(np.int32)
  139. gt_mask_in_proposal = gt_mask.crop(bbox)
  140. ratio = gt_mask_in_proposal.areas[0] / (
  141. gt_instance_mask_area[pos_assigned_gt_inds[i]] + 1e-7)
  142. area_ratios.append(ratio)
  143. area_ratios = torch.from_numpy(np.stack(area_ratios)).float().to(
  144. pos_proposals.device)
  145. else:
  146. area_ratios = pos_proposals.new_zeros((0, ))
  147. return area_ratios
  148. @force_fp32(apply_to=('mask_iou_pred', ))
  149. def get_mask_scores(self, mask_iou_pred, det_bboxes, det_labels):
  150. """Get the mask scores.
  151. mask_score = bbox_score * mask_iou
  152. """
  153. inds = range(det_labels.size(0))
  154. mask_scores = mask_iou_pred[inds, det_labels] * det_bboxes[inds, -1]
  155. mask_scores = mask_scores.cpu().numpy()
  156. det_labels = det_labels.cpu().numpy()
  157. return [mask_scores[det_labels == i] for i in range(self.num_classes)]

No Description

Contributors (3)