faster_rcnn.py 3.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. 
#   
# Licensed under the Apache License, Version 2.0 (the "License");   
# you may not use this file except in compliance with the License.  
# You may obtain a copy of the License at   
#   
#     http://www.apache.org/licenses/LICENSE-2.0    
#   
# Unless required by applicable law or agreed to in writing, software   
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
# See the License for the specific language governing permissions and   
# limitations under the License.

Q
qingqing01 已提交
15 16 17 18 19
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import paddle
20
from ppdet.core.workspace import register, create
Q
qingqing01 已提交
21 22 23 24 25 26 27 28
from .meta_arch import BaseArch

__all__ = ['FasterRCNN']


@register
class FasterRCNN(BaseArch):
    __category__ = 'architecture'
29
    __inject__ = ['bbox_post_process']
Q
qingqing01 已提交
30 31 32 33 34 35 36

    def __init__(self,
                 backbone,
                 rpn_head,
                 bbox_head,
                 bbox_post_process,
                 neck=None):
37 38 39 40 41 42 43
        """
        backbone (nn.Layer): backbone instance.
        rpn_head (nn.Layer): generates proposals using backbone features.
        bbox_head (nn.Layer): a head that performs per-region computation.
        mask_head (nn.Layer): generates mask from bbox and backbone features.
        """

Q
qingqing01 已提交
44 45
        super(FasterRCNN, self).__init__()
        self.backbone = backbone
46
        self.neck = neck
Q
qingqing01 已提交
47 48 49 50
        self.rpn_head = rpn_head
        self.bbox_head = bbox_head
        self.bbox_post_process = bbox_post_process

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    @classmethod
    def from_config(cls, cfg, *args, **kwargs):
        backbone = create(cfg['backbone'])
        kwargs = {'input_shape': backbone.out_shape}
        neck = cfg['neck'] and create(cfg['neck'], **kwargs)

        out_shape = neck and neck.out_shape or backbone.out_shape
        kwargs = {'input_shape': out_shape}
        rpn_head = create(cfg['rpn_head'], **kwargs)
        bbox_head = create(cfg['bbox_head'], **kwargs)
        return {
            'backbone': backbone,
            'neck': neck,
            "rpn_head": rpn_head,
            "bbox_head": bbox_head,
        }
Q
qingqing01 已提交
67

68 69
    def _forward(self):
        body_feats = self.backbone(self.inputs)
Q
qingqing01 已提交
70
        if self.neck is not None:
71 72 73 74 75 76 77 78 79
            body_feats = self.neck(body_feats)
        if self.training:
            rois, rois_num, rpn_loss = self.rpn_head(body_feats, self.inputs)
            bbox_loss, _ = self.bbox_head(body_feats, rois, rois_num,
                                          self.inputs)
            return rpn_loss, bbox_loss
        else:
            rois, rois_num, _ = self.rpn_head(body_feats, self.inputs)
            preds, _ = self.bbox_head(body_feats, rois, rois_num, None)
Q
qingqing01 已提交
80

81 82 83 84
            im_shape = self.inputs['im_shape']
            scale_factor = self.inputs['scale_factor']
            bbox, bbox_num = self.bbox_post_process(preds, (rois, rois_num),
                                                    im_shape, scale_factor)
Q
qingqing01 已提交
85

86 87 88 89
            # rescale the prediction back to origin image
            bbox_pred = self.bbox_post_process.get_pred(bbox, bbox_num,
                                                        im_shape, scale_factor)
            return bbox_pred, bbox_num
Q
qingqing01 已提交
90 91

    def get_loss(self, ):
92
        rpn_loss, bbox_loss = self._forward()
Q
qingqing01 已提交
93
        loss = {}
94 95
        loss.update(rpn_loss)
        loss.update(bbox_loss)
Q
qingqing01 已提交
96 97 98 99 100
        total_loss = paddle.add_n(list(loss.values()))
        loss.update({'loss': total_loss})
        return loss

    def get_pred(self):
101 102 103 104
        bbox_pred, bbox_num = self._forward()
        label = bbox_pred[:, 0]
        score = bbox_pred[:, 1]
        bbox = bbox_pred[:, 2:]
Q
qingqing01 已提交
105 106
        output = {
            'bbox': bbox,
107 108 109
            'score': score,
            'label': label,
            'bbox_num': bbox_num
Q
qingqing01 已提交
110 111
        }
        return output