s2anet.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Copyright (c) 2021 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. import paddle
  18. from ppdet.core.workspace import register, create
  19. from .meta_arch import BaseArch
  20. __all__ = ['S2ANet']
  21. @register
  22. class S2ANet(BaseArch):
  23. __category__ = 'architecture'
  24. __inject__ = ['head']
  25. def __init__(self, backbone, neck, head):
  26. """
  27. S2ANet, see https://arxiv.org/pdf/2008.09397.pdf
  28. Args:
  29. backbone (object): backbone instance
  30. neck (object): `FPN` instance
  31. head (object): `Head` instance
  32. """
  33. super(S2ANet, self).__init__()
  34. self.backbone = backbone
  35. self.neck = neck
  36. self.s2anet_head = head
  37. @classmethod
  38. def from_config(cls, cfg, *args, **kwargs):
  39. backbone = create(cfg['backbone'])
  40. kwargs = {'input_shape': backbone.out_shape}
  41. neck = cfg['neck'] and create(cfg['neck'], **kwargs)
  42. out_shape = neck and neck.out_shape or backbone.out_shape
  43. kwargs = {'input_shape': out_shape}
  44. head = create(cfg['head'], **kwargs)
  45. return {'backbone': backbone, 'neck': neck, "head": head}
  46. def _forward(self):
  47. body_feats = self.backbone(self.inputs)
  48. if self.neck is not None:
  49. body_feats = self.neck(body_feats)
  50. if self.training:
  51. loss = self.s2anet_head(body_feats, self.inputs)
  52. return loss
  53. else:
  54. head_outs = self.s2anet_head(body_feats)
  55. # post_process
  56. bboxes, bbox_num = self.s2anet_head.get_bboxes(head_outs)
  57. # rescale the prediction back to origin image
  58. im_shape = self.inputs['im_shape']
  59. scale_factor = self.inputs['scale_factor']
  60. bboxes = self.s2anet_head.get_pred(bboxes, bbox_num, im_shape,
  61. scale_factor)
  62. # output
  63. output = {'bbox': bboxes, 'bbox_num': bbox_num}
  64. return output
  65. def get_loss(self, ):
  66. loss = self._forward()
  67. return loss
  68. def get_pred(self):
  69. output = self._forward()
  70. return output