base_jde_tracker.py 8.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# 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.
14 15 16
"""
This code is based on https://github.com/Zhongdao/Towards-Realtime-MOT/blob/master/tracker/multitracker.py
"""
17 18

import numpy as np
19
from collections import defaultdict
20 21 22
from collections import deque, OrderedDict
from ..matching import jde_matching as matching
from ppdet.core.workspace import register, serializable
23 24
import warnings
warnings.filterwarnings("ignore")
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

__all__ = [
    'TrackState',
    'BaseTrack',
    'STrack',
    'joint_stracks',
    'sub_stracks',
    'remove_duplicate_stracks',
]


class TrackState(object):
    New = 0
    Tracked = 1
    Lost = 2
    Removed = 3


@register
@serializable
class BaseTrack(object):
46
    _count_dict = defaultdict(int)  # support single class and multi classes
47 48 49 50 51 52 53

    track_id = 0
    is_activated = False
    state = TrackState.New

    history = OrderedDict()
    features = []
54
    curr_feat = None
55 56 57 58 59 60 61 62 63 64 65 66 67
    score = 0
    start_frame = 0
    frame_id = 0
    time_since_update = 0

    # multi-camera
    location = (np.inf, np.inf)

    @property
    def end_frame(self):
        return self.frame_id

    @staticmethod
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    def next_id(cls_id):
        BaseTrack._count_dict[cls_id] += 1
        return BaseTrack._count_dict[cls_id]

    # @even: reset track id
    @staticmethod
    def init_count(num_classes):
        """
        Initiate _count for all object classes
        :param num_classes:
        """
        for cls_id in range(num_classes):
            BaseTrack._count_dict[cls_id] = 0

    @staticmethod
    def reset_track_count(cls_id):
        BaseTrack._count_dict[cls_id] = 0
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

    def activate(self, *args):
        raise NotImplementedError

    def predict(self):
        raise NotImplementedError

    def update(self, *args, **kwargs):
        raise NotImplementedError

    def mark_lost(self):
        self.state = TrackState.Lost

    def mark_removed(self):
        self.state = TrackState.Removed


@register
@serializable
class STrack(BaseTrack):
W
wangguanzhong 已提交
105
    def __init__(self, tlwh, score, cls_id, buff_size=30, temp_feat=None):
106
        # wait activate
W
wangguanzhong 已提交
107
        self._tlwh = np.asarray(tlwh, dtype=np.float32)
F
Feng Ni 已提交
108 109 110 111
        self.score = score
        self.cls_id = cls_id
        self.track_len = 0

112 113 114 115
        self.kalman_filter = None
        self.mean, self.covariance = None, None
        self.is_activated = False

F
Feng Ni 已提交
116 117 118 119 120 121
        self.use_reid = True if temp_feat is not None else False
        if self.use_reid:
            self.smooth_feat = None
            self.update_features(temp_feat)
            self.features = deque([], maxlen=buff_size)
            self.alpha = 0.9
122 123

    def update_features(self, feat):
F
Feng Ni 已提交
124
        # L2 normalizing, this function has no use for BYTETracker
125 126 127 128 129
        feat /= np.linalg.norm(feat)
        self.curr_feat = feat
        if self.smooth_feat is None:
            self.smooth_feat = feat
        else:
130
            self.smooth_feat = self.alpha * self.smooth_feat + (1.0 - self.alpha
131 132 133 134 135 136 137 138 139 140 141 142
                                                                ) * feat
        self.features.append(feat)
        self.smooth_feat /= np.linalg.norm(self.smooth_feat)

    def predict(self):
        mean_state = self.mean.copy()
        if self.state != TrackState.Tracked:
            mean_state[7] = 0
        self.mean, self.covariance = self.kalman_filter.predict(mean_state,
                                                                self.covariance)

    @staticmethod
143 144 145 146 147 148
    def multi_predict(tracks, kalman_filter):
        if len(tracks) > 0:
            multi_mean = np.asarray([track.mean.copy() for track in tracks])
            multi_covariance = np.asarray(
                [track.covariance for track in tracks])
            for i, st in enumerate(tracks):
149 150 151 152 153
                if st.state != TrackState.Tracked:
                    multi_mean[i][7] = 0
            multi_mean, multi_covariance = kalman_filter.multi_predict(
                multi_mean, multi_covariance)
            for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
154 155 156 157 158
                tracks[i].mean = mean
                tracks[i].covariance = cov

    def reset_track_id(self):
        self.reset_track_count(self.cls_id)
