Algorithm Search⌘K

Algorithmadvanced

SORT tracker

Also called simple online and realtime tracking.

Predict each track with a constant velocity Kalman filter on its box and assign detections by the Hungarian algorithm on IoU, frame by frame.

Time
O(N n m (n + m)) worst
Space
O(n m) extra
Where
N = the number of frames; m = the number of detections in a frame; n = the number of tracks
Properties
deterministicnot exactnot iterativeonline
Origin
Alex Bewley, Zongyuan Ge, Lionel Ott, Fabio Ramos, Ben Upcroft, 2016

SORT, short for simple online and realtime tracking, is a multi-object tracker of the tracking by detection kind. An object detector gives boxes in each frame, and SORT links them into tracks. Each track has a constant velocity Kalman filter on its box. In each frame the tracks predict their boxes, the intersection over union (IoU) between each prediction and each detection is the score of the pair, and the Hungarian algorithm picks the one-to-one assignment of largest total IoU. SORT uses no appearance and no past frames beyond the filter state, so it is fast and simple. Its weak point is identity switches after occlusions, which Deep SORT and ByteTrack address. The page global nearest neighbor association describes the same one-assignment-per-frame idea with a Mahalanobis cost; SORT replaces it with an IoU score and adds simple rules to start and end tracks.

In plain words

A camera watches a street, and a detector draws a box around each person in every picture, but it does not say who is who. SORT keeps a list of tracks, one per person. For each track it guesses where the box will be in the next picture, by assuming the person keeps the same speed. When the next picture comes, it compares each guessed box with each new box and measures how much they overlap. Then it pairs guesses and boxes so that the total overlap is as large as possible, with each box used once. A pair that overlaps too little is not accepted. Each track moves to its new box. A box that no track takes starts a new track, and a track that gets no box for too long is dropped.

The problem

The input is a sequence of frames. Frame tt comes with a list of mm detections d1,…,dmd_1, \ldots, d_m, each a box (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) in continuous image coordinates with x1<x2x_1 < x_2 and y1<y2y_1 < y_2, and area (x2−x1)(y2−y1)(x_2 - x_1)(y_2 - y_1), with no +1+1 term. The output of frame tt is a list of pairs (identity, box). The tracker is online: the output of frame tt depends only on frames 11 to tt. The goal is the one of multi-object tracking: each object keeps one identity for as long as it is in view, with few misses and few false tracks.

The state of a track. A track holds the Kalman state

x=(u,v,s,r,u˙,v˙,s˙),x = (u, v, s, r, \dot u, \dot v, \dot s),

where (u,v)(u, v) is the box center, s=whs = w h the area, r=w/hr = w / h the aspect ratio, and the dots are velocities in pixels per frame (and pixels squared per frame for ss). The ratio rr has no velocity: SORT takes it as constant. A box maps to the measurement z=(u,v,s,r)z = (u, v, s, r), and back by w=srw = \sqrt{s r} and h=s/wh = s / w. The motion is xt+1=Fxt+noisex_{t+1} = F x_t + \text{noise}, with FF the identity plus ones that add u˙,v˙,s˙\dot u, \dot v, \dot s to u,v,su, v, s. The measurement matrix HH picks the first four entries.

The algorithm

  1. SORT-STEP(the tracks, the detections d_1..d_m, IoU_min, max_age, min_hits)
  2. 1for each track i: Kalman predict x_i and P_i; drop the track if its box has s ≤ 0
  3. 2for each track i and each detection j: c_ij ← IoU(box of x_i, d_j)
  4. 3σ ← the assignment of largest total Σ c_iσ(i), by the Hungarian algorithm
  5. 4keep only the pairs (i, σ(i)) with c_iσ(i) ≥ IoU_min
  6. 5for each kept pair (i, j): Kalman update of track i with z(d_j)
  7. 6for each detection j in no kept pair: a new track with x = (z(d_j), 0, 0, 0)
  8. 7delete each track whose time since its last update exceeds max_age
  9. 8output the tracks updated in this frame that have at least min_hits updates in a row

The assignment of line L3 has size min⁡(n,m)\min(n, m) and uses every pair, also pairs with IoU 0. Line L4 then removes the weak pairs, so a track may end the frame with no detection. The paper says that a minimum IoU rejects weak pairs; the released code uses IoUmin⁡=0.3\mathrm{IoU}_{\min} = 0.3.

Track management. A new track starts with zero velocity and a large variance on the velocity, so the first updates set the velocity. The paper deletes a track that is not detected for Tlost=1T_{\text{lost}} = 1 frame. In the released code, which this page follows, a track is deleted when its count of frames since the last update passes max_age = 1, so it survives one missed frame and dies at the second. A new track is not reported until it has min_hits = 3 updates in a row, except in the first 3 frames of the video; the paper calls this the probation period. These rules are heuristics. They are tuned, and they often change the score of the tracker more than the assignment does.

The filter. The noise matrices of the released code are R=diag(1,1,10,10)R = \mathrm{diag}(1, 1, 10, 10) for the measurement, Q=diag(1,1,1,1,0.01,0.01,10−4)Q = \mathrm{diag}(1, 1, 1, 1, 0.01, 0.01, 10^{-4}) for the motion, and P0=diag(10,10,10,10,104,104,104)P_0 = \mathrm{diag}(10, 10, 10, 10, 10^4, 10^4, 10^4) for a new track. If the predicted area s+s˙s + \dot s would be negative, the code sets s˙\dot s to 0 first.

