jde.py 4.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# Copyright (c) 2021 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import paddle
from ppdet.modeling.mot.utils import scale_coords
from ppdet.core.workspace import register, create
from .meta_arch import BaseArch

__all__ = ['JDE']


@register
class JDE(BaseArch):
G
George Ni 已提交
29
    __category__ = 'architecture'
G
George Ni 已提交
30
    __shared__ = ['metric']
31 32 33 34 35 36 37
    """
    JDE network, see https://arxiv.org/abs/1909.12605v1

    Args:
        detector (object): detector model instance
        reid (object): reid model instance
        tracker (object): tracker instance
G
George Ni 已提交
38 39
        metric (str): 'MOTDet' for training and detection evaluation, 'ReID'
            for ReID embedding evaluation, or 'MOT' for multi object tracking
40
            evaluation.
41 42 43 44 45 46
    """

    def __init__(self,
                 detector='YOLOv3',
                 reid='JDEEmbeddingHead',
                 tracker='JDETracker',
G
George Ni 已提交
47
                 metric='MOT'):
48 49 50 51
        super(JDE, self).__init__()
        self.detector = detector
        self.reid = reid
        self.tracker = tracker
G
George Ni 已提交
52
        self.metric = metric
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

    @classmethod
    def from_config(cls, cfg, *args, **kwargs):
        detector = create(cfg['detector'])
        kwargs = {'input_shape': detector.neck.out_shape}

        reid = create(cfg['reid'], **kwargs)

        tracker = create(cfg['tracker'])

        return {
            "detector": detector,
            "reid": reid,
            "tracker": tracker,
        }

    def _forward(self):
        det_outs = self.detector(self.inputs)

        if self.training:
            emb_feats = det_outs['emb_feats']
            loss_confs = det_outs['det_losses']['loss_confs']
            loss_boxes = det_outs['det_losses']['loss_boxes']
            jde_losses = self.reid(emb_feats, self.inputs, loss_confs,
                                   loss_boxes)
            return jde_losses
        else:
G
George Ni 已提交
80
            if self.metric == 'MOTDet':
81 82 83 84 85 86
                det_results = {
                    'bbox': det_outs['bbox'],
                    'bbox_num': det_outs['bbox_num'],
                }
                return det_results

G
George Ni 已提交
87
            elif self.metric == 'ReID':
88 89 90 91
                emb_feats = det_outs['emb_feats']
                embs_and_gts = self.reid(emb_feats, self.inputs, test_emb=True)
                return embs_and_gts

G
George Ni 已提交
92
            elif self.metric == 'MOT':
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
                emb_feats = det_outs['emb_feats']
                emb_outs = self.reid(emb_feats, self.inputs)

                boxes_idx = det_outs['boxes_idx']
                bbox = det_outs['bbox']

                input_shape = self.inputs['image'].shape[2:]
                im_shape = self.inputs['im_shape']
                scale_factor = self.inputs['scale_factor']

                bbox[:, 2:] = scale_coords(bbox[:, 2:], input_shape, im_shape,
                                           scale_factor)

                nms_keep_idx = det_outs['nms_keep_idx']

                pred_dets = paddle.concat((bbox[:, 2:], bbox[:, 1:2]), axis=1)

110
                boxes_idx = paddle.cast(boxes_idx, 'int64')
111 112 113
                emb_valid = paddle.gather_nd(emb_outs, boxes_idx)
                pred_embs = paddle.gather_nd(emb_valid, nms_keep_idx)

114
                return pred_dets, pred_embs
115 116

            else:
G
George Ni 已提交
117 118
                raise ValueError("Unknown metric {} for multi object tracking.".
                                 format(self.metric))
119 120 121 122 123 124

    def get_loss(self):
        return self._forward()

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