1use crate::assignment::assign_with_cost_limit;
21use crate::bbox::{BBox, Detection};
22use crate::kalman::{BoxKalmanFilter, BoxKalmanState};
23
24#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct ByteTrackConfig {
27 pub high_score_threshold: f64,
29 pub low_score_threshold: f64,
32 pub new_track_score_threshold: f64,
35 pub first_match_cost_limit: f64,
37 pub second_match_cost_limit: f64,
39 pub unconfirmed_match_cost_limit: f64,
41 pub fuse_score: bool,
44 pub max_frames_lost: u64,
47 pub class_aware: bool,
50 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
76pub struct TrackId(pub u64);
77
78#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct TrackedObject {
81 pub id: TrackId,
82 pub class_id: u32,
84 pub bbox: BBox,
86 pub score: f64,
88 pub detection_index: usize,
90 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 last_frame: u64,
110 detection_index: Option<usize>,
112}
113
114impl Track {
115 fn bbox(&self) -> BBox {
116 self.kalman.bbox()
117 }
118}
119
120#[derive(Debug, Clone)]
122pub struct ByteTracker {
123 config: ByteTrackConfig,
124 frame: u64,
125 next_id: u64,
126 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 pub fn frame(&self) -> u64 {
154 self.frame
155 }
156
157 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 pub fn reset(&mut self) {
166 *self = Self::new(self.config);
167 }
168
169 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 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 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 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 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 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 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 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 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}