Example

One frame. Two tracks predict the boxes A=(0,0,10,10)A = (0, 0, 10, 10) and B=(6,0,16,10)B = (6, 0, 16, 10). The detector gives d1=(4,0,14,10)d_1 = (4, 0, 14, 10), d2=(9,0,19,10)d_2 = (9, 0, 19, 10) and d3=(40,40,50,50)d_3 = (40, 40, 50, 50). All boxes are 10 by 10, so each union is 200200 minus the overlap. The IoU matrix is

d1d_1 d2d_2 d3d_3
AA 60/140=3/7≈0.42960/140 = 3/7 \approx 0.429 10/190=1/19≈0.05310/190 = 1/19 \approx 0.053 0
BB 80/120=2/3≈0.66780/120 = 2/3 \approx 0.667 70/130=7/13≈0.53870/130 = 7/13 \approx 0.538 0

The assignment A→d1A \to d_1, B→d2B \to d_2 has total 0.429+0.538=0.9670.429 + 0.538 = 0.967. The other choice that uses d1d_1 and d2d_2, A→d2A \to d_2, B→d1B \to d_1, has total 0.053+0.667=0.7190.053 + 0.667 = 0.719. The Hungarian algorithm returns the first one. Both pairs pass IoUmin⁡=0.3\mathrm{IoU}_{\min} = 0.3, so both tracks are updated, and d3d_3 starts a new track. A greedy rule that takes the largest IoU first would pair BB with d1d_1, and then AA could only have d2d_2 at IoU 1/191/19, below the threshold. Track AA would miss its detection, and d2d_2 would start a false new track.

For the box d1d_1 the measurement is z=(9,5,100,1)z = (9, 5, 100, 1): center (9,5)(9, 5), area 100 and ratio 1.

A short sequence. Three boxes of size 20 by 40 move at constant velocity for 30 frames, and the detections are the true corners plus Gaussian noise of 1 pixel. Two of the boxes pass each other, with an IoU of at most 1/71/7 between them. The detector misses object 0 in frame 12, and a false box appears in frame 20 only. SORT gives each object one identity for the whole sequence. The track of object 0 survives the missed frame, but its run of updates restarts, so it is not reported in frames 12, 13 and 14 and comes back with the same identity in frame 15. The false box starts a track that is never reported and is deleted two frames later. The mean error of the reported box centers is 0.65 pixels.

Correctness

SORT is a heuristic tracker, and nothing guarantees that it keeps identities on real video. The proved parts are about one frame and about ideal input. The proofs are in proofs/correctness.md.

  • Theorem: the assignment. Line L3 returns an assignment of largest total IoU among all one-to-one assignments of size min⁡(n,m)\min(n, m). After line L4, the kept pairs form a partial matching in which every pair has IoU at least IoUmin⁡\mathrm{IoU}_{\min}.
  • Theorem: separated objects keep their identities. Suppose that in every frame each object is detected, the predicted box of its track has IoU at least IoUmin⁡>0\mathrm{IoU}_{\min} > 0 with its own detection, and IoU 0 with every other detection. Then every optimal assignment of line L3 pairs each track with its own object, and no identity switch occurs.
  • Theorem: the filter. Under the linear Gaussian model, each prediction and update is the Kalman recursion, which gives the mean and covariance of the state given the measurements so far. The update in Joseph form keeps PP symmetric and positive definite.
  • Not proved. With overlapping objects, missed detections or false boxes, the outcome depends on the detector and on the tuned thresholds. The Kalman model of a box is also not a true model of a person's motion.
Proof: Why the SORT assignment is optimal, why separated objects keep their identities, and why the Joseph form keeps the covariance positive definitefull

Notation as on the page. In one frame there are nn tracks and mm detections, and cij=IoU(b^i,dj)∈[0,1]c_{ij} = \mathrm{IoU}(\hat b_i, d_j) \in [0, 1] is the IoU between the predicted box of track ii and detection jj. An assignment is a set of pairs (i,j)(i, j) in which no track and no detection appears twice. It is full if it has min⁡(n,m)\min(n, m) pairs. Line L3 asks for a full assignment of largest total ∑cij\sum c_{ij}, which is the same as a full assignment of smallest total for the cost −cij-c_{ij}. The claims are about the algorithm, not about real video.

Claim 1: the assignment of line L3 is optimal

Let r≤cr \le c (else transpose the matrix) and let aij=−cija_{ij} = -c_{ij} be the r×cr \times c cost matrix. The solver of the implementation is the Hungarian method with potentials u1,…,uru_1, \ldots, u_r and v1,…,vcv_1, \ldots, v_c. When it stops, it has a full assignment σ\sigma (every row ii has a column σ(i)\sigma(i)) and potentials with

  1. ui+vj≤aiju_i + v_j \le a_{ij} for all i,ji, j,
  2. ui+vσ(i)=aiσ(i)u_i + v_{\sigma(i)} = a_{i \sigma(i)} for every row ii,
  3. vj≤0v_j \le 0 for every column jj, and vj=0v_j = 0 for every column not in σ\sigma.

