mask_rcnn.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. # Copyright (c) 2019 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 ppdet.experimental import mixed_precision_global_state
  21. from ppdet.core.workspace import register
  22. from .input_helper import multiscale_def
  23. __all__ = ['MaskRCNN']
  24. @register
  25. class MaskRCNN(object):
  26. """
  27. Mask R-CNN architecture, see https://arxiv.org/abs/1703.06870
  28. Args:
  29. backbone (object): backbone instance
  30. rpn_head (object): `RPNhead` instance
  31. bbox_assigner (object): `BBoxAssigner` instance
  32. roi_extractor (object): ROI extractor instance
  33. bbox_head (object): `BBoxHead` instance
  34. mask_assigner (object): `MaskAssigner` instance
  35. mask_head (object): `MaskHead` instance
  36. fpn (object): feature pyramid network instance
  37. """
  38. __category__ = 'architecture'
  39. __inject__ = [
  40. 'backbone', 'rpn_head', 'bbox_assigner', 'roi_extractor', 'bbox_head',
  41. 'mask_assigner', 'mask_head', 'fpn'
  42. ]
  43. def __init__(self,
  44. backbone,
  45. rpn_head,
  46. bbox_head='BBoxHead',
  47. bbox_assigner='BBoxAssigner',
  48. roi_extractor='RoIAlign',
  49. mask_assigner='MaskAssigner',
  50. mask_head='MaskHead',
  51. rpn_only=False,
  52. fpn=None):
  53. super(MaskRCNN, self).__init__()
  54. self.backbone = backbone
  55. self.rpn_head = rpn_head
  56. self.bbox_assigner = bbox_assigner
  57. self.roi_extractor = roi_extractor
  58. self.bbox_head = bbox_head
  59. self.mask_assigner = mask_assigner
  60. self.mask_head = mask_head
  61. self.rpn_only = rpn_only
  62. self.fpn = fpn
  63. def build(self, feed_vars, mode='train'):
  64. if mode == 'train':
  65. required_fields = [
  66. 'gt_class', 'gt_bbox', 'gt_mask', 'is_crowd', 'im_info'
  67. ]
  68. else:
  69. required_fields = ['im_shape', 'im_info']
  70. self._input_check(required_fields, feed_vars)
  71. im = feed_vars['image']
  72. im_info = feed_vars['im_info']
  73. mixed_precision_enabled = mixed_precision_global_state() is not None
  74. # cast inputs to FP16
  75. if mixed_precision_enabled:
  76. im = fluid.layers.cast(im, 'float16')
  77. # backbone
  78. body_feats = self.backbone(im)
  79. # cast features back to FP32
  80. if mixed_precision_enabled:
  81. body_feats = OrderedDict((k, fluid.layers.cast(v, 'float32'))
  82. for k, v in body_feats.items())
  83. # FPN
  84. spatial_scale = None
  85. if self.fpn is not None:
  86. body_feats, spatial_scale = self.fpn.get_output(body_feats)
  87. # RPN proposals
  88. rois = self.rpn_head.get_proposals(body_feats, im_info, mode=mode)
  89. if mode == 'train':
  90. rpn_loss = self.rpn_head.get_loss(im_info, feed_vars['gt_bbox'],
  91. feed_vars['is_crowd'])
  92. outs = self.bbox_assigner(
  93. rpn_rois=rois,
  94. gt_classes=feed_vars['gt_class'],
  95. is_crowd=feed_vars['is_crowd'],
  96. gt_boxes=feed_vars['gt_bbox'],
  97. im_info=feed_vars['im_info'])
  98. rois = outs[0]
  99. labels_int32 = outs[1]
  100. if self.fpn is None:
  101. last_feat = body_feats[list(body_feats.keys())[-1]]
  102. roi_feat = self.roi_extractor(last_feat, rois)
  103. else:
  104. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  105. loss = self.bbox_head.get_loss(roi_feat, labels_int32, *outs[2:])
  106. loss.update(rpn_loss)
  107. mask_rois, roi_has_mask_int32, mask_int32 = self.mask_assigner(
  108. rois=rois,
  109. gt_classes=feed_vars['gt_class'],
  110. is_crowd=feed_vars['is_crowd'],
  111. gt_segms=feed_vars['gt_mask'],
  112. im_info=feed_vars['im_info'],
  113. labels_int32=labels_int32)
  114. if self.fpn is None:
  115. bbox_head_feat = self.bbox_head.get_head_feat()
  116. feat = fluid.layers.gather(bbox_head_feat, roi_has_mask_int32)
  117. else:
  118. feat = self.roi_extractor(
  119. body_feats, mask_rois, spatial_scale, is_mask=True)
  120. mask_loss = self.mask_head.get_loss(feat, mask_int32)
  121. loss.update(mask_loss)
  122. total_loss = fluid.layers.sum(list(loss.values()))
  123. loss.update({'loss': total_loss})
  124. return loss
  125. else:
  126. if self.rpn_only:
  127. im_scale = fluid.layers.slice(
  128. im_info, [1], starts=[2], ends=[3])
  129. im_scale = fluid.layers.sequence_expand(im_scale, rois)
  130. rois = rois / im_scale
  131. return {'proposal': rois}
  132. mask_name = 'mask_pred'
  133. mask_pred, bbox_pred = self.single_scale_eval(
  134. body_feats, mask_name, rois, im_info, feed_vars['im_shape'],
  135. spatial_scale)
  136. return {'bbox': bbox_pred, 'mask': mask_pred}
  137. def build_multi_scale(self, feed_vars, mask_branch=False):
  138. required_fields = ['image', 'im_info']
  139. self._input_check(required_fields, feed_vars)
  140. result = {}
  141. if not mask_branch:
  142. assert 'im_shape' in feed_vars, \
  143. "{} has no im_shape field".format(feed_vars)
  144. result.update(feed_vars)
  145. for i in range(len(self.im_info_names) // 2):
  146. im = feed_vars[self.im_info_names[2 * i]]
  147. im_info = feed_vars[self.im_info_names[2 * i + 1]]
  148. body_feats = self.backbone(im)
  149. # FPN
  150. if self.fpn is not None:
  151. body_feats, spatial_scale = self.fpn.get_output(body_feats)
  152. rois = self.rpn_head.get_proposals(body_feats, im_info, mode='test')
  153. if not mask_branch:
  154. im_shape = feed_vars['im_shape']
  155. body_feat_names = list(body_feats.keys())
  156. if self.fpn is None:
  157. body_feat = body_feats[body_feat_names[-1]]
  158. roi_feat = self.roi_extractor(body_feat, rois)
  159. else:
  160. roi_feat = self.roi_extractor(body_feats, rois,
  161. spatial_scale)
  162. pred = self.bbox_head.get_prediction(
  163. roi_feat, rois, im_info, im_shape, return_box_score=True)
  164. bbox_name = 'bbox_' + str(i)
  165. score_name = 'score_' + str(i)
  166. if 'flip' in im.name:
  167. bbox_name += '_flip'
  168. score_name += '_flip'
  169. result[bbox_name] = pred['bbox']
  170. result[score_name] = pred['score']
  171. else:
  172. mask_name = 'mask_pred_' + str(i)
  173. bbox_pred = feed_vars['bbox']
  174. #result.update({im.name: im})
  175. if 'flip' in im.name:
  176. mask_name += '_flip'
  177. bbox_pred = feed_vars['bbox_flip']
  178. mask_pred, bbox_pred = self.single_scale_eval(
  179. body_feats, mask_name, rois, im_info, feed_vars['im_shape'],
  180. spatial_scale, bbox_pred)
  181. result[mask_name] = mask_pred
  182. return result
  183. def single_scale_eval(self,
  184. body_feats,
  185. mask_name,
  186. rois,
  187. im_info,
  188. im_shape,
  189. spatial_scale,
  190. bbox_pred=None):
  191. if not bbox_pred:
  192. if self.fpn is None:
  193. last_feat = body_feats[list(body_feats.keys())[-1]]
  194. roi_feat = self.roi_extractor(last_feat, rois)
  195. else:
  196. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  197. bbox_pred = self.bbox_head.get_prediction(roi_feat, rois, im_info,
  198. im_shape)
  199. bbox_pred = bbox_pred['bbox']
  200. # share weight
  201. bbox_shape = fluid.layers.shape(bbox_pred)
  202. bbox_size = fluid.layers.reduce_prod(bbox_shape)
  203. bbox_size = fluid.layers.reshape(bbox_size, [1, 1])
  204. size = fluid.layers.fill_constant([1, 1], value=6, dtype='int32')
  205. cond = fluid.layers.less_than(x=bbox_size, y=size)
  206. mask_pred = fluid.layers.create_global_var(
  207. shape=[1],
  208. value=0.0,
  209. dtype='float32',
  210. persistable=False,
  211. name=mask_name)
  212. def noop():
  213. fluid.layers.assign(input=bbox_pred, output=mask_pred)
  214. def process_boxes():
  215. bbox = fluid.layers.slice(bbox_pred, [1], starts=[2], ends=[6])
  216. im_scale = fluid.layers.slice(im_info, [1], starts=[2], ends=[3])
  217. im_scale = fluid.layers.sequence_expand(im_scale, bbox)
  218. mask_rois = bbox * im_scale
  219. if self.fpn is None:
  220. last_feat = body_feats[list(body_feats.keys())[-1]]
  221. mask_feat = self.roi_extractor(last_feat, mask_rois)
  222. mask_feat = self.bbox_head.get_head_feat(mask_feat)
  223. else:
  224. mask_feat = self.roi_extractor(
  225. body_feats, mask_rois, spatial_scale, is_mask=True)
  226. mask_out = self.mask_head.get_prediction(mask_feat, bbox)
  227. fluid.layers.assign(input=mask_out, output=mask_pred)
  228. fluid.layers.cond(cond, noop, process_boxes)
  229. return mask_pred, bbox_pred
  230. def _input_check(self, require_fields, feed_vars):
  231. for var in require_fields:
  232. assert var in feed_vars, \
  233. "{} has no {} field".format(feed_vars, var)
  234. def _inputs_def(self, image_shape):
  235. im_shape = [None] + image_shape
  236. # yapf: disable
  237. inputs_def = {
  238. 'image': {'shape': im_shape, 'dtype': 'float32', 'lod_level': 0},
  239. 'im_info': {'shape': [None, 3], 'dtype': 'float32', 'lod_level': 0},
  240. 'im_id': {'shape': [None, 1], 'dtype': 'int64', 'lod_level': 0},
  241. 'im_shape': {'shape': [None, 3], 'dtype': 'float32', 'lod_level': 0},
  242. 'gt_bbox': {'shape': [None, 4], 'dtype': 'float32', 'lod_level': 1},
  243. 'gt_class': {'shape': [None, 1], 'dtype': 'int32', 'lod_level': 1},
  244. 'is_crowd': {'shape': [None, 1], 'dtype': 'int32', 'lod_level': 1},
  245. 'gt_mask': {'shape': [None, 2], 'dtype': 'float32', 'lod_level': 3}, # polygon coordinates
  246. 'is_difficult': {'shape': [None, 1], 'dtype': 'int32', 'lod_level': 1},
  247. }
  248. # yapf: enable
  249. return inputs_def
  250. def build_inputs(self,
  251. image_shape=[3, None, None],
  252. fields=[
  253. 'image', 'im_info', 'im_id', 'gt_bbox', 'gt_class',
  254. 'is_crowd', 'gt_mask'
  255. ],
  256. multi_scale=False,
  257. num_scales=-1,
  258. use_flip=None,
  259. use_dataloader=True,
  260. iterable=False,
  261. mask_branch=False):
  262. inputs_def = self._inputs_def(image_shape)
  263. fields = copy.deepcopy(fields)
  264. if multi_scale:
  265. ms_def, ms_fields = multiscale_def(image_shape, num_scales,
  266. use_flip)
  267. inputs_def.update(ms_def)
  268. fields += ms_fields
  269. self.im_info_names = ['image', 'im_info'] + ms_fields
  270. if mask_branch:
  271. box_fields = ['bbox', 'bbox_flip'] if use_flip else ['bbox']
  272. for key in box_fields:
  273. inputs_def[key] = {
  274. 'shape': [None, 6],
  275. 'dtype': 'float32',
  276. 'lod_level': 1
  277. }
  278. fields += box_fields
  279. feed_vars = OrderedDict([(key, fluid.data(
  280. name=key,
  281. shape=inputs_def[key]['shape'],
  282. dtype=inputs_def[key]['dtype'],
  283. lod_level=inputs_def[key]['lod_level'])) for key in fields])
  284. use_dataloader = use_dataloader and not mask_branch
  285. loader = fluid.io.DataLoader.from_generator(
  286. feed_list=list(feed_vars.values()),
  287. capacity=16,
  288. use_double_buffer=True,
  289. iterable=iterable) if use_dataloader else None
  290. return feed_vars, loader
  291. def train(self, feed_vars):
  292. return self.build(feed_vars, 'train')
  293. def eval(self, feed_vars, multi_scale=None, mask_branch=False):
  294. if multi_scale:
  295. return self.build_multi_scale(feed_vars, mask_branch)
  296. return self.build(feed_vars, 'test')
  297. def test(self, feed_vars, exclude_nms=False):
  298. assert not exclude_nms, "exclude_nms for {} is not support currently".format(
  299. self.__class__.__name__)
  300. return self.build(feed_vars, 'test')