Skip to main content

visloc_objects/
byte_track.rs

1//! ByteTrack: multi-object tracking by associating every detection box.
2//!
3//! Zhang et al., "ByteTrack: Multi-Object Tracking by Associating Every
4//! Detection Box", ECCV 2022. Per frame:
5//!
6//! 1. Confirmed and lost tracks are predicted with a Kalman filter and matched
7//!    to the high-score detections by IoU.
8//! 2. Confirmed tracks left over are matched to the low-score detections, which
9//!    are often the same objects partly occluded. Tracks still unmatched are
10//!    lost; a lost track can be re-found in step 1 for `max_frames_lost` frames.
11//! 3. Tracks started last frame are matched to the remaining high-score
12//!    detections; they are confirmed on a match and dropped otherwise.
13//! 4. Remaining high-score detections start new tracks.
14//!
15//! This follows the reference implementation (`yolox/tracker/byte_tracker.py`)
16//! with two additions: association can be restricted to tracks and
17//! detections of the same class, and a track gets its ID when it is
18//! confirmed, so reported IDs have no gaps.
19
20use crate::assignment::assign_with_cost_limit;
21use crate::bbox::{BBox, Detection};
22use crate::kalman::{BoxKalmanFilter, BoxKalmanState};
23
24/// Settings of [`ByteTracker`]; the defaults are ByteTrack's for 30 fps video.
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct ByteTrackConfig {
27    /// Detections with at least this score are associated first (`track_thresh`, 0.5).
28    pub high_score_threshold: f64,
29    /// Detections with a score in `[low_score_threshold, high_score_threshold)`
30    /// are associated second, only with confirmed tracks (0.1).
31    pub low_score_threshold: f64,
32    /// A new track starts only from a detection with at least this score
33    /// (`track_thresh + 0.1`, 0.6).
34    pub new_track_score_threshold: f64,
35    /// Largest IoU distance (`1 - IoU`) for the first association (`match_thresh`, 0.8).
36    pub first_match_cost_limit: f64,
37    /// Largest IoU distance for the low-score association (0.5).
38    pub second_match_cost_limit: f64,
39    /// Largest IoU distance for confirming new tracks (0.7).
40    pub unconfirmed_match_cost_limit: f64,
41    /// Weight IoU by the detection score in the first and the confirming
42    /// association (ByteTrack's default; off for MOT20).
43    pub fuse_score: bool,
44    /// Frames a lost track is kept before it is dropped. ByteTrack uses
45    /// `frame_rate / 30 * track_buffer`, one second of video.
46    pub max_frames_lost: u64,
47    /// Associate detections only with tracks of the same class. The reference
48    /// tracker ignores classes.
49    pub class_aware: bool,
50    /// A tracked and a lost track closer than this IoU distance are the same
51    /// object; the younger one is dropped (0.15).
52    pub duplicate_cost_limit: f64,
53    pub kalman: BoxKalmanFilter,
54}
55
56impl Default for ByteTrackConfig {
57    fn default() -> Self {
58        Self {
59            high_score_threshold: 0.5,
60            low_score_threshold: 0.1,
61            new_track_score_threshold: 0.6,
62            first_match_cost_limit: 0.8,
63            second_match_cost_limit: 0.5,
64            unconfirmed_match_cost_limit: 0.7,
65            fuse_score: true,
66            max_frames_lost: 30,
67            class_aware: true,
68            duplicate_cost_limit: 0.15,
69            kalman: BoxKalmanFilter::default(),
70        }
71    }
72}
73
74/// Identifier of a confirmed track, unique within a sequence and starting at 1.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
76pub struct TrackId(pub u64);
77
78/// A confirmed track that was matched to a detection in this frame.
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct TrackedObject {
81    pub id: TrackId,
82    /// The class of the detection that started the track.
83    pub class_id: u32,
84    /// The Kalman-filtered box after this frame's update.
85    pub bbox: BBox,
86    /// Score of the matched detection.
87    pub score: f64,
88    /// Index of the matched detection in this frame's input.
89    pub detection_index: usize,
90    /// Frame (1-based) in which the track started.
91    pub start_frame: u64,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95enum TrackState {
96    Tracked,
97    Lost,
98}
99
100#[derive(Debug, Clone)]
101struct Track {
102    id: Option<TrackId>,
103    class_id: u32,
104    kalman: BoxKalmanState,
105    state: TrackState,
106    score: f64,
107    start_frame: u64,
108    /// Frame of the last matched detection.
109    last_frame: u64,
110    /// Detection matched in the current frame.
111    detection_index: Option<usize>,
112}
113
114impl Track {
115    fn bbox(&self) -> BBox {
116        self.kalman.bbox()
117    }
118}
119
120/// ByteTrack over a sequence of frames; see the module documentation.
121#[derive(Debug, Clone)]
122pub struct ByteTracker {
123    config: ByteTrackConfig,
124    frame: u64,
125    next_id: u64,
126    /// Tracks matched in the last frame, confirmed or not.
127    tracked: Vec<Track>,
128    lost: Vec<Track>,
129}
130
131impl Default for ByteTracker {
132    fn default() -> Self {
133        Self::new(ByteTrackConfig::default())
134    }
135}
136
137impl ByteTracker {
138    pub fn new(config: ByteTrackConfig) -> Self {
139        Self {
140            config,
141            frame: 0,
142            next_id: 1,
143            tracked: Vec::new(),
144            lost: Vec::new(),
145        }
146    }
147
148    pub fn config(&self) -> &ByteTrackConfig {
149        &self.config
150    }
151
152    /// Frames processed so far.
153    pub fn frame(&self) -> u64 {
154        self.frame
155    }
156
157    /// IDs of the confirmed tracks that are lost and can still be re-found.
158    pub fn lost_track_ids(&self) -> Vec<TrackId> {
159        let mut ids: Vec<TrackId> = self.lost.iter().filter_map(|t| t.id).collect();
160        ids.sort();
161        ids
162    }
163
164    /// Forget all tracks and start a new sequence; IDs start again at 1.
165    pub fn reset(&mut self) {
166        *self = Self::new(self.config);
167    }
168
169    /// Process one frame's detections and return the confirmed tracks matched
170    /// in it, sorted by ID. Detections with an invalid box or a non-finite
171    /// score are ignored.
172    pub fn update(&mut self, detections: &[Detection]) -> Vec<TrackedObject> {
173        self.frame += 1;
174        let frame = self.frame;
175        let config = self.config;
176        let kalman = config.kalman;
177
178        let usable = |d: &Detection| d.bbox.is_valid() && d.score.is_finite();
179        let high: Vec<usize> = (0..detections.len())
180            .filter(|&i| {
181                usable(&detections[i]) && detections[i].score >= config.high_score_threshold
182            })
183            .collect();
184        let low: Vec<usize> = (0..detections.len())
185            .filter(|&i| {
186                let score = detections[i].score;
187                usable(&detections[i])
188                    && score >= config.low_score_threshold
189                    && score < config.high_score_threshold
190            })
191            .collect();
192
193        let (mut pool, mut unconfirmed): (Vec<Track>, Vec<Track>) =
194            std::mem::take(&mut self.tracked)
195                .into_iter()
196                .partition(|t| t.id.is_some());
197        pool.append(&mut self.lost);
198        for track in pool.iter_mut().chain(unconfirmed.iter_mut()) {
199            track.detection_index = None;
200        }
201        // Unconfirmed tracks are not predicted, as in the reference.
202        for track in &mut pool {
203            if track.state == TrackState::Lost {
204                track.kalman.mean[7] = 0.0;
205            }
206            kalman.predict(&mut track.kalman);
207        }
208
209        // 1. Confirmed and lost tracks against high-score detections.
210        let first = self.associate(
211            &pool.iter().collect::<Vec<_>>(),
212            &high,
213            detections,
214            config.fuse_score,
215            config.first_match_cost_limit,
216        );
217        for &(t, d) in &first.matches {
218            self.apply(&mut pool[t], detections, high[d]);
219        }
220        let remaining_high: Vec<usize> = first.unmatched_cols.iter().map(|&d| high[d]).collect();
221
222        // 2. Confirmed tracks still tracked against low-score detections.
223        let still_tracked: Vec<usize> = first
224            .unmatched_rows
225            .iter()
226            .copied()
227            .filter(|&t| pool[t].state == TrackState::Tracked)
228            .collect();
229        let second = self.associate(
230            &still_tracked.iter().map(|&t| &pool[t]).collect::<Vec<_>>(),
231            &low,
232            detections,
233            false,
234            config.second_match_cost_limit,
235        );
236        for &(t, d) in &second.matches {
237            self.apply(&mut pool[still_tracked[t]], detections, low[d]);
238        }
239        for &t in &second.unmatched_rows {
240            pool[still_tracked[t]].state = TrackState::Lost;
241        }
242
243        // 3. Tracks started last frame against the remaining high-score detections.
244        let third = self.associate(
245            &unconfirmed.iter().collect::<Vec<_>>(),
246            &remaining_high,
247            detections,
248            config.fuse_score,
249            config.unconfirmed_match_cost_limit,
250        );
251        let mut confirmed = Vec::with_capacity(third.matches.len());
252        for &(t, d) in &third.matches {
253            let mut track = unconfirmed[t].clone();
254            self.apply(&mut track, detections, remaining_high[d]);
255            confirmed.push(track);
256        }
257
258        // 4. New tracks; on the first frame they are confirmed at once.
259        let mut started = Vec::new();
260        for &d in &third.unmatched_cols {
261            let detection = &detections[remaining_high[d]];
262            if detection.score < config.new_track_score_threshold {
263                continue;
264            }
265            let mut track = Track {
266                id: None,
267                class_id: detection.class_id,
268                kalman: kalman.initiate(&detection.bbox),
269                state: TrackState::Tracked,
270                score: detection.score,
271                start_frame: frame,
272                last_frame: frame,
273                detection_index: Some(remaining_high[d]),
274            };
275            if frame == 1 {
276                track.id = Some(self.take_id());
277            }
278            started.push(track);
279        }
280
281        let (mut tracked, lost): (Vec<Track>, Vec<Track>) = pool
282            .into_iter()
283            .partition(|t| t.state == TrackState::Tracked);
284        tracked.extend(confirmed);
285        tracked.extend(started);
286        let lost: Vec<Track> = lost
287            .into_iter()
288            .filter(|t| frame - t.last_frame <= config.max_frames_lost)
289            .collect();
290        let (tracked, lost) = self.remove_duplicates(tracked, lost);
291        self.tracked = tracked;
292        self.lost = lost;
293
294        let mut output: Vec<TrackedObject> = self
295            .tracked
296            .iter()
297            .filter_map(|t| {
298                Some(TrackedObject {
299                    id: t.id?,
300                    class_id: t.class_id,
301                    bbox: t.bbox(),
302                    score: t.score,
303                    detection_index: t.detection_index?,
304                    start_frame: t.start_frame,
305                })
306            })
307            .collect();
308        output.sort_by_key(|o| o.id);
309        output
310    }
311
312    fn take_id(&mut self) -> TrackId {
313        let id = TrackId(self.next_id);
314        self.next_id += 1;
315        id
316    }
317
318    /// Update a track with a detection; this re-finds a lost track and
319    /// confirms a new one.
320    fn apply(&mut self, track: &mut Track, detections: &[Detection], index: usize) {
321        let detection = &detections[index];
322        self.config
323            .kalman
324            .update(&mut track.kalman, &detection.bbox);
325        track.state = TrackState::Tracked;
326        track.score = detection.score;
327        track.last_frame = self.frame;
328        track.detection_index = Some(index);
329        if track.id.is_none() {
330            track.id = Some(self.take_id());
331        }
332    }
333
334    /// IoU-distance assignment of `tracks` to `detections[indices]`.
335    fn associate(
336        &self,
337        tracks: &[&Track],
338        indices: &[usize],
339        detections: &[Detection],
340        fuse_score: bool,
341        cost_limit: f64,
342    ) -> crate::assignment::Assignment {
343        let mut costs = Vec::with_capacity(tracks.len() * indices.len());
344        for track in tracks {
345            let bbox = track.bbox();
346            for &i in indices {
347                let detection = &detections[i];
348                let cost = if self.config.class_aware && track.class_id != detection.class_id {
349                    f64::INFINITY
350                } else {
351                    let iou = bbox.iou(&detection.bbox);
352                    1.0 - if fuse_score {
353                        iou * detection.score
354                    } else {
355                        iou
356                    }
357                };
358                costs.push(cost);
359            }
360        }
361        assign_with_cost_limit(tracks.len(), indices.len(), &costs, cost_limit)
362    }
363
364    /// Of a tracked and a lost track that overlap almost completely, keep the
365    /// one that has existed longer.
366    fn remove_duplicates(&self, tracked: Vec<Track>, lost: Vec<Track>) -> (Vec<Track>, Vec<Track>) {
367        let mut drop_tracked = vec![false; tracked.len()];
368        let mut drop_lost = vec![false; lost.len()];
369        for (p, a) in tracked.iter().enumerate() {
370            for (q, b) in lost.iter().enumerate() {
371                if self.config.class_aware && a.class_id != b.class_id {
372                    continue;
373                }
374                if 1.0 - a.bbox().iou(&b.bbox()) < self.config.duplicate_cost_limit {
375                    if a.last_frame - a.start_frame > b.last_frame - b.start_frame {
376                        drop_lost[q] = true;
377                    } else {
378                        drop_tracked[p] = true;
379                    }
380                }
381            }
382        }
383        let keep = |tracks: Vec<Track>, drop: &[bool]| {
384            tracks
385                .into_iter()
386                .zip(drop)
387                .filter_map(|(t, &d)| (!d).then_some(t))
388                .collect::<Vec<_>>()
389        };
390        (keep(tracked, &drop_tracked), keep(lost, &drop_lost))
391    }
392}