Then σ\sigma has the smallest total cost of all full assignments.

Proof of the three facts. Facts 1 and 2 are the invariants of the Hungarian method: each change of potentials by δ\delta adds δ\delta to uu on the rows of the search tree and subtracts δ\delta from vv on its columns, so the reduced costs aij−ui−vja_{ij} - u_i - v_j inside the tree do not change and outside it they drop by at most their smallest value, which keeps them nonnegative. An augmenting path only uses pairs with reduced cost 0. For fact 3, vjv_j only decreases, and only for columns in the search tree. A column joins the tree only when it is matched, because the search stops at the first free column that it reaches, before the next change of potentials. A matched column stays matched. So a column that is free at the end was never in a tree and has vj=0v_j = 0.

Proof of optimality. Let τ\tau be any full assignment, so each row ii has a column τ(i)\tau(i) and the columns are distinct. By fact 1, ∑iaiτ(i)≥∑iui+∑ivτ(i)\sum_i a_{i \tau(i)} \ge \sum_i u_i + \sum_i v_{\tau(i)}. Since every vj≤0v_j \le 0, adding the other columns can only lower the sum, so ∑ivτ(i)≥∑j=1cvj\sum_i v_{\tau(i)} \ge \sum_{j=1}^{c} v_j. By fact 3 the right side equals ∑ivσ(i)\sum_i v_{\sigma(i)}. By fact 2, ∑iui+∑ivσ(i)=∑iaiσ(i)\sum_i u_i + \sum_i v_{\sigma(i)} = \sum_i a_{i \sigma(i)}. So ∑iaiτ(i)≥∑iaiσ(i)\sum_i a_{i \tau(i)} \ge \sum_i a_{i \sigma(i)}. □\square

The tests compare the solver with a search over all full assignments on 200 random matrices of size up to 5×55 \times 5.

Claim 2: the kept pairs

After line L4, the kept pairs form an assignment in which every pair has cij≥IoUmin⁡c_{ij} \ge \mathrm{IoU}_{\min}. Every track and every detection is either in one kept pair or in none.

Proof. The kept pairs are a subset of σ\sigma, and a subset of an assignment is an assignment. The filter keeps a pair only if cij≥IoUmin⁡c_{ij} \ge \mathrm{IoU}_{\min}. □\square

Claim 3: filtering after the assignment is not the same as gating first

The kept set of line L4 need not be an assignment of largest total among assignments that use only pairs with cij≥IoUmin⁡c_{ij} \ge \mathrm{IoU}_{\min}, and it can have fewer pairs.

Example. Take two tracks A,BA, B, two detections a,ba, b, IoUmin⁡=0.3\mathrm{IoU}_{\min} = 0.3, and cAa=0.9c_{Aa} = 0.9, cAb=0.5c_{Ab} = 0.5, cBa=0.5c_{Ba} = 0.5, cBb=0.25c_{Bb} = 0.25. The two full assignments have totals 0.9+0.25=1.150.9 + 0.25 = 1.15 and 0.5+0.5=1.00.5 + 0.5 = 1.0, so line L3 takes {(A,a),(B,b)}\{(A, a), (B, b)\}, and line L4 drops (B,b)(B, b). One pair is kept, with total 0.9. If the pair (B,b)(B, b) is forbidden before the assignment, the best assignment is {(A,b),(B,a)}\{(A, b), (B, a)\}, with two pairs and total 1.0. □\square

The released code of the paper filters after the assignment, and so does the implementation of this page. The difference is a design choice, not an error, but the two rules give different tracks.

Claim 4: separated objects keep their identities

Suppose that in one frame, tracks 1,…,q1, \ldots, q and detections 1,…,q1, \ldots, q satisfy ckk≥IoUmin⁡>0c_{kk} \ge \mathrm{IoU}_{\min} > 0 for k≤qk \le q, and every other entry of the IoU matrix is 0 (this includes the rows of other tracks and the columns of other detections). Then every assignment of largest total contains the pairs (k,k)(k, k) for all k≤qk \le q, and line L4 keeps them.

Proof. Since q≤min⁡(n,m)q \le \min(n, m), the pairs (1,1),…,(q,q)(1, 1), \ldots, (q, q) extend to a full assignment by adding any pairs between the other rows and columns, and its total is ∑k≤qckk\sum_{k \le q} c_{kk}, because all the added pairs have IoU 0. So the optimum is at least ∑k≤qckk\sum_{k \le q} c_{kk}. In any assignment, the only pairs with a nonzero entry are pairs (k,k)(k, k), so its total is the sum of ckkc_{kk} over the pairs (k,k)(k, k) it contains. If it misses some (k,k)(k, k), its total is at most ∑k≤qckk−ckk<∑k≤qckk\sum_{k \le q} c_{kk} - c_{kk} < \sum_{k \le q} c_{kk}, because ckk>0c_{kk} > 0. So every optimal assignment contains all of them. Each has ckk≥IoUmin⁡c_{kk} \ge \mathrm{IoU}_{\min}, so line L4 keeps each one. □\square

