Motion & Tracking
Kalman Filter
A recursive algorithm that estimates the hidden state of a linear dynamic system from a sequence of noisy measurements, widely used to smooth and predict object positions in tracking.
intermediate
The Kalman filter estimates the hidden state of a dynamic system, such as the position and velocity of a moving object, from a sequence of noisy measurements. At every time step it predicts the state forward with a motion model, then corrects the prediction with the new measurement, weighting the two by their uncertainties. Introduced by Rudolf Kalman in 1960, it is one of the most widely used estimation algorithms in engineering. In computer vision it is the standard way to smooth noisy detections, predict where an object will appear in the next frame, and bridge short gaps in detection, which makes it a core component of object tracking systems.
Problem
A system’s state cannot be observed directly; at each time step a sensor produces a noisy measurement that depends on it. The goal is to estimate the current state from all measurements so far, online, without reprocessing the history. In tracking, the state might be a bounding-box center and its velocity, and the measurement the center reported by a detector, which jitters, occasionally goes missing, and carries no velocity information.
Inputs and Outputs
Inputs: a state-space model (transition matrix , measurement matrix , noise covariances and ); an initial estimate with covariance ; and a measurement at each step, or none when it is missing.
Outputs, at each step: the state estimate and its error covariance , plus the one-step predictions of state and measurement used for gating and data association.
Intuition
The filter maintains a belief: a best guess and an uncertainty around it.
- Predict. Move the belief forward with the motion model: an object at with velocity should now be near . Because the model is imperfect, uncertainty grows.
- Update. Move the estimate part of the way toward the new measurement. Uncertainty shrinks.
How far the estimate moves is set by the Kalman gain. In the scalar case, with prediction of variance and a measurement of variance ,
A confident prediction and a noisy sensor give a small gain; an uncertain prediction and a precise sensor give a gain near 1. The matrix version does the same per direction in state space and also corrects components that are never measured: velocity is inferred from how successive position measurements deviate from the predictions.
Algorithm
- Initialize and , with large variance for poorly known components.
- For each time step :
- Predict the state and covariance with the motion model.
- If a measurement is available, compute the innovation, the Kalman gain, and the updated state and covariance.
- Otherwise, keep the prediction as the estimate; its covariance keeps growing until a measurement arrives.
Mathematical Formulation
State-space model
The Kalman filter assumes a linear-Gaussian state-space model:
Here is the state and the measurement; the process noise and measurement noise are zero-mean, white, and mutually independent. (A known control input can be added to the transition; vision trackers rarely have one.) denotes the estimate of given measurements up to step (the prediction), the estimate given measurements up to step , and , the corresponding error covariances.
Predict
Update
is the innovation and its covariance. When the model is correct, the squared Mahalanobis distance follows a chi-squared distribution with degrees of freedom. Trackers use it to gate measurements: a detection whose distance exceeds a chi-squared threshold is considered too unlikely to belong to the track.
Running example: constant-velocity model
To track the center of a point or bounding box, a common choice is the state , measurement , and frame interval :
Velocity stays constant and position integrates it; process noise accounts for unmodeled acceleration. Modeling the acceleration as constant within each frame interval and independent between intervals, with variance per axis (the discrete white-noise acceleration model), gives
and isotropic detector noise gives . Bounding-box trackers often extend the state with box size. SORT, for example, uses the box center, area, and aspect ratio, plus velocities of the center and area; the aspect ratio is assumed constant.
Parameters
- Measurement noise . Detector noise; it can be estimated against ground truth and for box detectors often scales with object size.
- Process noise . How much true motion departs from the model; usually tuned. Small gives smooth estimates that lag behind maneuvers; large responds quickly but passes more noise.
- Ratio, not scale. Multiplying , , and by the same factor leaves the gain and state estimates unchanged; only the reported covariance scales.
- Initial covariance . Large for components unknown at initialization, such as velocity for a track created from one detection.
- Motion model. Constant position, velocity, or acceleration trade responsiveness against smoothness; constant velocity is the usual default in video.
A useful consistency check: in a well-tuned filter, the normalized innovation squared averages about . Consistently larger values mean the filter is overconfident, usually because or is too small.
Complexity
For state dimension and measurement dimension , each step costs for the covariance prediction and for the update, including the inversion of . Memory is . The cost per step does not grow with sequence length, because the estimate and covariance summarize all past measurements; for the four-dimensional constant-velocity model it is negligible even with hundreds of tracked objects.
Implementation
A constant-velocity Kalman filter tracking a point that moves in a straight line, observed with Gaussian noise of standard deviation 2 pixels:
import numpy as np
dt = 1.0 # time between frames
q = 0.01 # acceleration variance (unmodeled motion)
r = 4.0 # measurement noise variance, in pixels^2
# State x = [px, py, vx, vy]; measurement z = [px, py].
F = np.array([[1, 0, dt, 0],
[0, 1, 0, dt],
[0, 0, 1, 0],
[0, 0, 0, 1]], dtype=float)
H = np.array([[1, 0, 0, 0],
[0, 1, 0, 0]], dtype=float)
G = np.array([[dt**2 / 2, 0], [0, dt**2 / 2], [dt, 0], [0, dt]])
Q = q * G @ G.T # white-noise acceleration model
R = r * np.eye(2)
def predict(x, P):
x = F @ x
P = F @ P @ F.T + Q
return x, P
def update(x, P, z):
y = z - H @ x # innovation
S = H @ P @ H.T + R # innovation covariance
K = P @ H.T @ np.linalg.inv(S) # Kalman gain
x = x + K @ y
P = (np.eye(len(x)) - K @ H) @ P
return x, P
# Simulate a point moving at constant velocity, observed with noise.
rng = np.random.default_rng(0)
true_x = np.array([0.0, 0.0, 2.0, 1.0])
x = np.array([0.0, 0.0, 0.0, 0.0]) # initial guess: unknown velocity
P = np.diag([10.0, 10.0, 100.0, 100.0]) # large initial uncertainty
raw_err, filt_err = [], []
for t in range(50):
true_x = F @ true_x
z = H @ true_x + rng.normal(0.0, np.sqrt(r), size=2)
x, P = predict(x, P)
x, P = update(x, P, z)
raw_err.append(np.linalg.norm(z - true_x[:2]))
filt_err.append(np.linalg.norm(x[:2] - true_x[:2]))
print(f"mean position error, raw measurements: {np.mean(raw_err[10:]):.2f} px")
print(f"mean position error, Kalman filter: {np.mean(filt_err[10:]):.2f} px")
print("estimated velocity:", np.round(x[2:], 2))
Output:
mean position error, raw measurements: 2.54 px
mean position error, Kalman filter: 1.37 px
estimated velocity: [1.85 0.87]
After a short warm-up, the filtered positions are nearly twice as accurate as the raw measurements, and the filter has recovered the velocity, true value , although velocity is never measured. When a detection is missing, a tracker calls predict without update. Production code typically solves a linear system instead of forming , and uses the Joseph form to keep the covariance symmetric and positive semi-definite under rounding.
Properties and Behavior
- Optimality. For a linear model with Gaussian noise and Gaussian initial state, the posterior of the state given all measurements is Gaussian with mean and covariance . The Kalman estimate, the closed-form recursive Bayesian solution, is then the minimum mean squared error (MMSE) estimate and also the most probable state. Without the Gaussian assumption, but with the same linear model and known second-order noise statistics, it is the best linear unbiased estimator: minimum error variance among estimators linear in the measurements. A nonlinear estimator may do better.
- Data-independent covariance. and depend only on , , , , and , not on the measured values. For a time-invariant model that is detectable and stabilizable (with respect to the process noise), they converge to steady-state values, so a fixed-gain filter can be precomputed.
- Missing data. Skipping the update is correct under the model; the growing uncertainty widens the gate for re-associating the object.
- Sensitivity to modeling errors. With a wrong motion model or misestimated and , the filter can be biased, lag behind maneuvers, or become overconfident and ignore measurements.
Limitations
- Linearity. Perspective projection, rotation, and bearing-only sensors are nonlinear; the basic filter does not apply directly.
- Unimodal Gaussian belief. A single Gaussian cannot represent an object that may be behind either of two occluders, and one outlier detection can pull the estimate far off. Gating and robust variants mitigate this.
- No data association. With several objects, a separate step decides which detection updates which filter, for example the Hungarian algorithm on predicted positions or Mahalanobis distances. The filter cannot detect wrong associations.
- Model dependence. Constant velocity describes erratic motion, such as people in crowds, poorly, and uncompensated camera motion is treated as object motion.
Variants
The extended Kalman filter linearizes nonlinear dynamics and measurement functions around the current estimate using their Jacobians. It is widely used, for example in visual-inertial odometry and SLAM, but can diverge when the nonlinearity is strong relative to the uncertainty.
The unscented Kalman filter passes a small, deterministically chosen set of sigma points through the nonlinear functions and fits a Gaussian to the result. It needs no Jacobians and typically captures the transformed mean and covariance more accurately than linearization, at comparable cost.
The information filter propagates the inverse covariance and an information vector; updates become additive, which suits multi-sensor and decentralized fusion.
The Rauch–Tung–Striebel smoother refines past estimates offline with later measurements: a backward pass after the forward filter gives error covariance no larger than the filter’s.
Particle filters represent the belief with weighted samples and handle nonlinear models and multimodal distributions at much higher cost. Multiple-model filters run Kalman filters with different motion models in parallel and mix their estimates, which suits targets that alternate between, for example, moving straight and turning.
Related
- Object Tracking
Estimating the position, extent, or state of one or more objects in every frame of a video, keeping each object's identity over time.
- Hungarian Algorithm
An algorithm that finds the minimum-cost one-to-one matching between two sets, used in computer vision to match detections to tracks and predictions to ground truth.
- Data Association
Deciding which measurements or detections belong to which tracked targets, and which are false alarms, missed detections, new targets, or targets that have disappeared.
- SORT
Simple Online and Realtime Tracking, a multi-object tracker that links per-frame detections into tracks using a constant-velocity Kalman filter on each box and Hungarian matching on box overlap.
- A New Approach to Linear Filtering and Prediction Problems
Rudolf Kalman's 1960 paper that recast Wiener's filtering problem in state-space form and solved it with a recursive estimator, the origin of the Kalman filter.
References
- Kalman, R. E. (1960). A New Approach to Linear Filtering and Prediction Problems. Journal of Basic Engineering, 82(1), 35–45.
- Rauch, H. E., Tung, F. & Striebel, C. T. (1965). Maximum Likelihood Estimates of Linear Dynamic Systems. AIAA Journal, 3(8), 1445–1450.
- Julier, S. J. & Uhlmann, J. K. (2004). Unscented Filtering and Nonlinear Estimation. Proceedings of the IEEE, 92(3), 401–422.
- Bewley, A., Ge, Z., Ott, L., Ramos, F. & Upcroft, B. (2016). Simple Online and Realtime Tracking. IEEE International Conference on Image Processing (ICIP), 3464–3468.