use crate::assignment::assign_with_cost_limit;
use crate::bbox::{BBox, Detection};
use crate::kalman::{BoxKalmanFilter, BoxKalmanState};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ByteTrackConfig {
pub high_score_threshold: f64,
pub low_score_threshold: f64,
pub new_track_score_threshold: f64,
pub first_match_cost_limit: f64,
pub second_match_cost_limit: f64,
pub unconfirmed_match_cost_limit: f64,
pub fuse_score: bool,
pub max_frames_lost: u64,
pub class_aware: bool,
pub duplicate_cost_limit: f64,
pub kalman: BoxKalmanFilter,
}
impl Default for ByteTrackConfig {
fn default() -> Self {
Self {
high_score_threshold: 0.5,
low_score_threshold: 0.1,
new_track_score_threshold: 0.6,
first_match_cost_limit: 0.8,
second_match_cost_limit: 0.5,
unconfirmed_match_cost_limit: 0.7,
fuse_score: true,
max_frames_lost: 30,
class_aware: true,
duplicate_cost_limit: 0.15,
kalman: BoxKalmanFilter::default(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TrackId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TrackedObject {
pub id: TrackId,
pub class_id: u32,
pub bbox: BBox,
pub score: f64,
pub detection_index: usize,
pub start_frame: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TrackState {
Tracked,
Lost,
}
#[derive(Debug, Clone)]
struct Track {
id: Option<TrackId>,
class_id: u32,
kalman: BoxKalmanState,
state: TrackState,
score: f64,
start_frame: u64,
last_frame: u64,
detection_index: Option<usize>,
}
impl Track {
fn bbox(&self) -> BBox {
self.kalman.bbox()
}
}
#[derive(Debug, Clone)]
pub struct ByteTracker {
config: ByteTrackConfig,
frame: u64,
next_id: u64,
tracked: Vec<Track>,
lost: Vec<Track>,
}
impl Default for ByteTracker {
fn default() -> Self {
Self::new(ByteTrackConfig::default())
}
}
impl ByteTracker {
pub fn new(config: ByteTrackConfig) -> Self {
Self {
config,
frame: 0,
next_id: 1,
tracked: Vec::new(),
lost: Vec::new(),
}
}
pub fn config(&self) -> &ByteTrackConfig {
&self.config
}
pub fn frame(&self) -> u64 {
self.frame
}
pub fn lost_track_ids(&self) -> Vec<TrackId> {
let mut ids: Vec<TrackId> = self.lost.iter().filter_map(|t| t.id).collect();
ids.sort();
ids
}
pub fn reset(&mut self) {
*self = Self::new(self.config);
}
pub fn update(&mut self, detections: &[Detection]) -> Vec<TrackedObject> {
self.frame += 1;
let frame = self.frame;
let config = self.config;
let kalman = config.kalman;
let usable = |d: &Detection| d.bbox.is_valid() && d.score.is_finite();
let high: Vec<usize> = (0..detections.len())
.filter(|&i| {
usable(&detections[i]) && detections[i].score >= config.high_score_threshold
})
.collect();
let low: Vec<usize> = (0..detections.len())
.filter(|&i| {
let score = detections[i].score;
usable(&detections[i])
&& score >= config.low_score_threshold
&& score < config.high_score_threshold
})
.collect();
let (mut pool, mut unconfirmed): (Vec<Track>, Vec<Track>) =
std::mem::take(&mut self.tracked)
.into_iter()
.partition(|t| t.id.is_some());
pool.append(&mut self.lost);
for track in pool.iter_mut().chain(unconfirmed.iter_mut()) {
track.detection_index = None;
}
for track in &mut pool {
if track.state == TrackState::Lost {
track.kalman.mean[7] = 0.0;
}
kalman.predict(&mut track.kalman);
}
let first = self.associate(
&pool.iter().collect::<Vec<_>>(),
&high,
detections,
config.fuse_score,
config.first_match_cost_limit,
);
for &(t, d) in &first.matches {
self.apply(&mut pool[t], detections, high[d]);
}
let remaining_high: Vec<usize> = first.unmatched_cols.iter().map(|&d| high[d]).collect();
let still_tracked: Vec<usize> = first
.unmatched_rows
.iter()
.copied()
.filter(|&t| pool[t].state == TrackState::Tracked)
.collect();
let second = self.associate(
&still_tracked.iter().map(|&t| &pool[t]).collect::<Vec<_>>(),
&low,
detections,
false,
config.second_match_cost_limit,
);
for &(t, d) in &second.matches {
self.apply(&mut pool[still_tracked[t]], detections, low[d]);
}
for &t in &second.unmatched_rows {
pool[still_tracked[t]].state = TrackState::Lost;
}
let third = self.associate(
&unconfirmed.iter().collect::<Vec<_>>(),
&remaining_high,
detections,
config.fuse_score,
config.unconfirmed_match_cost_limit,
);
let mut confirmed = Vec::with_capacity(third.matches.len());
for &(t, d) in &third.matches {
let mut track = unconfirmed[t].clone();
self.apply(&mut track, detections, remaining_high[d]);
confirmed.push(track);
}
let mut started = Vec::new();
for &d in &third.unmatched_cols {
let detection = &detections[remaining_high[d]];
if detection.score < config.new_track_score_threshold {
continue;
}
let mut track = Track {
id: None,
class_id: detection.class_id,
kalman: kalman.initiate(&detection.bbox),
state: TrackState::Tracked,
score: detection.score,
start_frame: frame,
last_frame: frame,
detection_index: Some(remaining_high[d]),
};
if frame == 1 {
track.id = Some(self.take_id());
}
started.push(track);
}
let (mut tracked, lost): (Vec<Track>, Vec<Track>) = pool
.into_iter()
.partition(|t| t.state == TrackState::Tracked);
tracked.extend(confirmed);
tracked.extend(started);
let lost: Vec<Track> = lost
.into_iter()
.filter(|t| frame - t.last_frame <= config.max_frames_lost)
.collect();
let (tracked, lost) = self.remove_duplicates(tracked, lost);
self.tracked = tracked;
self.lost = lost;
let mut output: Vec<TrackedObject> = self
.tracked
.iter()
.filter_map(|t| {
Some(TrackedObject {
id: t.id?,
class_id: t.class_id,
bbox: t.bbox(),
score: t.score,
detection_index: t.detection_index?,
start_frame: t.start_frame,
})
})
.collect();
output.sort_by_key(|o| o.id);
output
}
fn take_id(&mut self) -> TrackId {
let id = TrackId(self.next_id);
self.next_id += 1;
id
}
fn apply(&mut self, track: &mut Track, detections: &[Detection], index: usize) {
let detection = &detections[index];
self.config
.kalman
.update(&mut track.kalman, &detection.bbox);
track.state = TrackState::Tracked;
track.score = detection.score;
track.last_frame = self.frame;
track.detection_index = Some(index);
if track.id.is_none() {
track.id = Some(self.take_id());
}
}
fn associate(
&self,
tracks: &[&Track],
indices: &[usize],
detections: &[Detection],
fuse_score: bool,
cost_limit: f64,
) -> crate::assignment::Assignment {
let mut costs = Vec::with_capacity(tracks.len() * indices.len());
for track in tracks {
let bbox = track.bbox();
for &i in indices {
let detection = &detections[i];
let cost = if self.config.class_aware && track.class_id != detection.class_id {
f64::INFINITY
} else {
let iou = bbox.iou(&detection.bbox);
1.0 - if fuse_score {
iou * detection.score
} else {
iou
}
};
costs.push(cost);
}
}
assign_with_cost_limit(tracks.len(), indices.len(), &costs, cost_limit)
}
fn remove_duplicates(&self, tracked: Vec<Track>, lost: Vec<Track>) -> (Vec<Track>, Vec<Track>) {
let mut drop_tracked = vec![false; tracked.len()];
let mut drop_lost = vec![false; lost.len()];
for (p, a) in tracked.iter().enumerate() {
for (q, b) in lost.iter().enumerate() {
if self.config.class_aware && a.class_id != b.class_id {
continue;
}
if 1.0 - a.bbox().iou(&b.bbox()) < self.config.duplicate_cost_limit {
if a.last_frame - a.start_frame > b.last_frame - b.start_frame {
drop_lost[q] = true;
} else {
drop_tracked[p] = true;
}
}
}
}
let keep = |tracks: Vec<Track>, drop: &[bool]| {
tracks
.into_iter()
.zip(drop)
.filter_map(|(t, &d)| (!d).then_some(t))
.collect::<Vec<_>>()
};
(keep(tracked, &drop_tracked), keep(lost, &drop_lost))
}
}