Corollary. If the hypothesis holds in every frame, with track kk created from the first detection of object kk, then by induction over the frames track kk is updated only with detections of object kk, and no identity switch occurs. The hypothesis is about the predicted boxes, so it is a condition on the input and on the filter, not a fact that SORT ensures. When two objects overlap, the IoU matrix has nonzero entries off the diagonal, and the claim says nothing.

Claim 5: the counters

With the code of the page, a track that is not matched in kk frames in a row has a count of frames since its last update equal to kk after line L7 of the kk-th of these frames, if it is still there. It is deleted in the first frame where k>max_agek > \texttt{max\_age}. With max_age=1\texttt{max\_age} = 1 it survives one missed frame and is deleted in the second.

Proof. Line L1 adds 1 to the count of every track, and line L5 sets it to 0 for each matched track. A track not matched in kk frames in a row therefore has count kk after line L5 of the kk-th frame. Line L7 deletes it when the count exceeds max_age\texttt{max\_age}, which first happens at k=max_age+1k = \texttt{max\_age} + 1. □\square

Claim 6: the Kalman steps

For the linear model xt+1=Fxt+wtx_{t+1} = F x_t + w_t, zt=Hxt+etz_t = H x_t + e_t, with Gaussian noise of covariances QQ and RR, independent of each other and of the start, the prediction x^←Fx^\hat x \leftarrow F \hat x, P←FPFT+QP \leftarrow F P F^{\mathsf T} + Q and the update with gain K=PHT(HPHT+R)−1K = P H^{\mathsf T} (H P H^{\mathsf T} + R)^{-1} give the mean and covariance of the state given all measurements so far. This is the Kalman filter; the proof is on the page Kalman filter. Two facts about the implementation remain.

(a) If PP is positive definite and QQ is positive definite, then FPFT+QF P F^{\mathsf T} + Q is positive definite. Indeed yTFPFTy≥0y^{\mathsf T} F P F^{\mathsf T} y \ge 0 and yTQy>0y^{\mathsf T} Q y > 0 for y≠0y \ne 0. Here Q=diag(1,1,1,1,0.01,0.01,10−4)Q = \mathrm{diag}(1, 1, 1, 1, 0.01, 0.01, 10^{-4}) is positive definite.

(b) The Joseph form P′=(I−KH)P(I−KH)T+KRKTP' = (I - K H) P (I - K H)^{\mathsf T} + K R K^{\mathsf T} is symmetric for every KK, and positive definite if PP and RR are. Symmetry holds because both terms have the form MAMTM A M^{\mathsf T} with AA symmetric. For y≠0y \ne 0, if KTy≠0K^{\mathsf T} y \ne 0 then yTKRKTy>0y^{\mathsf T} K R K^{\mathsf T} y > 0. If KTy=0K^{\mathsf T} y = 0, then (I−KH)Ty=y−HTKTy=y(I - K H)^{\mathsf T} y = y - H^{\mathsf T} K^{\mathsf T} y = y, so the first term gives yTPy>0y^{\mathsf T} P y > 0. In both cases yTP′y>0y^{\mathsf T} P' y > 0, since both terms are positive semidefinite. □\square

For the optimal gain the Joseph form equals the short form (I−KH)P(I - K H) P, but in floating point it keeps symmetry and positive definiteness, which the short form can lose. The model of a box as a constant velocity point with constant aspect ratio is a heuristic, so the "mean given the measurements" of Claim 6 is exact only for data that follow the model.

Complexity

Let nn be the number of tracks and mm the number of detections in a frame, in the real RAM model. The IoU matrix costs O(nm)O(n m). The Hungarian algorithm with potentials solves an r×cr \times c assignment with r≤cr \le c in O(r2c)O(r^2 c) time, and r2c≤nm(n+m)r^2 c \le n m (n + m). Each Kalman step works on a state of fixed size 7, so it costs O(1)O(1), and O(n+m)O(n + m) for all tracks. One frame costs O(nm(n+m))O(n m (n + m)) time and O(nm)O(n m) extra space, and a video of NN frames costs O(Nnm(n+m))O(N n m (n + m)) with nn and mm the largest counts over all frames. The detector is not part of this cost. The paper reports 260 frames per second for the tracking part on one CPU core, which is a measurement on its hardware and data, not a bound.

Properties

  • Online. The output of a frame never changes later.
  • One hypothesis. SORT keeps a single assignment per frame, like global nearest neighbor association.
  • No appearance. Two objects that swap places while one of them is not detected get swapped identities, since IoU sees only geometry.
  • Short memory. With max_age = 1, a track dies after two missed frames, and the object gets a new identity when it comes back.
  • Deterministic. The output depends only on the detections, up to ties in the assignment.

Variants and improvements

  • Deep SORT. Deep SORT adds an appearance embedding per detection, a Mahalanobis gate and a matching cascade, and keeps tracks for 30 frames.
  • ByteTrack. ByteTrack also matches the low-score detections, in a second round, so that occluded objects keep their tracks.
  • Gating before the assignment. Set the score of pairs with IoU below the threshold to a forbidden value before line L3, instead of removing them after. The two can give different matchings, as the pitfalls below show.
  • Other scores. Generalized IoU, center distance, or the Mahalanobis distance of track gating can replace IoU.
  • Later trackers of the same family. OC-SORT changes the Kalman update after an occlusion, and BoT-SORT adds camera motion compensation and appearance. Their gains are benchmark results.

