Skip to main content

visloc_objects/
kalman.rs

1//! Constant-velocity Kalman filter on image boxes, as in SORT, DeepSORT and ByteTrack.
2//!
3//! The state is `(cx, cy, a, h, vcx, vcy, va, vh)`: box centre, aspect ratio
4//! `a = w / h`, height, and their per-frame velocities. The noise is scaled by
5//! the box height, so a far (small) object and a near (large) one are tracked
6//! with the same relative uncertainty.
7
8use nalgebra::{Matrix4, SMatrix, SVector, Vector4};
9
10use crate::bbox::BBox;
11
12pub type BoxState = SVector<f64, 8>;
13pub type BoxCovariance = SMatrix<f64, 8, 8>;
14
15/// Noise weights of the filter; the defaults are ByteTrack's.
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct BoxKalmanFilter {
18    /// Position noise as a fraction of the box height (1/20).
19    pub std_weight_position: f64,
20    /// Velocity noise as a fraction of the box height (1/160).
21    pub std_weight_velocity: f64,
22}
23
24impl Default for BoxKalmanFilter {
25    fn default() -> Self {
26        Self {
27            std_weight_position: 1.0 / 20.0,
28            std_weight_velocity: 1.0 / 160.0,
29        }
30    }
31}
32
33/// Mean and covariance of one track's box.
34#[derive(Debug, Clone, PartialEq)]
35pub struct BoxKalmanState {
36    pub mean: BoxState,
37    pub covariance: BoxCovariance,
38}
39
40impl BoxKalmanState {
41    /// The box at the state's mean.
42    pub fn bbox(&self) -> BBox {
43        let height = self.mean[3];
44        BBox::from_center_size(self.mean[0], self.mean[1], self.mean[2] * height, height)
45    }
46}
47
48/// `(cx, cy, w / h, h)` of a box with a positive height.
49pub fn box_measurement(bbox: &BBox) -> Vector4<f64> {
50    let (cx, cy) = bbox.center();
51    let height = bbox.height();
52    Vector4::new(cx, cy, bbox.width() / height, height)
53}
54
55impl BoxKalmanFilter {
56    /// A state at `bbox` with zero velocity.
57    pub fn initiate(&self, bbox: &BBox) -> BoxKalmanState {
58        let z = box_measurement(bbox);
59        let mut mean = BoxState::zeros();
60        mean.fixed_rows_mut::<4>(0).copy_from(&z);
61        let p = self.std_weight_position * z[3];
62        let v = self.std_weight_velocity * z[3];
63        let std = [
64            2.0 * p,
65            2.0 * p,
66            1e-2,
67            2.0 * p,
68            10.0 * v,
69            10.0 * v,
70            1e-5,
71            10.0 * v,
72        ];
73        BoxKalmanState {
74            mean,
75            covariance: BoxCovariance::from_diagonal(&BoxState::from_iterator(
76                std.iter().map(|s| s * s),
77            )),
78        }
79    }
80
81    /// Advance the state by one frame.
82    pub fn predict(&self, state: &mut BoxKalmanState) {
83        let height = state.mean[3];
84        let p = self.std_weight_position * height;
85        let v = self.std_weight_velocity * height;
86        let std = [p, p, 1e-2, p, v, v, 1e-5, v];
87        let mut motion = BoxCovariance::identity();
88        for i in 0..4 {
89            motion[(i, i + 4)] = 1.0;
90        }
91        state.mean = motion * state.mean;
92        state.covariance = motion * state.covariance * motion.transpose()
93            + BoxCovariance::from_diagonal(&BoxState::from_iterator(std.iter().map(|s| s * s)));
94    }
95
96    /// Correct the state with a measured box. A box with a non-positive height
97    /// is ignored.
98    pub fn update(&self, state: &mut BoxKalmanState, bbox: &BBox) {
99        if bbox.height() <= 0.0 {
100            return;
101        }
102        let height = state.mean[3];
103        let p = self.std_weight_position * height;
104        let measurement_noise = Matrix4::from_diagonal(&Vector4::new(p * p, p * p, 1e-2, p * p));
105        // H = [I4 0]: the measurement is the first four state entries.
106        let projected_covariance =
107            state.covariance.fixed_view::<4, 4>(0, 0).into_owned() + measurement_noise;
108        let covariance_ht = state.covariance.fixed_view::<8, 4>(0, 0).into_owned();
109        let Some(cholesky) = projected_covariance.cholesky() else {
110            *state = self.initiate(bbox);
111            return;
112        };
113        // K = P Hᵀ S⁻¹, from S Kᵀ = H P.
114        let gain = cholesky.solve(&covariance_ht.transpose()).transpose();
115        let innovation = box_measurement(bbox) - state.mean.fixed_rows::<4>(0);
116        state.mean += gain * innovation;
117        let covariance = state.covariance - gain * projected_covariance * gain.transpose();
118        state.covariance = 0.5 * (covariance + covariance.transpose());
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn initiate_round_trips_the_box() {
128        let filter = BoxKalmanFilter::default();
129        let bbox = BBox::from_xywh(10.0, 20.0, 30.0, 60.0);
130        let state = filter.initiate(&bbox);
131        let back = state.bbox();
132        for (a, b) in [
133            (back.x_min, bbox.x_min),
134            (back.y_min, bbox.y_min),
135            (back.x_max, bbox.x_max),
136            (back.y_max, bbox.y_max),
137        ] {
138            assert!((a - b).abs() < 1e-9);
139        }
140    }
141
142    #[test]
143    fn learns_a_constant_velocity_and_predicts_with_it() {
144        let filter = BoxKalmanFilter::default();
145        let at = |k: f64| BBox::from_center_size(100.0 + 4.0 * k, 50.0 - 1.0 * k, 40.0, 80.0);
146        let mut state = filter.initiate(&at(0.0));
147        for k in 1..30 {
148            filter.predict(&mut state);
149            filter.update(&mut state, &at(k as f64));
150        }
151        assert!((state.mean[4] - 4.0).abs() < 0.05, "vx {}", state.mean[4]);
152        assert!((state.mean[5] + 1.0).abs() < 0.05, "vy {}", state.mean[5]);
153        // Five frames without measurements: the box keeps moving.
154        for _ in 0..5 {
155            filter.predict(&mut state);
156        }
157        let (cx, cy) = state.bbox().center();
158        assert!((cx - (100.0 + 4.0 * 34.0)).abs() < 1.0, "cx {cx}");
159        assert!((cy - (50.0 - 34.0)).abs() < 1.0, "cy {cy}");
160        assert_eq!(state.covariance, state.covariance.transpose());
161    }
162
163    #[test]
164    fn a_zero_height_measurement_is_ignored() {
165        let filter = BoxKalmanFilter::default();
166        let mut state = filter.initiate(&BBox::from_xywh(0.0, 0.0, 10.0, 20.0));
167        let before = state.clone();
168        filter.update(&mut state, &BBox::new(0.0, 5.0, 10.0, 5.0));
169        assert_eq!(state, before);
170    }
171}