Skip to main content

adk_vision/
track.rs

1//! [`ByteTracker`]: ByteTrack over `trackforge` 0.5 (spec 3.7 §7.13), feature `track`.
2
3use std::collections::{BTreeMap, HashMap};
4
5use trackforge::trackers::byte_track::{ByteTrack, ByteTrackParams};
6use trackforge::trackers::common::CommonParams;
7
8use crate::geometry::{Region, TrackId};
9use crate::media::FrameMeta;
10use crate::traits::Tracker;
11
12/// Settings for [`ByteTracker`]: when a detection starts or continues a track, how much it
13/// must overlap a track to continue it, and how long a lost track waits to be found again.
14///
15/// # Example
16///
17/// ```
18/// use adk_vision::ByteTrackConfig;
19///
20/// // Ride out occlusions of up to two seconds of a 5 fps stream.
21/// let config = ByteTrackConfig::default().with_max_missed(10);
22/// assert_eq!(config.max_missed, 10);
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq)]
25#[non_exhaustive]
26pub struct ByteTrackConfig {
27    /// Frames a track that stopped matching is kept, so an object hidden for up to this
28    /// many frames keeps its identifier when it reappears.
29    pub max_missed: u32,
30    /// Detections scoring at least this are matched first; lower ones only continue
31    /// tracks the first pass left unmatched (ByteTrack's recovery step).
32    pub high_score: f32,
33    /// The score an unmatched detection needs to start a new track.
34    pub new_track_score: f32,
35    /// The overlap (intersection over union) a high-scoring detection needs with a track's
36    /// predicted box to continue it.
37    pub match_iou: f32,
38    /// The overlap a low-scoring detection needs to continue a track.
39    pub low_match_iou: f32,
40}
41
42impl Default for ByteTrackConfig {
43    /// ByteTrack's reference settings: 30 frames, 0.5 and 0.6 score thresholds, matches at
44    /// 0.2 overlap for high-scoring detections and 0.5 for low-scoring ones.
45    fn default() -> Self {
46        Self {
47            max_missed: 30,
48            high_score: 0.5,
49            new_track_score: 0.6,
50            match_iou: 0.2,
51            low_match_iou: 0.5,
52        }
53    }
54}
55
56impl ByteTrackConfig {
57    /// Keeps a lost track for `frames` frames.
58    pub fn with_max_missed(mut self, frames: u32) -> Self {
59        self.max_missed = frames;
60        self
61    }
62
63    /// Sets the high-score and new-track thresholds.
64    pub fn with_scores(mut self, high_score: f32, new_track_score: f32) -> Self {
65        self.high_score = high_score;
66        self.new_track_score = new_track_score;
67        self
68    }
69
70    /// Sets the overlaps a high- and a low-scoring detection need to continue a track.
71    pub fn with_match_iou(mut self, high: f32, low: f32) -> Self {
72        self.match_iou = high;
73        self.low_match_iou = low;
74        self
75    }
76
77    fn params(&self) -> ByteTrackParams {
78        ByteTrackParams {
79            common: CommonParams::new(self.max_missed as usize, 1),
80            track_thresh: self.high_score,
81            // trackforge takes the largest IoU distance (one minus IoU) that still matches.
82            match_thresh: 1.0 - self.match_iou.clamp(0.0, 1.0),
83            det_thresh: self.new_track_score,
84            second_match_thresh: 1.0 - self.low_match_iou.clamp(0.0, 1.0),
85        }
86    }
87}
88
89/// A detection as trackforge takes it, with its index in the frame's regions.
90type Detection = (usize, [f32; 4], f32);
91
92/// One label's ByteTrack, and the anonymous identifiers its tracks were given.
93struct Lane {
94    tracker: ByteTrack,
95    /// trackforge's track id to this tracker's identifier and the update it last matched.
96    ids: HashMap<u64, (TrackId, u64)>,
97}
98
99/// ByteTrack (Zhang et al., 2022) through `trackforge` 0.5 (MIT): a Kalman filter predicts
100/// each track's box, high-scoring detections match tracks first by overlap, low-scoring
101/// detections then recover the tracks left over, and a lost track is kept for
102/// [`max_missed`](ByteTrackConfig::max_missed) frames so an occluded object keeps its
103/// identifier when it reappears.
104///
105/// Each label is tracked on its own, so a person and a forklift never swap identifiers.
106/// Identifiers are anonymous counters shared across labels that restart on
107/// [`reset`](Tracker::reset) (V-I8). A detection that starts no track and continues none —
108/// below [`new_track_score`](ByteTrackConfig::new_track_score) with nothing to recover —
109/// comes back with `track: None`, as does a region with no area. A region with no score
110/// counts as certain. Call [`update`](Tracker::update) once per sampled frame: the motion
111/// model steps one frame per call.
112///
113/// # Example
114///
115/// ```
116/// use adk_vision::{ByteTracker, Tracker};
117///
118/// let mut tracker = ByteTracker::default();
119/// tracker.reset();
120/// ```
121pub struct ByteTracker {
122    config: ByteTrackConfig,
123    lanes: BTreeMap<Option<String>, Lane>,
124    next: u64,
125    updates: u64,
126}
127
128impl std::fmt::Debug for ByteTracker {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        f.debug_struct("ByteTracker")
131            .field("config", &self.config)
132            .field("labels", &self.lanes.len())
133            .field("next", &self.next)
134            .finish_non_exhaustive()
135    }
136}
137
138impl Default for ByteTracker {
139    fn default() -> Self {
140        Self::new(ByteTrackConfig::default())
141    }
142}
143
144impl ByteTracker {
145    /// A tracker with `config`.
146    pub fn new(config: ByteTrackConfig) -> Self {
147        Self { config, lanes: BTreeMap::new(), next: 0, updates: 0 }
148    }
149
150    /// The settings.
151    pub fn config(&self) -> &ByteTrackConfig {
152        &self.config
153    }
154}
155
156impl Tracker for ByteTracker {
157    fn update(&mut self, _frame: &FrameMeta, mut detections: Vec<Region>) -> Vec<Region> {
158        self.updates += 1;
159        // Each label's detections: index in `detections`, TLWH box, score.
160        let mut groups: BTreeMap<Option<String>, Vec<Detection>> = BTreeMap::new();
161        for (i, region) in detections.iter_mut().enumerate() {
162            region.track = None;
163            let Some(b) = region.shape.bbox() else { continue };
164            let (w, h) = (b.x1 - b.x0, b.y1 - b.y0);
165            if !(w > 0.0 && h > 0.0 && b.x0.is_finite() && b.y0.is_finite()) {
166                continue;
167            }
168            let score = region.score.unwrap_or(1.0);
169            groups.entry(region.label.clone()).or_default().push((i, [b.x0, b.y0, w, h], score));
170        }
171        for label in groups.keys() {
172            if !self.lanes.contains_key(label) {
173                let lane = Lane {
174                    tracker: ByteTrack::from_params(self.config.params()),
175                    ids: HashMap::new(),
176                };
177                self.lanes.insert(label.clone(), lane);
178            }
179        }
180        // Every lane steps each frame, so an absent label ages its lost tracks too; lanes
181        // step in label order, so identifiers are handed out the same way on every run.
182        let horizon = u64::from(self.config.max_missed) + 1;
183        let (updates, next) = (self.updates, &mut self.next);
184        for (label, lane) in &mut self.lanes {
185            let group = groups.remove(label).unwrap_or_default();
186            let input = group.iter().map(|(_, tlwh, score)| (*tlwh, *score, 0i64)).collect();
187            for track in lane.tracker.update(input) {
188                let Some(&(index, _, _)) = track.det_ind.and_then(|d| group.get(d)) else {
189                    continue;
190                };
191                let entry = lane.ids.entry(track.track_id).or_insert_with(|| {
192                    let id = TrackId(*next);
193                    *next += 1;
194                    (id, updates)
195                });
196                entry.1 = updates;
197                detections[index].track = Some(entry.0);
198            }
199            lane.ids.retain(|_, (_, seen)| updates - *seen <= horizon);
200        }
201        self.lanes.retain(|_, lane| !lane.ids.is_empty());
202        detections
203    }
204
205    fn reset(&mut self) {
206        self.lanes.clear();
207        self.next = 0;
208        self.updates = 0;
209    }
210
211    fn live_tracks(&self) -> Vec<TrackId> {
212        let mut live: Vec<TrackId> =
213            self.lanes.values().flat_map(|lane| lane.ids.values().map(|(id, _)| *id)).collect();
214        live.sort_unstable();
215        live
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::Digest;
223    use crate::backend::BackendId;
224    use crate::geometry::{BBox, CoordFrame, RegionOrigin, Shape, TransformChain};
225    use crate::media::FrameSourceId;
226
227    fn frame(index: u64) -> FrameMeta {
228        FrameMeta {
229            source: FrameSourceId("test".into()),
230            index,
231            pts_ms: index * 200,
232            captured_at: chrono::Utc::now(),
233        }
234    }
235
236    fn region(bbox: BBox, label: &str, score: f32) -> Region {
237        Region {
238            image: Digest::of(b"frame"),
239            shape: Shape::Box(bbox),
240            label: Some(label.into()),
241            score: Some(score),
242            track: None,
243            origin: RegionOrigin {
244                backend: BackendId::new("test"),
245                manifest: None,
246                frame: CoordFrame::SentPixels,
247                chain: TransformChain::new(640, 480),
248                escalated_from: None,
249            },
250        }
251    }
252
253    #[test]
254    fn labels_are_tracked_apart() {
255        let mut tracker = ByteTracker::default();
256        let same = BBox::new(100.0, 100.0, 200.0, 200.0);
257        let out = tracker
258            .update(&frame(0), vec![region(same, "person", 0.9), region(same, "forklift", 0.9)]);
259        assert_ne!(out[0].track, out[1].track);
260        let again = tracker
261            .update(&frame(1), vec![region(same, "forklift", 0.9), region(same, "person", 0.9)]);
262        assert_eq!((again[0].track, again[1].track), (out[1].track, out[0].track));
263    }
264
265    #[test]
266    fn a_weak_detection_starts_no_track_but_continues_one() {
267        let mut tracker = ByteTracker::default();
268        let b = BBox::new(10.0, 10.0, 90.0, 90.0);
269        assert_eq!(tracker.update(&frame(0), vec![region(b, "part", 0.3)])[0].track, None);
270        let first = tracker.update(&frame(1), vec![region(b, "part", 0.9)])[0].track;
271        assert!(first.is_some());
272        // A low score inside the track's box recovers it (ByteTrack's second pass).
273        assert_eq!(tracker.update(&frame(2), vec![region(b, "part", 0.3)])[0].track, first);
274    }
275
276    #[test]
277    fn regions_without_area_carry_no_track() {
278        let mut tracker = ByteTracker::default();
279        let out = tracker.update(&frame(0), vec![region(BBox::new(5.0, 5.0, 5.0, 9.0), "x", 0.9)]);
280        assert_eq!(out[0].track, None);
281    }
282
283    #[test]
284    fn forgotten_tracks_release_their_lanes() {
285        let mut tracker = ByteTracker::new(ByteTrackConfig::default().with_max_missed(2));
286        tracker.update(&frame(0), vec![region(BBox::new(0.0, 0.0, 50.0, 50.0), "a", 0.9)]);
287        for i in 1..6 {
288            tracker.update(&frame(i), Vec::new());
289        }
290        assert!(tracker.lanes.is_empty());
291    }
292}