When to use it

Use SORT when the detector is good, the frame rate is high so that boxes of one object overlap from frame to frame, and speed matters more than identity through long occlusions. It is a strong baseline and a common first step before an appearance model is added. Do not use it alone when objects are often hidden for several frames, or when the camera moves fast, since then the predicted box no longer overlaps the detection.

Pitfalls

  • Low frame rate or fast motion. If an object moves more than its width between frames, the IoU with its own detection is 0, and the track is lost. A center distance or a Mahalanobis gate does better there.
  • Filtering after the assignment. Because line L3 maximizes the total IoU over all pairs, a pair below the threshold can take part in the optimum and be removed in line L4, while another assignment would have kept more pairs above the threshold. The released code accepts this.
  • Box conventions. Mixing (x,y,w,h)(x, y, w, h) with (x1,y1,x2,y2)(x_1, y_1, x_2, y_2), or adding 1 to widths in one place only, gives wrong IoU values without an error.
  • Negative area. A box that shrinks fast can predict a negative area. Clamp the area velocity, as the released code does.
  • Benchmark numbers taken as properties. The MOTA of 33.4 on the 2015 MOT benchmark that the paper reports used Faster R-CNN detections. With other detections the score changes much, as the paper itself shows.

Implementations

The Python file follows the released code: the same state, the same noise matrices, the IoU threshold 0.3, max_age = 1 and min_hits = 3. The Hungarian algorithm and the small matrix routines are in the same file. The tests compare the assignment with brute force over all assignments, check the IoU values 1/71/7 and 1/31/3 exactly, check the page example, and run the 30-frame sequence above.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

sort_tracker.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sort-tracker/. The authors are listed in prov/2C1PFP.jsonl.
"""SORT: simple online and realtime tracking (Bewley et al. 2016).

Each track is a constant velocity Kalman filter on the state
(u, v, s, r, du, dv, ds): the box center (u, v), the area s, the aspect ratio
r = width / height (taken as constant), and the velocities of u, v and s.
In each frame the tracks are predicted, the IoU between every predicted box
and every detection is computed, and the Hungarian algorithm finds the
assignment of largest total IoU. Pairs with IoU below iou_min are dropped.
Matched tracks are corrected, unmatched detections start new tracks, and
tracks that miss more than max_age frames in a row are deleted.

Boxes are (x1, y1, x2, y2) in continuous image coordinates with x1 < x2 and
y1 < y2; the area is (x2 - x1)(y2 - y1), with no +1 term. The noise matrices
follow the released code of the paper. Matrices are lists of rows.
Cost of one frame with n tracks and m detections: O(n m) for the IoU matrix,
O(min(n, m)^2 max(n, m)) for the assignment, and O(n) Kalman steps of fixed size.
"""

import math


# ---------------------------------------------------------------- small linear algebra


def mat_mul(a, b):
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def transpose(a):
    return [list(r) for r in zip(*a)]


def mat_add(a, b):
    return [[x + y for x, y in zip(r, s)] for r, s in zip(a, b)]


def mat_sub(a, b):
    return [[x - y for x, y in zip(r, s)] for r, s in zip(a, b)]


def mat_vec(a, x):
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def eye(n):
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def diag(values):
    n = len(values)
    return [[float(values[i]) if i == j else 0.0 for j in range(n)] for i in range(n)]


def inverse(a):
    """Inverse of a small nonsingular matrix by Gauss-Jordan elimination with partial pivoting."""
    n = len(a)
    m = [list(map(float, r)) + [1.0 if i == j else 0.0 for j in range(n)] for i, r in enumerate(a)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[p][c]) < 1e-300:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        m[c] = [x / piv for x in m[c]]
        for r in range(n):
            if r != c and m[r][c] != 0.0:
                f = m[r][c]
                m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    return [r[n:] for r in m]


# ---------------------------------------------------------------- boxes


def iou(a, b):
    """Intersection over union of two boxes (x1, y1, x2, y2). Exact on Fractions."""
    w = min(a[2], b[2]) - max(a[0], b[0])
    h = min(a[3], b[3]) - max(a[1], b[1])
    if w <= 0 or h <= 0:
        return 0 * w
    inter = w * h
    union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    return inter / union


def box_to_z(box):
    """(x1, y1, x2, y2) to the measurement (u, v, s, r)."""
    w = box[2] - box[0]
    h = box[3] - box[1]
    return [box[0] + w / 2.0, box[1] + h / 2.0, float(w * h), w / float(h)]


def z_to_box(z):
    """(u, v, s, r) to (x1, y1, x2, y2); s and r must be positive."""
    w = math.sqrt(z[2] * z[3])
    h = z[2] / w
    return (z[0] - w / 2.0, z[1] - h / 2.0, z[0] + w / 2.0, z[1] + h / 2.0)


# ---------------------------------------------------------------- assignment