159 160

    def activate(self, kalman_filter, frame_id):
161
        """Start a new track"""
162
        self.kalman_filter = kalman_filter
163 164
        # update track id for the object class
        self.track_id = self.next_id(self.cls_id)
165 166 167
        self.mean, self.covariance = self.kalman_filter.initiate(
            self.tlwh_to_xyah(self._tlwh))

168 169 170 171
        self.track_len = 0
        self.state = TrackState.Tracked  # set flag 'tracked'

        if frame_id == 1:  # to record the first frame's detection result
172
            self.is_activated = True
173

174 175 176 177 178 179
        self.frame_id = frame_id
        self.start_frame = frame_id

    def re_activate(self, new_track, frame_id, new_id=False):
        self.mean, self.covariance = self.kalman_filter.update(
            self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh))
F
Feng Ni 已提交
180 181
        if self.use_reid:
            self.update_features(new_track.curr_feat)
182
        self.track_len = 0
183 184 185
        self.state = TrackState.Tracked
        self.is_activated = True
        self.frame_id = frame_id
186 187
        if new_id:  # update track id for the object class
            self.track_id = self.next_id(self.cls_id)
188 189 190

    def update(self, new_track, frame_id, update_feature=True):
        self.frame_id = frame_id
191
        self.track_len += 1
192 193 194 195

        new_tlwh = new_track.tlwh
        self.mean, self.covariance = self.kalman_filter.update(
            self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh))
196 197
        self.state = TrackState.Tracked  # set flag 'tracked'
        self.is_activated = True  # set flag 'activated'
198 199

        self.score = new_track.score
F
Feng Ni 已提交
200
        if update_feature and self.use_reid:
201 202 203 204
            self.update_features(new_track.curr_feat)

    @property
    def tlwh(self):
205 206
        """Get current position in bounding box format `(top left x, top left y,
                width, height)`.
207 208 209
        """
        if self.mean is None:
            return self._tlwh.copy()
210

211 212 213 214 215 216 217
        ret = self.mean[:4].copy()
        ret[2] *= ret[3]
        ret[:2] -= ret[2:] / 2
        return ret

    @property
    def tlbr(self):
218
        """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
219 220 221 222 223 224 225 226
        `(top left, bottom right)`.
        """
        ret = self.tlwh.copy()
        ret[2:] += ret[:2]
        return ret

    @staticmethod
    def tlwh_to_xyah(tlwh):
227
        """Convert bounding box to format `(center x, center y, aspect ratio,
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        height)`, where the aspect ratio is `width / height`.
        """
        ret = np.asarray(tlwh).copy()
        ret[:2] += ret[2:] / 2
        ret[2] /= ret[3]
        return ret

    def to_xyah(self):
        return self.tlwh_to_xyah(self.tlwh)

    @staticmethod
    def tlbr_to_tlwh(tlbr):
        ret = np.asarray(tlbr).copy()
        ret[2:] -= ret[:2]
        return ret

    @staticmethod
    def tlwh_to_tlbr(tlwh):
        ret = np.asarray(tlwh).copy()
        ret[2:] += ret[:2]
        return ret

    def __repr__(self):
251 252
        return 'OT_({}-{})_({}-{})'.format(self.cls_id, self.track_id,
                                           self.start_frame, self.end_frame)
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293


def joint_stracks(tlista, tlistb):
    exists = {}
    res = []
    for t in tlista:
        exists[t.track_id] = 1
        res.append(t)
    for t in tlistb:
        tid = t.track_id
        if not exists.get(tid, 0):
            exists[tid] = 1
            res.append(t)
    return res


def sub_stracks(tlista, tlistb):
    stracks = {}
    for t in tlista:
        stracks[t.track_id] = t
    for t in tlistb:
        tid = t.track_id
        if stracks.get(tid, 0):
            del stracks[tid]
    return list(stracks.values())


def remove_duplicate_stracks(stracksa, stracksb):
    pdist = matching.iou_distance(stracksa, stracksb)
    pairs = np.where(pdist < 0.15)
    dupa, dupb = list(), list()
    for p, q in zip(*pairs):
        timep = stracksa[p].frame_id - stracksa[p].start_frame
        timeq = stracksb[q].frame_id - stracksb[q].start_frame
        if timep > timeq:
            dupb.append(q)
        else:
            dupa.append(p)
    resa = [t for i, t in enumerate(stracksa) if not i in dupa]
    resb = [t for i, t in enumerate(stracksb) if not i in dupb]
    return resa, resb