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.
- Solves
- Multi-object tracking
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativeonline
- Evidence
- Proof sketchCode in 1 languages
- 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 comes with a list of detections , each a box in continuous image coordinates with and , and area , with no term. The output of frame is a list of pairs (identity, box). The tracker is online: the output of frame depends only on frames to . 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
where is the box center, the area, the aspect ratio, and the dots are velocities in pixels per frame (and pixels squared per frame for ). The ratio has no velocity: SORT takes it as constant. A box maps to the measurement , and back by and . The motion is , with the identity plus ones that add to . The measurement matrix picks the first four entries.
The algorithm
SORT-STEP(the tracks, the detections d_1..d_m, IoU_min, max_age, min_hits)- 1
for each track i: Kalman predict x_i and P_i; drop the track if its box has s ≤ 0 - 2
for each track i and each detection j: c_ij ← IoU(box of x_i, d_j) - 3
σ ← the assignment of largest total Σ c_iσ(i), by the Hungarian algorithm - 4
keep only the pairs (i, σ(i)) with c_iσ(i) ≥ IoU_min - 5
for each kept pair (i, j): Kalman update of track i with z(d_j) - 6
for each detection j in no kept pair: a new track with x = (z(d_j), 0, 0, 0) - 7
delete each track whose time since its last update exceeds max_age - 8
output the tracks updated in this frame that have at least min_hits updates in a row
The assignment of line L3 has size 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 .
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 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 for the measurement, for the motion, and for a new track. If the predicted area would be negative, the code sets to 0 first.
Example
One frame. Two tracks predict the boxes and . The detector gives , and . All boxes are 10 by 10, so each union is minus the overlap. The IoU matrix is
| 0 | |||
| 0 |
The assignment , has total . The other choice that uses and , , , has total . The Hungarian algorithm returns the first one. Both pairs pass , so both tracks are updated, and starts a new track. A greedy rule that takes the largest IoU first would pair with , and then could only have at IoU , below the threshold. Track would miss its detection, and would start a false new track.
For the box the measurement is : center , 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 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 . After line L4, the kept pairs form a partial matching in which every pair has IoU at least .
- 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 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 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 tracks and detections, and is the IoU between the predicted box of track and detection . An assignment is a set of pairs in which no track and no detection appears twice. It is full if it has pairs. Line L3 asks for a full assignment of largest total , which is the same as a full assignment of smallest total for the cost . The claims are about the algorithm, not about real video.
Claim 1: the assignment of line L3 is optimal
Let (else transpose the matrix) and let be the cost matrix. The solver of the implementation is the Hungarian method with potentials and . When it stops, it has a full assignment (every row has a column ) and potentials with
- for all ,
- for every row ,
- for every column , and for every column not in .
Then 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 adds to on the rows of the search tree and subtracts from on its columns, so the reduced costs 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, 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 .
Proof of optimality. Let be any full assignment, so each row has a column and the columns are distinct. By fact 1, . Since every , adding the other columns can only lower the sum, so . By fact 3 the right side equals . By fact 2, . So .
The tests compare the solver with a search over all full assignments on 200 random matrices of size up to .
Claim 2: the kept pairs
After line L4, the kept pairs form an assignment in which every pair has . Every track and every detection is either in one kept pair or in none.
Proof. The kept pairs are a subset of , and a subset of an assignment is an assignment. The filter keeps a pair only if .
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 , and it can have fewer pairs.
Example. Take two tracks , two detections , , and , , , . The two full assignments have totals and , so line L3 takes , and line L4 drops . One pair is kept, with total 0.9. If the pair is forbidden before the assignment, the best assignment is , with two pairs and total 1.0.
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 and detections satisfy for , 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 for all , and line L4 keeps them.
Proof. Since , the pairs extend to a full assignment by adding any pairs between the other rows and columns, and its total is , because all the added pairs have IoU 0. So the optimum is at least . In any assignment, the only pairs with a nonzero entry are pairs , so its total is the sum of over the pairs it contains. If it misses some , its total is at most , because . So every optimal assignment contains all of them. Each has , so line L4 keeps each one.
Corollary. If the hypothesis holds in every frame, with track created from the first detection of object , then by induction over the frames track is updated only with detections of object , 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 frames in a row has a count of frames since its last update equal to after line L7 of the -th of these frames, if it is still there. It is deleted in the first frame where . With 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 frames in a row therefore has count after line L5 of the -th frame. Line L7 deletes it when the count exceeds , which first happens at .
Claim 6: the Kalman steps
For the linear model , , with Gaussian noise of covariances and , independent of each other and of the start, the prediction , and the update with gain 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 is positive definite and is positive definite, then is positive definite. Indeed and for . Here is positive definite.
(b) The Joseph form is symmetric for every , and positive definite if and are. Symmetry holds because both terms have the form with symmetric. For , if then . If , then , so the first term gives . In both cases , since both terms are positive semidefinite.
For the optimal gain the Joseph form equals the short form , 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 be the number of tracks and the number of detections in a frame, in the real RAM model. The IoU matrix costs . The Hungarian algorithm with potentials solves an assignment with in time, and . Each Kalman step works on a state of fixed size 7, so it costs , and for all tracks. One frame costs time and extra space, and a video of frames costs with and 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 with , 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 and 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.
# 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
- 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)
- 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2C1PFP Edit this page History Report an error Markdown