def hungarian_min(cost):
    """Minimum cost assignment for a rectangular matrix of finite costs.

    Returns the sorted list of pairs (row, column); its size is min(rows, columns).
    The potentials method takes O(r^2 c) time for r <= c.
    """
    r = len(cost)
    if r == 0 or len(cost[0]) == 0:
        return []
    c = len(cost[0])
    flip = r > c
    if flip:
        cost = transpose(cost)
        r, c = c, r
    inf = float("inf")
    u, v = [0.0] * (r + 1), [0.0] * (c + 1)
    p, way = [0] * (c + 1), [0] * (c + 1)
    for i in range(1, r + 1):
        p[0], j0 = i, 0
        minv, used = [inf] * (c + 1), [False] * (c + 1)
        while True:
            used[j0] = True
            i0, delta, j1 = p[j0], inf, 0
            for j in range(1, c + 1):
                if not used[j]:
                    cur = cost[i0 - 1][j - 1] - u[i0] - v[j]
                    if cur < minv[j]:
                        minv[j], way[j] = cur, j0
                    if minv[j] < delta:
                        delta, j1 = minv[j], j
            for j in range(c + 1):
                if used[j]:
                    u[p[j]] += delta
                    v[j] -= delta
                else:
                    minv[j] -= delta
            j0 = j1
            if p[j0] == 0:
                break
        while True:
            j1 = way[j0]
            p[j0] = p[j1]
            j0 = j1
            if j0 == 0:
                break
    pairs = [(p[j] - 1, j - 1) for j in range(1, c + 1) if p[j] != 0]
    if flip:
        pairs = [(b, a) for a, b in pairs]
    return sorted(pairs)


def associate(pred_boxes, det_boxes, iou_min):
    """Lines L2 to L4: IoU matrix, assignment of largest total IoU, then the IoU_min filter.

    Returns (matches, unmatched_tracks, unmatched_detections, iou_matrix).
    """
    n, m = len(pred_boxes), len(det_boxes)
    ious = [[iou(p, d) for d in det_boxes] for p in pred_boxes]  # @line L2
    pairs = hungarian_min([[-x for x in row] for row in ious]) if n and m else []  # @line L3
    matches = [(i, j) for i, j in pairs if ious[i][j] >= iou_min]  # @line L4
    mt = {i for i, _ in matches}
    md = {j for _, j in matches}
    return matches, [i for i in range(n) if i not in mt], [j for j in range(m) if j not in md], ious


# ---------------------------------------------------------------- Kalman filter of one track

F7 = [[1.0 if (i == j or j == i + 4) else 0.0 for j in range(7)] for i in range(7)]
H7 = [[1.0 if i == j else 0.0 for j in range(7)] for i in range(4)]
Q7 = diag([1, 1, 1, 1, 0.01, 0.01, 0.0001])
R4 = diag([1, 1, 10, 10])
P0 = diag([10, 10, 10, 10, 10000, 10000, 10000])


class Track:
    """One SORT track: a Kalman filter on (u, v, s, r, du, dv, ds) and its counters."""

    def __init__(self, box, track_id):
        self.x = box_to_z(box) + [0.0, 0.0, 0.0]  # zero velocity
        self.P = [row[:] for row in P0]  # large velocity variance
        self.id = track_id
        self.time_since_update = 0
        self.hits = 0
        self.hit_streak = 0
        self.age = 0

    def predict(self):
        if self.x[2] + self.x[6] <= 0:  # the area must stay positive
            self.x[6] = 0.0
        self.x = mat_vec(F7, self.x)
        self.P = mat_add(mat_mul(mat_mul(F7, self.P), transpose(F7)), Q7)
        self.age += 1
        if self.time_since_update > 0:
            self.hit_streak = 0
        self.time_since_update += 1
        return self.box()

    def update(self, box):
        z = box_to_z(box)
        y = [a - b for a, b in zip(z, mat_vec(H7, self.x))]
        ph = mat_mul(self.P, transpose(H7))
        s = mat_add(mat_mul(H7, ph), R4)
        k = mat_mul(ph, inverse(s))
        self.x = [a + b for a, b in zip(self.x, mat_vec(k, y))]
        ikh = mat_sub(eye(7), mat_mul(k, H7))
        # Joseph form keeps P symmetric and positive definite.
        self.P = mat_add(mat_mul(mat_mul(ikh, self.P), transpose(ikh)), mat_mul(mat_mul(k, R4), transpose(k)))
        self.time_since_update = 0
        self.hits += 1
        self.hit_streak += 1

    def box(self):
        if self.x[2] <= 0 or self.x[3] <= 0:
            return None
        return z_to_box(self.x)


class SortTracker:
    """The SORT tracker. Call step(detections) once per frame."""

    def __init__(self, iou_min=0.3, max_age=1, min_hits=3):
        self.iou_min = iou_min
        self.max_age = max_age
        self.min_hits = min_hits
        self.tracks = []
        self.frame_count = 0
        self.next_id = 1

    def step(self, detections):
        """detections: list of boxes. Returns a list of (track_id, box) for this frame."""
        self.frame_count += 1
        alive = []
        for t in self.tracks:  # @line L1
            if t.predict() is not None:
                alive.append(t)
        self.tracks = alive
        preds = [t.box() for t in self.tracks]
        matches, _, unmatched_dets, _ = associate(preds, detections, self.iou_min)
        for i, j in matches:  # @line L5
            self.tracks[i].update(detections[j])
        for j in unmatched_dets:  # @line L6
            self.tracks.append(Track(detections[j], self.next_id))
            self.next_id += 1
        self.tracks = [t for t in self.tracks if t.time_since_update <= self.max_age]  # @line L7
        out = []
        for t in self.tracks:  # @line L8
            if t.time_since_update == 0 and (t.hit_streak >= self.min_hits or self.frame_count <= self.min_hits):
                out.append((t.id, t.box()))
        return out
