mask_rcnn.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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, HRFPN)
  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. if self.backbone.__class__.__name__.startswith('HRNet'):
  88. fpn = HRFPN()
  89. fpn.min_level = 2
  90. fpn.max_level = 6
  91. else:
  92. fpn = FPN(num_chan=num_chan,
  93. min_level=min_level,
  94. max_level=max_level,
  95. spatial_scale=spatial_scale)
  96. self.fpn = fpn
  97. self.num_classes = num_classes
  98. if rpn_head is None:
  99. if self.fpn is None:
  100. rpn_head = RPNHead(
  101. anchor_sizes=anchor_sizes,
  102. aspect_ratios=aspect_ratios,
  103. rpn_batch_size_per_im=rpn_batch_size_per_im,
  104. rpn_fg_fraction=rpn_fg_fraction,
  105. rpn_positive_overlap=rpn_positive_overlap,
  106. rpn_negative_overlap=rpn_negative_overlap,
  107. train_pre_nms_top_n=train_pre_nms_top_n,
  108. train_post_nms_top_n=train_post_nms_top_n,
  109. train_nms_thresh=train_nms_thresh,
  110. test_pre_nms_top_n=test_pre_nms_top_n,
  111. test_post_nms_top_n=test_post_nms_top_n,
  112. test_nms_thresh=test_nms_thresh)
  113. else:
  114. rpn_head = FPNRPNHead(
  115. anchor_start_size=anchor_sizes[0],
  116. aspect_ratios=aspect_ratios,
  117. num_chan=self.fpn.num_chan,
  118. min_level=self.fpn.min_level,
  119. max_level=self.fpn.max_level,
  120. rpn_batch_size_per_im=rpn_batch_size_per_im,
  121. rpn_fg_fraction=rpn_fg_fraction,
  122. rpn_positive_overlap=rpn_positive_overlap,
  123. rpn_negative_overlap=rpn_negative_overlap,
  124. train_pre_nms_top_n=train_pre_nms_top_n,
  125. train_post_nms_top_n=train_post_nms_top_n,
  126. train_nms_thresh=train_nms_thresh,
  127. test_pre_nms_top_n=test_pre_nms_top_n,
  128. test_post_nms_top_n=test_post_nms_top_n,
  129. test_nms_thresh=test_nms_thresh)
  130. self.rpn_head = rpn_head
  131. if roi_extractor is None:
  132. if self.fpn is None:
  133. roi_extractor = RoIAlign(
  134. resolution=14,
  135. spatial_scale=1. / 2**self.backbone.feature_maps[0])
  136. else:
  137. roi_extractor = FPNRoIAlign(sampling_ratio=2)
  138. self.roi_extractor = roi_extractor
  139. if bbox_head is None:
  140. if self.fpn is None:
  141. head = ResNetC5(
  142. layers=self.backbone.layers,
  143. norm_type=self.backbone.norm_type,
  144. freeze_norm=self.backbone.freeze_norm)
  145. else:
  146. head = TwoFCHead()
  147. bbox_head = BBoxHead(
  148. head=head,
  149. keep_top_k=keep_top_k,
  150. nms_threshold=nms_threshold,
  151. score_threshold=score_threshold,
  152. num_classes=num_classes)
  153. self.bbox_head = bbox_head
  154. if mask_head is None:
  155. mask_head = MaskHead(
  156. num_convs=num_convs,
  157. resolution=mask_head_resolution,
  158. num_classes=num_classes)
  159. self.mask_head = mask_head
  160. self.batch_size_per_im = batch_size_per_im
  161. self.fg_fraction = fg_fraction
  162. self.fg_thresh = fg_thresh
  163. self.bg_thresh_hi = bg_thresh_hi
  164. self.bg_thresh_lo = bg_thresh_lo
  165. self.bbox_reg_weights = bbox_reg_weights
  166. self.rpn_only = rpn_only
  167. self.fixed_input_shape = fixed_input_shape
  168. def build_net(self, inputs):
  169. im = inputs['image']
  170. im_info = inputs['im_info']
  171. # backbone
  172. body_feats = self.backbone(im)
  173. # FPN
  174. spatial_scale = None
  175. if self.fpn is not None:
  176. body_feats, spatial_scale = self.fpn.get_output(body_feats)
  177. # RPN proposals
  178. rois = self.rpn_head.get_proposals(body_feats, im_info, mode=self.mode)
  179. if self.mode == 'train':
  180. rpn_loss = self.rpn_head.get_loss(im_info, inputs['gt_box'],
  181. inputs['is_crowd'])
  182. outputs = fluid.layers.generate_proposal_labels(
  183. rpn_rois=rois,
  184. gt_classes=inputs['gt_label'],
  185. is_crowd=inputs['is_crowd'],
  186. gt_boxes=inputs['gt_box'],
  187. im_info=inputs['im_info'],
  188. batch_size_per_im=self.batch_size_per_im,
  189. fg_fraction=self.fg_fraction,
  190. fg_thresh=self.fg_thresh,
  191. bg_thresh_hi=self.bg_thresh_hi,
  192. bg_thresh_lo=self.bg_thresh_lo,
  193. bbox_reg_weights=self.bbox_reg_weights,
  194. class_nums=self.num_classes,
  195. use_random=self.rpn_head.use_random)
  196. rois = outputs[0]
  197. labels_int32 = outputs[1]
  198. if self.fpn is None:
  199. last_feat = body_feats[list(body_feats.keys())[-1]]
  200. roi_feat = self.roi_extractor(last_feat, rois)
  201. else:
  202. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  203. loss = self.bbox_head.get_loss(roi_feat, labels_int32,
  204. *outputs[2:])
  205. loss.update(rpn_loss)
  206. mask_rois, roi_has_mask_int32, mask_int32 = fluid.layers.generate_mask_labels(
  207. rois=rois,
  208. gt_classes=inputs['gt_label'],
  209. is_crowd=inputs['is_crowd'],
  210. gt_segms=inputs['gt_mask'],
  211. im_info=inputs['im_info'],
  212. labels_int32=labels_int32,
  213. num_classes=self.num_classes,
  214. resolution=self.mask_head.resolution)
  215. if self.fpn is None:
  216. bbox_head_feat = self.bbox_head.get_head_feat()
  217. feat = fluid.layers.gather(bbox_head_feat, roi_has_mask_int32)
  218. else:
  219. feat = self.roi_extractor(
  220. body_feats, mask_rois, spatial_scale, is_mask=True)
  221. mask_loss = self.mask_head.get_loss(feat, mask_int32)
  222. loss.update(mask_loss)
  223. total_loss = fluid.layers.sum(list(loss.values()))
  224. loss.update({'loss': total_loss})
  225. return loss
  226. else:
  227. if self.rpn_only:
  228. im_scale = fluid.layers.slice(
  229. im_info, [1], starts=[2], ends=[3])
  230. im_scale = fluid.layers.sequence_expand(im_scale, rois)
  231. rois = rois / im_scale
  232. return {'proposal': rois}
  233. mask_name = 'mask_pred'
  234. mask_pred, bbox_pred = self._eval(body_feats, mask_name, rois,
  235. im_info, inputs['im_shape'],
  236. spatial_scale)
  237. return OrderedDict(zip(['bbox', 'mask'], [bbox_pred, mask_pred]))
  238. def _eval(self,
  239. body_feats,
  240. mask_name,
  241. rois,
  242. im_info,
  243. im_shape,
  244. spatial_scale,
  245. bbox_pred=None):
  246. if not bbox_pred:
  247. if self.fpn is None:
  248. last_feat = body_feats[list(body_feats.keys())[-1]]
  249. roi_feat = self.roi_extractor(last_feat, rois)
  250. else:
  251. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  252. bbox_pred = self.bbox_head.get_prediction(roi_feat, rois, im_info,
  253. im_shape)
  254. bbox_pred = bbox_pred['bbox']
  255. # share weight
  256. bbox_shape = fluid.layers.shape(bbox_pred)
  257. bbox_size = fluid.layers.reduce_prod(bbox_shape)
  258. bbox_size = fluid.layers.reshape(bbox_size, [1, 1])
  259. size = fluid.layers.fill_constant([1, 1], value=6, dtype='int32')
  260. cond = fluid.layers.less_than(x=bbox_size, y=size)
  261. mask_pred = fluid.layers.create_global_var(
  262. shape=[1],
  263. value=0.0,
  264. dtype='float32',
  265. persistable=False,
  266. name=mask_name)
  267. with fluid.layers.control_flow.Switch() as switch:
  268. with switch.case(cond):
  269. fluid.layers.assign(input=bbox_pred, output=mask_pred)
  270. with switch.default():
  271. bbox = fluid.layers.slice(bbox_pred, [1], starts=[2], ends=[6])
  272. im_scale = fluid.layers.slice(
  273. im_info, [1], starts=[2], ends=[3])
  274. im_scale = fluid.layers.sequence_expand(im_scale, bbox)
  275. mask_rois = bbox * im_scale
  276. if self.fpn is None:
  277. last_feat = body_feats[list(body_feats.keys())[-1]]
  278. mask_feat = self.roi_extractor(last_feat, mask_rois)
  279. mask_feat = self.bbox_head.get_head_feat(mask_feat)
  280. else:
  281. mask_feat = self.roi_extractor(
  282. body_feats, mask_rois, spatial_scale, is_mask=True)
  283. mask_out = self.mask_head.get_prediction(mask_feat, bbox)
  284. fluid.layers.assign(input=mask_out, output=mask_pred)
  285. return mask_pred, bbox_pred
  286. def generate_inputs(self):
  287. inputs = OrderedDict()
  288. if self.fixed_input_shape is not None:
  289. input_shape = [
  290. None, 3, self.fixed_input_shape[1], self.fixed_input_shape[0]
  291. ]
  292. inputs['image'] = fluid.data(
  293. dtype='float32', shape=input_shape, name='image')
  294. else:
  295. inputs['image'] = fluid.data(
  296. dtype='float32', shape=[None, 3, None, None], name='image')
  297. if self.mode == 'train':
  298. inputs['im_info'] = fluid.data(
  299. dtype='float32', shape=[None, 3], name='im_info')
  300. inputs['gt_box'] = fluid.data(
  301. dtype='float32', shape=[None, 4], lod_level=1, name='gt_box')
  302. inputs['gt_label'] = fluid.data(
  303. dtype='int32', shape=[None, 1], lod_level=1, name='gt_label')
  304. inputs['is_crowd'] = fluid.data(
  305. dtype='int32', shape=[None, 1], lod_level=1, name='is_crowd')
  306. inputs['gt_mask'] = fluid.data(
  307. dtype='float32', shape=[None, 2], lod_level=3, name='gt_mask')
  308. elif self.mode == 'eval':
  309. inputs['im_info'] = fluid.data(
  310. dtype='float32', shape=[None, 3], name='im_info')
  311. inputs['im_id'] = fluid.data(
  312. dtype='int64', shape=[None, 1], name='im_id')
  313. inputs['im_shape'] = fluid.data(
  314. dtype='float32', shape=[None, 3], name='im_shape')
  315. elif self.mode == 'test':
  316. inputs['im_info'] = fluid.data(
  317. dtype='float32', shape=[None, 3], name='im_info')
  318. inputs['im_shape'] = fluid.data(
  319. dtype='float32', shape=[None, 3], name='im_shape')
  320. return inputs