faster_rcnn.py 10 KB

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