test_sort_tracker.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sort-tracker/. The authors are listed in prov/2C1PFP.jsonl.

import itertools
import math
import random
from fractions import Fraction

from sort_tracker import (
    SortTracker,
    Track,
    associate,
    box_to_z,
    hungarian_min,
    iou,
    z_to_box,
)


def brute_max_sum(ious):
    """Largest total IoU over all assignments of size min(n, m)."""
    n, m = len(ious), len(ious[0])
    best = -1.0
    if n <= m:
        for cols in itertools.permutations(range(m), n):
            best = max(best, sum(ious[i][c] for i, c in enumerate(cols)))
    else:
        for rows in itertools.permutations(range(n), m):
            best = max(best, sum(ious[r][j] for j, r in enumerate(rows)))
    return best


def test_iou_check_values():
    assert iou(tuple(map(Fraction, (0, 0, 2, 2))), tuple(map(Fraction, (1, 1, 3, 3)))) == Fraction(1, 7)
    assert iou(tuple(map(Fraction, (0, 0, 10, 10))), tuple(map(Fraction, (5, 0, 15, 10)))) == Fraction(1, 3)
    assert iou((0, 0, 1, 1), (2, 2, 3, 3)) == 0


def test_state_round_trip():
    box = (4.0, 0.0, 14.0, 10.0)
    assert box_to_z(box) == [9.0, 5.0, 100.0, 1.0]
    rng = random.Random(1)
    for _ in range(50):
        x1, y1 = rng.uniform(-50, 50), rng.uniform(-50, 50)
        b = (x1, y1, x1 + rng.uniform(1, 40), y1 + rng.uniform(1, 40))
        assert all(abs(p - q) < 1e-9 for p, q in zip(z_to_box(box_to_z(b)), b))


def test_hungarian_against_brute_force():
    rng = random.Random(7)
    for _ in range(200):
        n, m = rng.randint(1, 5), rng.randint(1, 5)
        c = [[rng.random() for _ in range(m)] for _ in range(n)]
        pairs = hungarian_min([[-x for x in row] for row in c])
        assert len(pairs) == min(n, m)
        assert len({i for i, _ in pairs}) == len(pairs) == len({j for _, j in pairs})
        assert abs(sum(c[i][j] for i, j in pairs) - brute_max_sum(c)) < 1e-9


def test_page_example_global_beats_greedy():
    preds = [(0, 0, 10, 10), (6, 0, 16, 10)]
    dets = [(4, 0, 14, 10), (9, 0, 19, 10), (40, 40, 50, 50)]
    fr = [tuple(map(Fraction, b)) for b in preds]
    fd = [tuple(map(Fraction, b)) for b in dets]
    assert [[iou(p, d) for d in fd] for p in fr] == [
        [Fraction(3, 7), Fraction(1, 19), 0],
        [Fraction(2, 3), Fraction(7, 13), 0],
    ]
    matches, um_t, um_d, _ = associate(preds, dets, 0.3)
    assert matches == [(0, 0), (1, 1)] and um_t == [] and um_d == [2]
    # The greedy rule takes the largest IoU first, (B, d1), and then A is left
    # with d2 at IoU 1/19 < 0.3, so A loses its detection.
    assert max((iou(p, d), i, j) for i, p in enumerate(preds) for j, d in enumerate(dets))[1:] == (1, 0)


def test_iou_min_filter_keeps_only_strong_pairs():
    rng = random.Random(3)
    for _ in range(100):
        preds, dets = [], []
        for _ in range(rng.randint(1, 4)):
            x, y = rng.uniform(0, 60), rng.uniform(0, 60)
            preds.append((x, y, x + 10, y + 10))
        for _ in range(rng.randint(1, 4)):
            x, y = rng.uniform(0, 60), rng.uniform(0, 60)
            dets.append((x, y, x + 10, y + 10))
        matches, um_t, um_d, ious = associate(preds, dets, 0.3)
        assert all(ious[i][j] >= 0.3 for i, j in matches)
        assert sorted([i for i, _ in matches] + um_t) == list(range(len(preds)))
        assert sorted([j for _, j in matches] + um_d) == list(range(len(dets)))


def test_filter_after_assignment_differs_from_gating_first():
    # Claim 3 of the proof: tracks A, B and detections a, b with IoU_min = 0.3.
    c = [[0.9, 0.5], [0.5, 0.25]]
    pairs = hungarian_min([[-x for x in row] for row in c])
    assert pairs == [(0, 0), (1, 1)]
    kept = [(i, j) for i, j in pairs if c[i][j] >= 0.3]
    assert kept == [(0, 0)]
    big = 1e6  # forbid the weak pair before the assignment
    gated = hungarian_min([[-x if x >= 0.3 else big for x in row] for row in c])
    assert [(i, j) for i, j in gated if c[i][j] >= 0.3] == [(0, 1), (1, 0)]


