mask_rcnn.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from collections import OrderedDict
  18. import copy
  19. import paddle.fluid as fluid
  20. from .fpn import FPN
  21. from .rpn_head import (RPNHead, FPNRPNHead)
  22. from .roi_extractor import (RoIAlign, FPNRoIAlign)
  23. from .bbox_head import (BBoxHead, TwoFCHead)
  24. from .mask_head import MaskHead
  25. from ..resnet import ResNetC5
  26. __all__ = ['MaskRCNN']
  27. class MaskRCNN(object):
  28. """
  29. Mask R-CNN architecture, see https://arxiv.org/abs/1703.06870
  30. Args:
  31. backbone (object): backbone instance
  32. rpn_head (object): `RPNhead` instance
  33. roi_extractor (object): ROI extractor instance
  34. bbox_head (object): `BBoxHead` instance
  35. mask_head (object): `MaskHead` instance
  36. fpn (object): feature pyramid network instance
  37. """
  38. def __init__(
  39. self,
  40. backbone,
  41. num_classes=81,
  42. mode='train',
  43. with_fpn=False,
  44. fpn=None,
  45. num_chan=256,
  46. min_level=2,
  47. max_level=6,
  48. spatial_scale=[1. / 32., 1. / 16., 1. / 8., 1. / 4.],
  49. #rpn_head
  50. rpn_only=False,
  51. rpn_head=None,
  52. anchor_sizes=[32, 64, 128, 256, 512],
  53. aspect_ratios=[0.5, 1.0, 2.0],
  54. rpn_batch_size_per_im=256,
  55. rpn_fg_fraction=0.5,
  56. rpn_positive_overlap=0.7,
  57. rpn_negative_overlap=0.3,
  58. train_pre_nms_top_n=12000,
  59. train_post_nms_top_n=2000,
  60. train_nms_thresh=0.7,
  61. test_pre_nms_top_n=6000,
  62. test_post_nms_top_n=1000,
  63. test_nms_thresh=0.7,
  64. #roi_extractor
  65. roi_extractor=None,
  66. #bbox_head
  67. bbox_head=None,
  68. keep_top_k=100,
  69. nms_threshold=0.5,
  70. score_threshold=0.05,
  71. #MaskHead
  72. mask_head=None,
  73. num_convs=0,
  74. mask_head_resolution=14,
  75. #bbox_assigner
  76. batch_size_per_im=512,
  77. fg_fraction=.25,
  78. fg_thresh=.5,
  79. bg_thresh_hi=.5,
  80. bg_thresh_lo=0.,
  81. bbox_reg_weights=[0.1, 0.1, 0.2, 0.2],
  82. fixed_input_shape=None):
  83. super(MaskRCNN, self).__init__()
  84. self.backbone = backbone
  85. self.mode = mode
  86. if with_fpn and fpn is None:
  87. fpn = FPN(
  88. num_chan=num_chan,
  89. min_level=min_level,
  90. max_level=max_level,
  91. spatial_scale=spatial_scale)
  92. self.fpn = fpn
  93. self.num_classes = num_classes
  94. if rpn_head is None:
  95. if self.fpn is None:
  96. rpn_head = RPNHead(
  97. anchor_sizes=anchor_sizes,
  98. aspect_ratios=aspect_ratios,
  99. rpn_batch_size_per_im=rpn_batch_size_per_im,
  100. rpn_fg_fraction=rpn_fg_fraction,
  101. rpn_positive_overlap=rpn_positive_overlap,
  102. rpn_negative_overlap=rpn_negative_overlap,
  103. train_pre_nms_top_n=train_pre_nms_top_n,
  104. train_post_nms_top_n=train_post_nms_top_n,
  105. train_nms_thresh=train_nms_thresh,
  106. test_pre_nms_top_n=test_pre_nms_top_n,
  107. test_post_nms_top_n=test_post_nms_top_n,
  108. test_nms_thresh=test_nms_thresh)
  109. else:
  110. rpn_head = FPNRPNHead(
  111. anchor_start_size=anchor_sizes[0],
  112. aspect_ratios=aspect_ratios,
  113. num_chan=self.fpn.num_chan,
  114. min_level=self.fpn.min_level,
  115. max_level=self.fpn.max_level,
  116. rpn_batch_size_per_im=rpn_batch_size_per_im,
  117. rpn_fg_fraction=rpn_fg_fraction,
  118. rpn_positive_overlap=rpn_positive_overlap,
  119. rpn_negative_overlap=rpn_negative_overlap,
  120. train_pre_nms_top_n=train_pre_nms_top_n,
  121. train_post_nms_top_n=train_post_nms_top_n,
  122. train_nms_thresh=train_nms_thresh,
  123. test_pre_nms_top_n=test_pre_nms_top_n,
  124. test_post_nms_top_n=test_post_nms_top_n,
  125. test_nms_thresh=test_nms_thresh)
  126. self.rpn_head = rpn_head
  127. if roi_extractor is None:
  128. if self.fpn is None:
  129. roi_extractor = RoIAlign(
  130. resolution=14,
  131. spatial_scale=1. / 2**self.backbone.feature_maps[0])
  132. else:
  133. roi_extractor = FPNRoIAlign(sampling_ratio=2)
  134. self.roi_extractor = roi_extractor
  135. if bbox_head is None:
  136. if self.fpn is None:
  137. head = ResNetC5(
  138. layers=self.backbone.layers,
  139. norm_type=self.backbone.norm_type,
  140. freeze_norm=self.backbone.freeze_norm)
  141. else:
  142. head = TwoFCHead()
  143. bbox_head = BBoxHead(
  144. head=head,
  145. keep_top_k=keep_top_k,
  146. nms_threshold=nms_threshold,
  147. score_threshold=score_threshold,
  148. num_classes=num_classes)
  149. self.bbox_head = bbox_head
  150. if mask_head is None:
  151. mask_head = MaskHead(
  152. num_convs=num_convs,
  153. resolution=mask_head_resolution,
  154. num_classes=num_classes)
  155. self.mask_head = mask_head
  156. self.batch_size_per_im = batch_size_per_im
  157. self.fg_fraction = fg_fraction
  158. self.fg_thresh = fg_thresh
  159. self.bg_thresh_hi = bg_thresh_hi
  160. self.bg_thresh_lo = bg_thresh_lo
  161. self.bbox_reg_weights = bbox_reg_weights
  162. self.rpn_only = rpn_only
  163. self.fixed_input_shape = fixed_input_shape
  164. def build_net(self, inputs):
  165. im = inputs['image']
  166. im_info = inputs['im_info']
  167. # backbone
  168. body_feats = self.backbone(im)
  169. # FPN
  170. spatial_scale = None
  171. if self.fpn is not None:
  172. body_feats, spatial_scale = self.fpn.get_output(body_feats)
  173. # RPN proposals
  174. rois = self.rpn_head.get_proposals(body_feats, im_info, mode=self.mode)
  175. if self.mode == 'train':
  176. rpn_loss = self.rpn_head.get_loss(im_info, inputs['gt_box'],
  177. inputs['is_crowd'])
  178. outputs = fluid.layers.generate_proposal_labels(
  179. rpn_rois=rois,
  180. gt_classes=inputs['gt_label'],
  181. is_crowd=inputs['is_crowd'],
  182. gt_boxes=inputs['gt_box'],
  183. im_info=inputs['im_info'],
  184. batch_size_per_im=self.batch_size_per_im,
  185. fg_fraction=self.fg_fraction,
  186. fg_thresh=self.fg_thresh,
  187. bg_thresh_hi=self.bg_thresh_hi,
  188. bg_thresh_lo=self.bg_thresh_lo,
  189. bbox_reg_weights=self.bbox_reg_weights,
  190. class_nums=self.num_classes,
  191. use_random=self.rpn_head.use_random)
  192. rois = outputs[0]
  193. labels_int32 = outputs[1]
  194. if self.fpn is None:
  195. last_feat = body_feats[list(body_feats.keys())[-1]]
  196. roi_feat = self.roi_extractor(last_feat, rois)
  197. else:
  198. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  199. loss = self.bbox_head.get_loss(roi_feat, labels_int32,
  200. *outputs[2:])
  201. loss.update(rpn_loss)
  202. mask_rois, roi_has_mask_int32, mask_int32 = fluid.layers.generate_mask_labels(
  203. rois=rois,
  204. gt_classes=inputs['gt_label'],
  205. is_crowd=inputs['is_crowd'],
  206. gt_segms=inputs['gt_mask'],
  207. im_info=inputs['im_info'],
  208. labels_int32=labels_int32,
  209. num_classes=self.num_classes,
  210. resolution=self.mask_head.resolution)
  211. if self.fpn is None:
  212. bbox_head_feat = self.bbox_head.get_head_feat()
  213. feat = fluid.layers.gather(bbox_head_feat, roi_has_mask_int32)
  214. else:
  215. feat = self.roi_extractor(
  216. body_feats, mask_rois, spatial_scale, is_mask=True)
  217. mask_loss = self.mask_head.get_loss(feat, mask_int32)
  218. loss.update(mask_loss)
  219. total_loss = fluid.layers.sum(list(loss.values()))
  220. loss.update({'loss': total_loss})
  221. return loss
  222. else:
  223. if self.rpn_only:
  224. im_scale = fluid.layers.slice(
  225. im_info, [1], starts=[2], ends=[3])
  226. im_scale = fluid.layers.sequence_expand(im_scale, rois)
  227. rois = rois / im_scale
  228. return {'proposal': rois}
  229. mask_name = 'mask_pred'
  230. mask_pred, bbox_pred = self._eval(body_feats, mask_name, rois,
  231. im_info, inputs['im_shape'],
  232. spatial_scale)
  233. return OrderedDict(zip(['bbox', 'mask'], [bbox_pred, mask_pred]))
  234. def _eval(self,
  235. body_feats,
  236. mask_name,
  237. rois,
  238. im_info,
  239. im_shape,
  240. spatial_scale,
  241. bbox_pred=None):
  242. if not bbox_pred:
  243. if self.fpn is None:
  244. last_feat = body_feats[list(body_feats.keys())[-1]]
  245. roi_feat = self.roi_extractor(last_feat, rois)
  246. else:
  247. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  248. bbox_pred = self.bbox_head.get_prediction(roi_feat, rois, im_info,
  249. im_shape)
  250. bbox_pred = bbox_pred['bbox']
  251. # share weight
  252. bbox_shape = fluid.layers.shape(bbox_pred)
  253. bbox_size = fluid.layers.reduce_prod(bbox_shape)
  254. bbox_size = fluid.layers.reshape(bbox_size, [1, 1])
  255. size = fluid.layers.fill_constant([1, 1], value=6, dtype='int32')
  256. cond = fluid.layers.less_than(x=bbox_size, y=size)
  257. mask_pred = fluid.layers.create_global_var(
  258. shape=[1],
  259. value=0.0,
  260. dtype='float32',
  261. persistable=False,
  262. name=mask_name)
  263. with fluid.layers.control_flow.Switch() as switch:
  264. with switch.case(cond):
  265. fluid.layers.assign(input=bbox_pred, output=mask_pred)
  266. with switch.default():
  267. bbox = fluid.layers.slice(bbox_pred, [1], starts=[2], ends=[6])
  268. im_scale = fluid.layers.slice(
  269. im_info, [1], starts=[2], ends=[3])
  270. im_scale = fluid.layers.sequence_expand(im_scale, bbox)
  271. mask_rois = bbox * im_scale
  272. if self.fpn is None:
  273. last_feat = body_feats[list(body_feats.keys())[-1]]
  274. mask_feat = self.roi_extractor(last_feat, mask_rois)
  275. mask_feat = self.bbox_head.get_head_feat(mask_feat)
  276. else:
  277. mask_feat = self.roi_extractor(
  278. body_feats, mask_rois, spatial_scale, is_mask=True)
  279. mask_out = self.mask_head.get_prediction(mask_feat, bbox)
  280. fluid.layers.assign(input=mask_out, output=mask_pred)
  281. return mask_pred, bbox_pred
  282. def generate_inputs(self):
  283. inputs = OrderedDict()
  284. if self.fixed_input_shape is not None:
  285. input_shape = [
  286. None, 3, self.fixed_input_shape[1], self.fixed_input_shape[0]
  287. ]
  288. inputs['image'] = fluid.data(
  289. dtype='float32', shape=input_shape, name='image')
  290. else:
  291. inputs['image'] = fluid.data(
  292. dtype='float32', shape=[None, 3, None, None], name='image')
  293. if self.mode == 'train':
  294. inputs['im_info'] = fluid.data(
  295. dtype='float32', shape=[None, 3], name='im_info')
  296. inputs['gt_box'] = fluid.data(
  297. dtype='float32', shape=[None, 4], lod_level=1, name='gt_box')
  298. inputs['gt_label'] = fluid.data(
  299. dtype='int32', shape=[None, 1], lod_level=1, name='gt_label')
  300. inputs['is_crowd'] = fluid.data(
  301. dtype='int32', shape=[None, 1], lod_level=1, name='is_crowd')
  302. inputs['gt_mask'] = fluid.data(
  303. dtype='float32', shape=[None, 2], lod_level=3, name='gt_mask')
  304. elif self.mode == 'eval':
  305. inputs['im_info'] = fluid.data(
  306. dtype='float32', shape=[None, 3], name='im_info')
  307. inputs['im_id'] = fluid.data(
  308. dtype='int64', shape=[None, 1], name='im_id')
  309. inputs['im_shape'] = fluid.data(
  310. dtype='float32', shape=[None, 3], name='im_shape')
  311. elif self.mode == 'test':
  312. inputs['im_info'] = fluid.data(
  313. dtype='float32', shape=[None, 3], name='im_info')
  314. inputs['im_shape'] = fluid.data(
  315. dtype='float32', shape=[None, 3], name='im_shape')
  316. return inputs