faster_rcnn.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. from paddle import 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 ..resnet import ResNetC5
  25. __all__ = ['FasterRCNN']
  26. class FasterRCNN(object):
  27. """
  28. Faster R-CNN architecture, see https://arxiv.org/abs/1506.01497
  29. Args:
  30. backbone (object): backbone instance
  31. rpn_head (object): `RPNhead` instance
  32. roi_extractor (object): ROI extractor instance
  33. bbox_head (object): `BBoxHead` instance
  34. fpn (object): feature pyramid network instance
  35. """
  36. def __init__(
  37. self,
  38. backbone,
  39. mode='train',
  40. num_classes=81,
  41. with_fpn=False,
  42. fpn=None,
  43. #rpn_head
  44. rpn_only=False,
  45. rpn_head=None,
  46. anchor_sizes=[32, 64, 128, 256, 512],
  47. aspect_ratios=[0.5, 1.0, 2.0],
  48. rpn_batch_size_per_im=256,
  49. rpn_fg_fraction=0.5,
  50. rpn_positive_overlap=0.7,
  51. rpn_negative_overlap=0.3,
  52. train_pre_nms_top_n=12000,
  53. train_post_nms_top_n=2000,
  54. train_nms_thresh=0.7,
  55. test_pre_nms_top_n=6000,
  56. test_post_nms_top_n=1000,
  57. test_nms_thresh=0.7,
  58. #roi_extractor
  59. roi_extractor=None,
  60. #bbox_head
  61. bbox_head=None,
  62. keep_top_k=100,
  63. nms_threshold=0.5,
  64. score_threshold=0.05,
  65. #bbox_assigner
  66. batch_size_per_im=512,
  67. fg_fraction=.25,
  68. fg_thresh=.5,
  69. bg_thresh_hi=.5,
  70. bg_thresh_lo=0.,
  71. bbox_reg_weights=[0.1, 0.1, 0.2, 0.2],
  72. fixed_input_shape=None):
  73. super(FasterRCNN, self).__init__()
  74. self.backbone = backbone
  75. self.mode = mode
  76. if with_fpn and fpn is None:
  77. if self.backbone.__class__.__name__.startswith('HRNet'):
  78. fpn = HRFPN()
  79. fpn.min_level = 2
  80. fpn.max_level = 6
  81. else:
  82. fpn = FPN()
  83. self.fpn = fpn
  84. self.num_classes = num_classes
  85. if rpn_head is None:
  86. if self.fpn is None:
  87. rpn_head = RPNHead(
  88. anchor_sizes=anchor_sizes,
  89. aspect_ratios=aspect_ratios,
  90. rpn_batch_size_per_im=rpn_batch_size_per_im,
  91. rpn_fg_fraction=rpn_fg_fraction,
  92. rpn_positive_overlap=rpn_positive_overlap,
  93. rpn_negative_overlap=rpn_negative_overlap,
  94. train_pre_nms_top_n=train_pre_nms_top_n,
  95. train_post_nms_top_n=train_post_nms_top_n,
  96. train_nms_thresh=train_nms_thresh,
  97. test_pre_nms_top_n=test_pre_nms_top_n,
  98. test_post_nms_top_n=test_post_nms_top_n,
  99. test_nms_thresh=test_nms_thresh)
  100. else:
  101. rpn_head = FPNRPNHead(
  102. anchor_start_size=anchor_sizes[0],
  103. aspect_ratios=aspect_ratios,
  104. num_chan=self.fpn.num_chan,
  105. min_level=self.fpn.min_level,
  106. max_level=self.fpn.max_level,
  107. rpn_batch_size_per_im=rpn_batch_size_per_im,
  108. rpn_fg_fraction=rpn_fg_fraction,
  109. rpn_positive_overlap=rpn_positive_overlap,
  110. rpn_negative_overlap=rpn_negative_overlap,
  111. train_pre_nms_top_n=train_pre_nms_top_n,
  112. train_post_nms_top_n=train_post_nms_top_n,
  113. train_nms_thresh=train_nms_thresh,
  114. test_pre_nms_top_n=test_pre_nms_top_n,
  115. test_post_nms_top_n=test_post_nms_top_n,
  116. test_nms_thresh=test_nms_thresh)
  117. self.rpn_head = rpn_head
  118. if roi_extractor is None:
  119. if self.fpn is None:
  120. roi_extractor = RoIAlign(
  121. resolution=14,
  122. spatial_scale=1. / 2**self.backbone.feature_maps[0])
  123. else:
  124. roi_extractor = FPNRoIAlign(sampling_ratio=2)
  125. self.roi_extractor = roi_extractor
  126. if bbox_head is None:
  127. if self.fpn is None:
  128. head = ResNetC5(
  129. layers=self.backbone.layers,
  130. norm_type=self.backbone.norm_type,
  131. freeze_norm=self.backbone.freeze_norm,
  132. variant=self.backbone.variant)
  133. else:
  134. head = TwoFCHead()
  135. bbox_head = BBoxHead(
  136. head=head,
  137. keep_top_k=keep_top_k,
  138. nms_threshold=nms_threshold,
  139. score_threshold=score_threshold,
  140. num_classes=num_classes)
  141. self.bbox_head = bbox_head
  142. self.batch_size_per_im = batch_size_per_im
  143. self.fg_fraction = fg_fraction
  144. self.fg_thresh = fg_thresh
  145. self.bg_thresh_hi = bg_thresh_hi
  146. self.bg_thresh_lo = bg_thresh_lo
  147. self.bbox_reg_weights = bbox_reg_weights
  148. self.rpn_only = rpn_only
  149. self.fixed_input_shape = fixed_input_shape
  150. def build_net(self, inputs):
  151. im = inputs['image']
  152. im_info = inputs['im_info']
  153. if self.mode == 'train':
  154. gt_bbox = inputs['gt_box']
  155. is_crowd = inputs['is_crowd']
  156. else:
  157. im_shape = inputs['im_shape']
  158. body_feats = self.backbone(im)
  159. body_feat_names = list(body_feats.keys())
  160. if self.fpn is not None:
  161. body_feats, spatial_scale = self.fpn.get_output(body_feats)
  162. rois = self.rpn_head.get_proposals(body_feats, im_info, mode=self.mode)
  163. if self.mode == 'train':
  164. rpn_loss = self.rpn_head.get_loss(im_info, gt_bbox, is_crowd)
  165. outputs = fluid.layers.generate_proposal_labels(
  166. rpn_rois=rois,
  167. gt_classes=inputs['gt_label'],
  168. is_crowd=inputs['is_crowd'],
  169. gt_boxes=inputs['gt_box'],
  170. im_info=inputs['im_info'],
  171. batch_size_per_im=self.batch_size_per_im,
  172. fg_fraction=self.fg_fraction,
  173. fg_thresh=self.fg_thresh,
  174. bg_thresh_hi=self.bg_thresh_hi,
  175. bg_thresh_lo=self.bg_thresh_lo,
  176. bbox_reg_weights=self.bbox_reg_weights,
  177. class_nums=self.num_classes,
  178. use_random=self.rpn_head.use_random)
  179. rois = outputs[0]
  180. labels_int32 = outputs[1]
  181. bbox_targets = outputs[2]
  182. bbox_inside_weights = outputs[3]
  183. bbox_outside_weights = outputs[4]
  184. else:
  185. if self.rpn_only:
  186. im_scale = fluid.layers.slice(
  187. im_info, [1], starts=[2], ends=[3])
  188. im_scale = fluid.layers.sequence_expand(im_scale, rois)
  189. rois = rois / im_scale
  190. return {'proposal': rois}
  191. if self.fpn is None:
  192. # in models without FPN, roi extractor only uses the last level of
  193. # feature maps. And body_feat_names[-1] represents the name of
  194. # last feature map.
  195. body_feat = body_feats[body_feat_names[-1]]
  196. roi_feat = self.roi_extractor(body_feat, rois)
  197. else:
  198. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  199. if self.mode == 'train':
  200. loss = self.bbox_head.get_loss(roi_feat, labels_int32,
  201. bbox_targets, bbox_inside_weights,
  202. bbox_outside_weights)
  203. loss.update(rpn_loss)
  204. total_loss = fluid.layers.sum(list(loss.values()))
  205. loss.update({'loss': total_loss})
  206. return loss
  207. else:
  208. pred = self.bbox_head.get_prediction(roi_feat, rois, im_info,
  209. im_shape)
  210. return pred
  211. def generate_inputs(self):
  212. inputs = OrderedDict()
  213. if self.fixed_input_shape is not None:
  214. input_shape = [
  215. None, 3, self.fixed_input_shape[1], self.fixed_input_shape[0]
  216. ]
  217. inputs['image'] = fluid.data(
  218. dtype='float32', shape=input_shape, name='image')
  219. else:
  220. inputs['image'] = fluid.data(
  221. dtype='float32', shape=[None, 3, None, None], name='image')
  222. if self.mode == 'train':
  223. inputs['im_info'] = fluid.data(
  224. dtype='float32', shape=[None, 3], name='im_info')
  225. inputs['gt_box'] = fluid.data(
  226. dtype='float32', shape=[None, 4], lod_level=1, name='gt_box')
  227. inputs['gt_label'] = fluid.data(
  228. dtype='int32', shape=[None, 1], lod_level=1, name='gt_label')
  229. inputs['is_crowd'] = fluid.data(
  230. dtype='int32', shape=[None, 1], lod_level=1, name='is_crowd')
  231. elif self.mode == 'eval':
  232. inputs['im_info'] = fluid.data(
  233. dtype='float32', shape=[None, 3], name='im_info')
  234. inputs['im_id'] = fluid.data(
  235. dtype='int64', shape=[None, 1], name='im_id')
  236. inputs['im_shape'] = fluid.data(
  237. dtype='float32', shape=[None, 3], name='im_shape')
  238. inputs['gt_box'] = fluid.data(
  239. dtype='float32', shape=[None, 4], lod_level=1, name='gt_box')
  240. inputs['gt_label'] = fluid.data(
  241. dtype='int32', shape=[None, 1], lod_level=1, name='gt_label')
  242. inputs['is_difficult'] = fluid.data(
  243. dtype='int32',
  244. shape=[None, 1],
  245. lod_level=1,
  246. name='is_difficult')
  247. elif self.mode == 'test':
  248. inputs['im_info'] = fluid.data(
  249. dtype='float32', shape=[None, 3], name='im_info')
  250. inputs['im_shape'] = fluid.data(
  251. dtype='float32', shape=[None, 3], name='im_shape')
  252. return inputs