def test_kalman_constant_velocity_converges():
    t = Track((0.0, 0.0, 10.0, 20.0), 1)
    for k in range(1, 40):
        t.predict()
        t.update((3.0 * k, 2.0 * k, 3.0 * k + 10.0, 2.0 * k + 20.0))
    assert abs(t.x[4] - 3.0) < 1e-2 and abs(t.x[5] - 2.0) < 1e-2 and abs(t.x[6]) < 1e-2
    p = t.predict()
    assert all(abs(a - b) < 0.05 for a, b in zip(p, (120.0, 80.0, 130.0, 100.0)))
    # P stays symmetric
    assert all(abs(t.P[i][j] - t.P[j][i]) < 1e-9 for i in range(7) for j in range(7))


def make_sequence(seed):
    """Three boxes with constant velocity, 30 frames, noise of 1 pixel on the corners.

    Object 0 is missed in frame 12. A false box appears in frame 20 only.
    Objects 0 and 1 pass each other; their boxes overlap with IoU at most 1/7.
    """
    rng = random.Random(seed)
    starts = [(10.0, 20.0, 3.0, 0.0), (150.0, 50.0, -3.0, 0.0), (80.0, 0.0, 1.0, 0.5)]
    frames, truth = [], []
    for f in range(30):
        dets, gt = [], []
        for k, (x, y, vx, vy) in enumerate(starts):
            b = (x + vx * f, y + vy * f, x + vx * f + 20.0, y + vy * f + 40.0)
            gt.append(b)
            if k == 0 and f == 12:
                continue
            dets.append(tuple(c + rng.gauss(0.0, 1.0) for c in b))
        if f == 20:
            dets.append((300.0, 300.0, 320.0, 340.0))
        rng.shuffle(dets)
        frames.append(dets)
        truth.append(gt)
    return frames, truth


def test_sequence_keeps_identities():
    frames, truth = make_sequence(11)
    tr = SortTracker()
    ids = {0: set(), 1: set(), 2: set()}
    errors = []
    for f, dets in enumerate(frames):
        out = tr.step(dets)
        for tid, box in out:
            best = max(range(3), key=lambda k: iou(box, truth[f][k]))
            assert iou(box, truth[f][best]) > 0.5  # no output on the false box
            ids[best].add(tid)
            cu, cv = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
            g = truth[f][best]
            errors.append(math.hypot(cu - (g[0] + g[2]) / 2, cv - (g[1] + g[3]) / 2))
    assert all(len(s) == 1 for s in ids.values())  # one identity per object, no switch
    assert len(set().union(*ids.values())) == 3
    assert sum(errors) / len(errors) < 1.5
    # the track of object 0 survives the missed frame 12 (max_age = 1)
    assert tr.next_id == 5  # three objects and the false box of frame 20


def test_track_deleted_after_two_misses():
    tr = SortTracker()
    box = (0.0, 0.0, 10.0, 10.0)
    for _ in range(4):
        tr.step([box])
    assert len(tr.tracks) == 1
    tr.step([])
    assert len(tr.tracks) == 1  # one miss is allowed
    tr.step([])
    assert tr.tracks == []

History

Tracking by detection with a Kalman filter per target and an optimal assignment per frame comes from radar tracking, where it is the global nearest neighbor method. In 2016, Bewley, Ge, Ott, Ramos and Upcroft showed with SORT that this simple scheme, with IoU as the score and detections from Faster R-CNN, was close to the best online trackers of the MOT benchmark of 2015, and much faster. They also showed that a better detector improved the tracking score more than a more complex tracker. In 2017 Wojke, Bewley and Paulus added an appearance metric and called the result Deep SORT. Many later trackers keep the SORT structure and change the score, the filter or the track rules.

References

  1. Alex Bewley, Zongyuan Ge, Lionel Ott, Fabio Ramos and Ben Upcroft, Simple online and realtime tracking, IEEE International Conference on Image Processing (ICIP), 2016, 3464-3468 (arXiv:1602.00763), Section 3.2 (the state and the constant velocity model), Section 3.3 (the IoU assignment by the Hungarian algorithm), Section 3.4 (track creation and deletion), Section 4 (the setup and the MOT benchmark results)
  2. R. E. Kalman, A new approach to linear filtering and prediction problems, Journal of Basic Engineering 82(1), 1960, 35-45, the recursive linear estimator used for each track
  3. Harold W. Kuhn, The Hungarian method for the assignment problem, Naval Research Logistics Quarterly 2(1-2), 1955, 83-97, the whole paper (the assignment step)
  4. Nicolai Wojke, Alex Bewley and Dietrich Paulus, Simple online and realtime tracking with a deep association metric, ICIP 2017, 3645-3649 (arXiv:1703.07402), Section 1 and Section 3 (the identity switches of SORT under occlusion, which motivate Deep SORT)
  5. Laura Leal-Taixe, Anton Milan, Ian Reid, Stefan Roth and Konrad Schindler, MOTChallenge 2015: towards a benchmark for multi-target tracking, arXiv:1504.01942, 2015, the benchmark and the metrics on which SORT reports its results

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example