faster_rcnn.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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
  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. fpn = FPN()
  78. self.fpn = fpn
  79. self.num_classes = num_classes
  80. if rpn_head is None:
  81. if self.fpn is None:
  82. rpn_head = RPNHead(
  83. anchor_sizes=anchor_sizes,
  84. aspect_ratios=aspect_ratios,
  85. rpn_batch_size_per_im=rpn_batch_size_per_im,
  86. rpn_fg_fraction=rpn_fg_fraction,
  87. rpn_positive_overlap=rpn_positive_overlap,
  88. rpn_negative_overlap=rpn_negative_overlap,
  89. train_pre_nms_top_n=train_pre_nms_top_n,
  90. train_post_nms_top_n=train_post_nms_top_n,
  91. train_nms_thresh=train_nms_thresh,
  92. test_pre_nms_top_n=test_pre_nms_top_n,
  93. test_post_nms_top_n=test_post_nms_top_n,
  94. test_nms_thresh=test_nms_thresh)
  95. else:
  96. rpn_head = FPNRPNHead(
  97. anchor_start_size=anchor_sizes[0],
  98. aspect_ratios=aspect_ratios,
  99. num_chan=self.fpn.num_chan,
  100. min_level=self.fpn.min_level,
  101. max_level=self.fpn.max_level,
  102. rpn_batch_size_per_im=rpn_batch_size_per_im,
  103. rpn_fg_fraction=rpn_fg_fraction,
  104. rpn_positive_overlap=rpn_positive_overlap,
  105. rpn_negative_overlap=rpn_negative_overlap,
  106. train_pre_nms_top_n=train_pre_nms_top_n,
  107. train_post_nms_top_n=train_post_nms_top_n,
  108. train_nms_thresh=train_nms_thresh,
  109. test_pre_nms_top_n=test_pre_nms_top_n,
  110. test_post_nms_top_n=test_post_nms_top_n,
  111. test_nms_thresh=test_nms_thresh)
  112. self.rpn_head = rpn_head
  113. if roi_extractor is None:
  114. if self.fpn is None:
  115. roi_extractor = RoIAlign(
  116. resolution=14,
  117. spatial_scale=1. / 2**self.backbone.feature_maps[0])
  118. else:
  119. roi_extractor = FPNRoIAlign(sampling_ratio=2)
  120. self.roi_extractor = roi_extractor
  121. if bbox_head is None:
  122. if self.fpn is None:
  123. head = ResNetC5(
  124. layers=self.backbone.layers,
  125. norm_type=self.backbone.norm_type,
  126. freeze_norm=self.backbone.freeze_norm,
  127. variant=self.backbone.variant)
  128. else:
  129. head = TwoFCHead()
  130. bbox_head = BBoxHead(
  131. head=head,
  132. keep_top_k=keep_top_k,
  133. nms_threshold=nms_threshold,
  134. score_threshold=score_threshold,
  135. num_classes=num_classes)
  136. self.bbox_head = bbox_head
  137. self.batch_size_per_im = batch_size_per_im
  138. self.fg_fraction = fg_fraction
  139. self.fg_thresh = fg_thresh
  140. self.bg_thresh_hi = bg_thresh_hi
  141. self.bg_thresh_lo = bg_thresh_lo
  142. self.bbox_reg_weights = bbox_reg_weights
  143. self.rpn_only = rpn_only
  144. self.fixed_input_shape = fixed_input_shape
  145. def build_net(self, inputs):
  146. im = inputs['image']
  147. im_info = inputs['im_info']
  148. if self.mode == 'train':
  149. gt_bbox = inputs['gt_box']
  150. is_crowd = inputs['is_crowd']
  151. else:
  152. im_shape = inputs['im_shape']
  153. body_feats = self.backbone(im)
  154. body_feat_names = list(body_feats.keys())
  155. if self.fpn is not None:
  156. body_feats, spatial_scale = self.fpn.get_output(body_feats)
  157. rois = self.rpn_head.get_proposals(body_feats, im_info, mode=self.mode)
  158. if self.mode == 'train':
  159. rpn_loss = self.rpn_head.get_loss(im_info, gt_bbox, is_crowd)
  160. outputs = fluid.layers.generate_proposal_labels(
  161. rpn_rois=rois,
  162. gt_classes=inputs['gt_label'],
  163. is_crowd=inputs['is_crowd'],
  164. gt_boxes=inputs['gt_box'],
  165. im_info=inputs['im_info'],
  166. batch_size_per_im=self.batch_size_per_im,
  167. fg_fraction=self.fg_fraction,
  168. fg_thresh=self.fg_thresh,
  169. bg_thresh_hi=self.bg_thresh_hi,
  170. bg_thresh_lo=self.bg_thresh_lo,
  171. bbox_reg_weights=self.bbox_reg_weights,
  172. class_nums=self.num_classes,
  173. use_random=self.rpn_head.use_random)
  174. rois = outputs[0]
  175. labels_int32 = outputs[1]
  176. bbox_targets = outputs[2]
  177. bbox_inside_weights = outputs[3]
  178. bbox_outside_weights = outputs[4]
  179. else:
  180. if self.rpn_only:
  181. im_scale = fluid.layers.slice(
  182. im_info, [1], starts=[2], ends=[3])
  183. im_scale = fluid.layers.sequence_expand(im_scale, rois)
  184. rois = rois / im_scale
  185. return {'proposal': rois}
  186. if self.fpn is None:
  187. # in models without FPN, roi extractor only uses the last level of
  188. # feature maps. And body_feat_names[-1] represents the name of
  189. # last feature map.
  190. body_feat = body_feats[body_feat_names[-1]]
  191. roi_feat = self.roi_extractor(body_feat, rois)
  192. else:
  193. roi_feat = self.roi_extractor(body_feats, rois, spatial_scale)
  194. if self.mode == 'train':
  195. loss = self.bbox_head.get_loss(roi_feat, labels_int32,
  196. bbox_targets, bbox_inside_weights,
  197. bbox_outside_weights)
  198. loss.update(rpn_loss)
  199. total_loss = fluid.layers.sum(list(loss.values()))
  200. loss.update({'loss': total_loss})
  201. return loss
  202. else:
  203. pred = self.bbox_head.get_prediction(roi_feat, rois, im_info,
  204. im_shape)
  205. return pred
  206. def generate_inputs(self):
  207. inputs = OrderedDict()
  208. if self.fixed_input_shape is not None:
  209. input_shape =[None, 3, self.fixed_input_shape[0], self.fixed_input_shape[1]]
  210. inputs['image'] = fluid.data(
  211. dtype='float32', shape=input_shape, name='image')
  212. else:
  213. inputs['image'] = fluid.data(
  214. dtype='float32', shape=[None, 3, None, None], name='image')
  215. if self.mode == 'train':
  216. inputs['im_info'] = fluid.data(
  217. dtype='float32', shape=[None, 3], name='im_info')
  218. inputs['gt_box'] = fluid.data(
  219. dtype='float32', shape=[None, 4], lod_level=1, name='gt_box')
  220. inputs['gt_label'] = fluid.data(
  221. dtype='int32', shape=[None, 1], lod_level=1, name='gt_label')
  222. inputs['is_crowd'] = fluid.data(
  223. dtype='int32', shape=[None, 1], lod_level=1, name='is_crowd')
  224. elif self.mode == 'eval':
  225. inputs['im_info'] = fluid.data(
  226. dtype='float32', shape=[None, 3], name='im_info')
  227. inputs['im_id'] = fluid.data(
  228. dtype='int64', shape=[None, 1], name='im_id')
  229. inputs['im_shape'] = fluid.data(
  230. dtype='float32', shape=[None, 3], name='im_shape')
  231. inputs['gt_box'] = fluid.data(
  232. dtype='float32', shape=[None, 4], lod_level=1, name='gt_box')
  233. inputs['gt_label'] = fluid.data(
  234. dtype='int32', shape=[None, 1], lod_level=1, name='gt_label')
  235. inputs['is_difficult'] = fluid.data(
  236. dtype='int32',
  237. shape=[None, 1],
  238. lod_level=1,
  239. name='is_difficult')
  240. elif self.mode == 'test':
  241. inputs['im_info'] = fluid.data(
  242. dtype='float32', shape=[None, 3], name='im_info')
  243. inputs['im_shape'] = fluid.data(
  244. dtype='float32', shape=[None, 3], name='im_shape')
  245. return inputs