yolo.py 5.2 KB
Newer Older
G
George Ni 已提交
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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

19
from ppdet.core.workspace import register, create
Q
qingqing01 已提交
20
from .meta_arch import BaseArch
G
George Ni 已提交
21
from ..post_process import JDEBBoxPostProcess
Q
qingqing01 已提交
22 23

__all__ = ['YOLOv3']
24 25
# YOLOv3,PP-YOLO,PP-YOLOv2,PP-YOLOE,PP-YOLOE+ use the same architecture as YOLOv3
# PP-YOLOE and PP-YOLOE+ are recommended to use PPYOLOE architecture in ppyoloe.py
Q
qingqing01 已提交
26 27 28 29 30


@register
class YOLOv3(BaseArch):
    __category__ = 'architecture'
31
    __shared__ = ['data_format']
32
    __inject__ = ['post_process']
Q
qingqing01 已提交
33 34 35 36 37

    def __init__(self,
                 backbone='DarkNet',
                 neck='YOLOv3FPN',
                 yolo_head='YOLOv3Head',
38
                 post_process='BBoxPostProcess',
39 40
                 data_format='NCHW',
                 for_mot=False):
W
wangxinxin08 已提交
41 42 43 44 45 46 47 48 49
        """
        YOLOv3 network, see https://arxiv.org/abs/1804.02767

        Args:
            backbone (nn.Layer): backbone instance
            neck (nn.Layer): neck instance
            yolo_head (nn.Layer): anchor_head instance
            bbox_post_process (object): `BBoxPostProcess` instance
            data_format (str): data format, NCHW or NHWC
50 51
            for_mot (bool): whether return other features for multi-object tracking
                models, default False in pure object detection models.
W
wangxinxin08 已提交
52
        """
53
        super(YOLOv3, self).__init__(data_format=data_format)
Q
qingqing01 已提交
54 55 56 57
        self.backbone = backbone
        self.neck = neck
        self.yolo_head = yolo_head
        self.post_process = post_process
58
        self.for_mot = for_mot
G
George Ni 已提交
59
        self.return_idx = isinstance(post_process, JDEBBoxPostProcess)
Q
qingqing01 已提交
60

61 62 63 64 65 66 67 68 69 70 71 72
    @classmethod
    def from_config(cls, cfg, *args, **kwargs):
        # backbone
        backbone = create(cfg['backbone'])

        # fpn
        kwargs = {'input_shape': backbone.out_shape}
        neck = create(cfg['neck'], **kwargs)

        # head
        kwargs = {'input_shape': neck.out_shape}
        yolo_head = create(cfg['yolo_head'], **kwargs)
Q
qingqing01 已提交
73

74 75 76 77 78 79 80 81
        return {
            'backbone': backbone,
            'neck': neck,
            "yolo_head": yolo_head,
        }

    def _forward(self):
        body_feats = self.backbone(self.inputs)
W
wangxinxin08 已提交
82 83 84 85
        if self.for_mot:
            neck_feats = self.neck(body_feats, self.for_mot)
        else:
            neck_feats = self.neck(body_feats)
86 87 88 89 90

        if isinstance(neck_feats, dict):
            assert self.for_mot == True
            emb_feats = neck_feats['emb_feats']
            neck_feats = neck_feats['yolo_feats']
Q
qingqing01 已提交
91

92
        if self.training:
93 94 95 96 97 98 99
            yolo_losses = self.yolo_head(neck_feats, self.inputs)

            if self.for_mot:
                return {'det_losses': yolo_losses, 'emb_feats': emb_feats}
            else:
                return yolo_losses

100
        else:
X
xs1997zju 已提交
101
            cam_data = {} # record bbox scores and index before nms
102
            yolo_head_outs = self.yolo_head(neck_feats)
X
xs1997zju 已提交
103
            cam_data['scores'] = yolo_head_outs[0]
104 105

            if self.for_mot:
106
                # the detection part of JDE MOT model
107 108 109 110 111 112 113 114 115 116
                boxes_idx, bbox, bbox_num, nms_keep_idx = self.post_process(
                    yolo_head_outs, self.yolo_head.mask_anchors)
                output = {
                    'bbox': bbox,
                    'bbox_num': bbox_num,
                    'boxes_idx': boxes_idx,
                    'nms_keep_idx': nms_keep_idx,
                    'emb_feats': emb_feats,
                }
            else:
G
George Ni 已提交
117
                if self.return_idx:
118
                    # the detection part of JDE MOT model
G
George Ni 已提交
119 120
                    _, bbox, bbox_num, _ = self.post_process(
                        yolo_head_outs, self.yolo_head.mask_anchors)
S
shangliang Xu 已提交
121
                elif self.post_process is not None:
122
                    # anchor based YOLOs: YOLOv3,PP-YOLO,PP-YOLOv2 use mask_anchors
X
xs1997zju 已提交
123
                    bbox, bbox_num, before_nms_indexes = self.post_process(
G
George Ni 已提交
124 125
                        yolo_head_outs, self.yolo_head.mask_anchors,
                        self.inputs['im_shape'], self.inputs['scale_factor'])
X
xs1997zju 已提交
126
                    cam_data['before_nms_indexes'] = before_nms_indexes
S
shangliang Xu 已提交
127
                else:
128
                    # anchor free YOLOs: PP-YOLOE, PP-YOLOE+
X
xs1997zju 已提交
129
                    bbox, bbox_num, before_nms_indexes = self.yolo_head.post_process(
S
shangliang Xu 已提交
130
                        yolo_head_outs, self.inputs['scale_factor'])
X
xs1997zju 已提交
131 132 133
                    # data for cam 
                    cam_data['before_nms_indexes'] = before_nms_indexes
                output = {'bbox': bbox, 'bbox_num': bbox_num, 'cam_data': cam_data}
134 135

            return output
Q
qingqing01 已提交
136

137 138
    def get_loss(self):
        return self._forward()
Q
qingqing01 已提交
139 140

    def get_pred(self):
141
        return self._forward()