Algorithmadvanced
Network flow data association
Also called min-cost flow tracking, Zhang-Li-Nevatia tracking.
Link detections over a whole video as a min-cost flow, each unit of flow a track from source to sink through detection nodes, solved globally.
- Time
- O(K n (n + L)) worst · averageO(n (n + L)) best
- Space
- O(n + L) extra
- Where
- K = the number of tracks found; L = the number of allowed links between detections; n = the number of detections
- Model
- Real RAM
- Properties
- deterministicexactiterativenot localoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Li Zhang, Yuan Li, Ramakant Nevatia, 2008
Network flow data association links all detections of a video into tracks in one global optimization. Each detection becomes an edge of unit capacity in a directed graph with a source and a sink, and each track becomes one unit of flow from the source to the sink through the detections it contains. Costs on the edges say how likely each detection is to be real, how likely a track is to start or end there, and how likely two detections are to be the same object. A min-cost flow then gives the set of disjoint tracks of least total cost, which is the most probable set of tracks under the model. Zhang, Li and Nevatia introduced this formulation in 2008. It solves its model exactly in polynomial time, which is rare in data association, because it scores a track only by pairs of consecutive detections. It is a batch method for tracking-by-detection when the whole video, or a window of it, is known.
In plain words
Think of a set of stepping stones laid across a river over several days, where each day adds a row of stones, and some stones are fake. Each person who crosses steps on at most one stone per row, and no two people share a stone. Real stones pay a reward for stepping on them, long jumps cost effort, and entering or leaving the river costs a fee. We want to choose who crosses and by which stones so that the total reward minus the effort and the fees is as large as possible. Network flow finds this best choice for all people at once. It sends people one at a time along the best path, and a later person can push an earlier one onto a different stone if that helps the total.
The problem
The input is a set of detections, each with a frame number, a position and a confidence, and the costs of a model:
- for using detection , where is the probability that detection is false, so a confident detection has a negative cost;
- and for starting and ending a track, the negative logs of the probabilities of entry and exit;
- for detection following detection in a track, defined only for allowed links, from an earlier frame to a later one within a small gap.
A set of tracks is a set of disjoint chains of detections along allowed links. Its cost is the sum, over tracks, of the entry and exit costs, the detection costs and the link costs. The output is a set of tracks of least cost. Zhang, Li and Nevatia derive this cost as the negative log of the posterior probability of the set of tracks, under the assumptions that detections are independent given the tracks, that tracks do not overlap, and that a track is a Markov chain of its detections.
The flow network has the source , the sink , and two nodes and per detection, so . Its edges, all of capacity 1, are with cost , with cost , with cost , and with cost for each of the allowed links, so . The capacity 1 on makes each detection belong to at most one track.
The algorithm
NETWORK-FLOW-TRACKING(the detections, the costs c_i, c_en, c_ex, c_ij)- 1
build the nodes s, t, u_i, v_i and the edges u_i → v_i of cost c_i, all of capacity 1 - 2
add s → u_i of cost c_en, v_i → t of cost c_ex, and v_i → u_j of cost c_ij for each allowed link - 3
start with the zero flow - 4
repeat: find a shortest s-t path P in the residual graph, with Bellman-Ford - 5
if there is no path or cost(P) ≥ 0, stop - 6
push one unit of flow along P - 7
decompose the flow into s-t paths; each path is a track
This is the successive shortest path method for the min-cost flow problem, with one change: the amount of flow is not given. Each augmentation adds one track, and the method stops when the next track would not lower the cost. The residual graph has edges with negative cost, from the detection edges and from the reverse edges, so the code uses Bellman-Ford. Line L7 follows the edges with flow from the source. Each path visits the detections of one track in order of time, which is flow decomposition.
Example
A reroute by hand. Frame 0 has detections and , and frame 1 has and . Every detection costs , and entry and exit cost 1 each. The allowed links cost : 1.0, : 0.1, : 5.0, and : 0.2. A track of two detections costs .
- The first shortest path is , with cost . A greedy method would keep it and stop there, because and alone cost 0 each and is expensive: total .
- The second shortest path in the residual graph is . It takes for , goes back along the reverse of the link at cost , and gives to . Its cost is .
- The third search finds no path of negative cost, so the method stops with the tracks and and the total . That is .
A short sequence. In the code, three targets move to the right for 10 frames, 4 units apart, with position noise 0.2 and confidences between 0.8 and 0.95. Target 0 is missed in frame 4 and target 2 in frame 6, and three false alarms with confidence between 0.5 and 0.65 appear at random places. The 31 detections and 43 allowed links, with gaps of up to 2 frames, give three augmenting paths with costs , and , then stop. The three tracks are exactly the three targets, each bridging its missed frame, and the false alarms are left out.
Correctness
The full proof is in proofs/correctness.md. It shows these facts.
- Theorem: flows are track sets. The integral flows of value correspond to the sets of disjoint tracks, with the same cost.
- Theorem: each step is optimal. After augmentations, the flow has the least cost among all flows of value , and the residual graph has no cycle of negative cost, so Bellman-Ford is correct at every step.
- Theorem: convexity. The least cost of a flow of value is convex in , and the cost of the -th augmenting path is . So the first path of nonnegative cost marks the minimum of over all , and the returned tracks have the least cost over all track sets.
The optimality is for the model. The model scores a track only by its detections and its consecutive links, so it cannot express long-range terms such as a constant velocity over three detections or an appearance model that changes over the track. Adding such terms breaks the flow structure, and the problem then becomes NP-hard in general, as for multiple hypothesis tracking.
Proof: Why integral flows in the tracking network are sets of disjoint tracks, and why successive shortest paths stopped at the first nonnegative path give the track set of least costfull
Notation as on the page. The network has the nodes , , , for , and the edges (cost ), (cost ), (cost ) and for each allowed link (cost ), all of capacity 1. Links go from an earlier frame to a later one. A track is a sequence of detections with in which each is an allowed link. Its cost is . A track set is a set of tracks with no detection in common.
Claim 1: integral flows of value k are track sets of k tracks
Every track set with tracks gives an integral flow of value with the same cost, and every integral flow of value gives a track set with tracks and the same cost.
Proof. A track is the - path , and the cost of the path is the cost of the track. Disjoint tracks use disjoint edges and so disjoint edges overall, since every other edge touches one or of a single track. So the sum of the paths is a flow with values 0 or 1, of value , and its cost is the sum of the track costs.
Conversely, take an integral flow of value . All capacities are 1, so is 0 or 1 on each edge. The graph has no directed cycle: number the nodes by frame and put before , then every edge other than those at and goes from a node of a frame to a later node. By flow decomposition, a flow in a graph with no cycle is a sum of - paths, each with flow 1. Node has a single outgoing edge, of capacity 1, so at most one path passes through , and any path through continues to . Node has a single incoming edge, so a path that reaches came from . So each path has the form with allowed links in between, which is a track, and no two paths share a detection. The cost of is the sum of the path costs, which is the cost of the track set.
The empty track set is the zero flow, of cost 0. So the least cost over all track sets is , where is the least cost of an integral flow of value (and if no flow of value exists).
Claim 2: each augmentation keeps the flow optimal for its value
Let be the flow after augmentations. Then has the least cost among all flows of value , the residual graph has no cycle of negative cost, and is integral.
Proof. By induction on . The zero flow is the only flow of value 0, and has no cycle at all. Assume the claim for . A flow of value is of least cost if and only if its residual graph has no cycle of negative cost (the negative cycle optimality condition of the min-cost flow problem). Since has no negative cycle, Bellman-Ford computes correct shortest distances from , and the path it returns is a shortest - path. The successive shortest path theorem says that augmenting a flow of least cost for its value along a shortest path of the residual graph gives a flow of least cost for the new value. So is of least cost for value , and by the optimality condition has no negative cycle. All residual capacities are integers and the path carries one unit, so is integral.
Claim 3: the cost is convex in the number of tracks, so the stopping rule is right
Let be the cost of the shortest path found in step . Then , and is convex on the values for which a flow exists. So , and if the method stops before step because or no path exists, then .
Proof. By Claim 2, .
For convexity, let be the least cost of a flow of value with real flows allowed, the optimal value of a linear program whose constraints are , , with the node-edge incidence matrix and the vector with at and at . If and are optimal for the values and , then is feasible for the value , so , and is convex. The incidence matrix of a directed graph is totally unimodular, so for an integer value the linear program has an integral optimal solution (flow integrality), and . So restricted to the integers is convex: , which is .
If , then for every , so for all . For , , because every path that was augmented had negative cost. If no path exists, no flow of value exists, and by the same argument for the minimum is at .
Together, the three claims give the result: the method stops after at most searches, since each track uses at least one detection, and the flow decomposition of line L7 returns a track set of least cost over all track sets.
Complexity
The graph has nodes and edges. Each augmentation adds one track, so there are at most shortest path searches. Bellman-Ford costs per search, so the total is time. The first search can use shortest paths on a DAG in , since the original graph has no cycles. After it, node potentials make all reduced costs nonnegative, so the later searches can use Dijkstra's algorithm in , for in all. The code keeps Bellman-Ford for every search, which is simpler, and needs at least one search, so its best case is . The space is for the graph. With links per detection to the few next frames, grows linearly in , and the method handles thousands of detections.
Properties
- Globally optimal for its model. No other set of tracks has lower cost.
- Number of tracks found. The number of tracks is an output, not an input.
- Batch. It needs all frames of the window before it can answer. A sliding window gives a delayed online version.
- Integral. The min-cost flow has an integral optimum because the constraint matrix of a network is totally unimodular, so no rounding is needed.
- Pairwise costs only. Each cost depends on one detection or two consecutive ones.
- Missed detections. Links across a gap of a few frames bridge short occlusions.
Variants and improvements
- Successive shortest paths with dynamic programming. Pirsiavash, Ramanan and Fowlkes (2011) showed that the first path can be found by dynamic programming over the frames, and gave a greedy approximation that adds paths without the reverse edges, with non-maximum suppression between rounds.
- K-shortest paths. Berclaz, Fleuret, Türetken and Fua (2011) track on a grid of ground locations from a probabilistic occupancy map, and find the disjoint paths with the K-shortest paths method.
- Other min-cost flow solvers. Cost scaling, push-relabel and the network simplex method solve the same problem, with or without a fixed amount of flow.
- Linear programming. The same model is a linear program whose optimum is integral, which allows extra linear constraints at the risk of losing integrality.
- Higher-order costs. Lifted multicut, quadratic terms and learned costs add terms on three or more detections, at the price of an NP-hard problem solved approximately.
- Learned link costs. Later work learns from appearance and motion features, and keeps the flow solver.
When to use it
Use network flow association for offline tracking, or online with a delay, when detections are reasonably good, and when you want the best set of tracks of a simple model without tuning a search. It is a good fit for people or vehicles seen by a fixed camera, where the number of objects changes and short occlusions are common. For online use with no delay, use a frame-by-frame method such as GNN. If identity depends on long-range evidence, such as appearance over the whole track, a method with higher-order costs or MHT can model it better.
Pitfalls
- Costs with the wrong signs. If for every detection, each false alarm becomes a track of one detection. The entry and exit costs must outweigh a weak detection.
- Dijkstra on negative costs. The detection costs are negative. Use Bellman-Ford or a DAG pass first, then potentials, before Dijkstra.
- Too many links. Allowing links across many frames makes grow quickly. Gate the links by distance and by the gap.
- One detection for two objects. Capacity 1 per detection means two objects merged into one detection cannot both use it. One of the tracks then needs a gap link.
- Fixed amount of flow. Giving the number of tracks in advance wastes the main advantage. Stop when the path cost becomes nonnegative.
- Identity switches inside the model. The optimum of a pairwise model can still swap two close targets if their links have similar costs.
Implementations
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/network-flow-tracking/. The authors are listed in prov/4Z2N0P.jsonl.
"""Network flow data association (Zhang, Li and Nevatia, 2008).
All detections of a video are linked into tracks at once. Each detection i
becomes two nodes u_i and v_i joined by an edge of capacity 1 and cost c_i
(negative for a likely true detection). The source s connects to every u_i
(entry cost), every v_i connects to the sink t (exit cost), and v_i connects
to u_j when detection j may follow detection i in a track (link cost). A flow
of k units is a set of k disjoint tracks, and its cost is the cost of the
tracks. The flow of least cost over all k is found by successive shortest
paths: augment one unit along a shortest s-t path of the residual graph,
found with Bellman-Ford because costs can be negative, until the shortest
path costs 0 or more.
"""
import math
INF = float("inf")
class FlowGraph:
"""A directed graph with unit capacities and a residual edge for each edge."""
def __init__(self, n_nodes):
self.n = n_nodes
self.to, self.cap, self.cost, self.adj = [], [], [], [[] for _ in range(n_nodes)]
def add_edge(self, a, b, cost, cap=1):
self.adj[a].append(len(self.to))
self.to.append(b)
self.cap.append(cap)
self.cost.append(cost)
self.adj[b].append(len(self.to))
self.to.append(a)
self.cap.append(0)
self.cost.append(-cost)
def shortest_path(self, s, t):
"""Bellman-Ford on the edges with residual capacity. Returns (distance, list of edge ids) or (INF, None)."""
dist = [INF] * self.n
prev = [-1] * self.n
dist[s] = 0.0
for _ in range(self.n - 1):
changed = False
for a in range(self.n):
if dist[a] == INF:
continue
for e in self.adj[a]:
if self.cap[e] > 0 and dist[a] + self.cost[e] < dist[self.to[e]] - 1e-12:
dist[self.to[e]] = dist[a] + self.cost[e]
prev[self.to[e]] = e
changed = True
if not changed:
break
if dist[t] == INF:
return INF, None
path, node = [], t
while node != s:
e = prev[node]
path.append(e)
node = self.to[e ^ 1]
return dist[t], path[::-1]
def track_by_flow(n_det, det_cost, entry_cost, exit_cost, links):
"""Least-cost set of disjoint tracks.
n_det: the number of detections. det_cost[i], entry_cost[i], exit_cost[i]:
the costs of using detection i, of starting a track at i, of ending a track
at i. links: a dict {(i, j): cost} of the allowed links from detection i to
a later detection j. Returns (tracks, total cost, the costs of the
augmenting paths in order), with each track a list of detections.
"""
s, t = 2 * n_det, 2 * n_det + 1
g = FlowGraph(2 * n_det + 2) # u_i = 2i, v_i = 2i + 1
for i in range(n_det): # @line L1
g.add_edge(2 * i, 2 * i + 1, det_cost[i])
g.add_edge(s, 2 * i, entry_cost[i]) # @line L2
g.add_edge(2 * i + 1, t, exit_cost[i])
for (i, j), c in sorted(links.items()):
g.add_edge(2 * i + 1, 2 * j, c)
total, path_costs = 0.0, [] # @line L3
while True:
d, path = g.shortest_path(s, t) # @line L4
if path is None or d >= 0: # @line L5
break
for e in path: # @line L6
g.cap[e] -= 1
g.cap[e ^ 1] += 1
total += d
path_costs.append(d)
tracks = [] # @line L7
for e in g.adj[s]:
if e % 2 == 0 and g.cap[e] == 0: # an edge s -> u_i that carries flow
node, track = g.to[e], []
while node != t:
track.append(node // 2)
v = node + 1
nxt = None
for f in g.adj[v]:
if f % 2 == 0 and g.cap[f] == 0:
nxt = g.to[f]
break
node = nxt
tracks.append(track)
tracks.sort()
return tracks, total, path_costs
def tracks_cost(tracks, det_cost, entry_cost, exit_cost, links):
"""The cost of a set of tracks under the model of track_by_flow."""
total = 0.0
for tr in tracks:
total += entry_cost[tr[0]] + exit_cost[tr[-1]] + sum(det_cost[i] for i in tr)
total += sum(links[(a, b)] for a, b in zip(tr, tr[1:]))
return total
def detection_costs(frames, sigma=1.0, max_gap=2, gap_cost=1.0, enter=2.0, leave=2.0, speed=None):
"""Costs of a simple tracking model from detections (frame, x, y, score).
det_cost = ln((1 - score) / score), negative for a score above 0.5.
A link i -> j with 1 <= gap <= max_gap frames costs |p_j - p_i - gap v|^2
/ (2 gap sigma^2) + (gap - 1) gap_cost, with v a known mean velocity or
zero, and is allowed only below 9.21 / 2 + (gap - 1) gap_cost.
"""
n = len(frames)
det = [math.log((1.0 - f[3]) / f[3]) for f in frames]
vx, vy = speed if speed else (0.0, 0.0)
links = {}
for i in range(n):
for j in range(n):
gap = frames[j][0] - frames[i][0]
if 1 <= gap <= max_gap:
dx = frames[j][1] - frames[i][1] - gap * vx
dy = frames[j][2] - frames[i][2] - gap * vy
c = (dx * dx + dy * dy) / (2 * gap * sigma * sigma)
if c <= 9.21 / 2:
links[(i, j)] = c + (gap - 1) * gap_cost
return det, [enter] * n, [leave] * n, links
test_network_flow_tracking.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/network-flow-tracking/. The authors are listed in prov/4Z2N0P.jsonl.
import itertools
import random
from network_flow_tracking import INF, detection_costs, track_by_flow, tracks_cost
def brute_force(n, det, enter, leave, links):
"""Least cost over all sets of disjoint tracks: each detection is unused, ends a track, or links to a successor."""
options = []
for i in range(n):
succ = [j for (a, j) in links if a == i]
options.append(["off", "end"] + succ)
best = 0.0 # the empty set of tracks
for choice in itertools.product(*options):
used = [c != "off" for c in choice]
targets = [c for c in choice if c not in ("off", "end")]
if len(targets) != len(set(targets)):
continue
if any(not used[j] for j in targets):
continue
has_pred = set(targets)
cost = 0.0
for i, c in enumerate(choice):
if c == "off":
continue
cost += det[i]
if i not in has_pred:
cost += enter[i]
if c == "end":
cost += leave[i]
else:
cost += links[(i, c)]
best = min(best, cost)
return best
def random_instance(rng):
frames = [rng.randint(1, 2) for _ in range(3)] # detections per frame
frame_of = [f for f, k in enumerate(frames) for _ in range(k)]
n = len(frame_of)
det = [rng.uniform(-3.0, 1.0) for _ in range(n)]
enter = [rng.uniform(0.0, 2.0) for _ in range(n)]
leave = [rng.uniform(0.0, 2.0) for _ in range(n)]
links = {}
for i in range(n):
for j in range(n):
if 1 <= frame_of[j] - frame_of[i] <= 2 and rng.random() < 0.7:
links[(i, j)] = rng.uniform(0.0, 3.0)
return n, det, enter, leave, links
def test_optimal_against_brute_force():
rng = random.Random(2008)
for _ in range(150):
n, det, enter, leave, links = random_instance(rng)
tracks, total, path_costs = track_by_flow(n, det, enter, leave, links)
assert abs(total - brute_force(n, det, enter, leave, links)) < 1e-9
# the tracks are disjoint, follow allowed links, and their cost is the total
flat = [i for tr in tracks for i in tr]
assert len(flat) == len(set(flat))
assert all((a, b) in links for tr in tracks for a, b in zip(tr, tr[1:]))
assert abs(tracks_cost(tracks, det, enter, leave, links) - total) < 1e-9
# the augmenting paths get no cheaper: the cost is convex in the number of tracks
assert all(a <= b + 1e-9 for a, b in zip(path_costs, path_costs[1:]))
assert len(tracks) == len(path_costs)
def test_page_example():
# frame 0: a = 0, b = 1; frame 1: c = 2, d = 3
det = [-2.0] * 4
enter = [1.0] * 4
leave = [1.0] * 4
links = {(0, 2): 1.0, (0, 3): 0.1, (1, 2): 5.0, (1, 3): 0.2}
tracks, total, path_costs = track_by_flow(4, det, enter, leave, links)
# the first path takes a -> d; the second sends b to d and moves a to c through the residual edge
assert tracks == [[0, 2], [1, 3]]
assert abs(total + 2.8) < 1e-9
assert [round(c, 9) for c in path_costs] == [-1.9, -0.9]
def test_a_weak_isolated_detection_is_dropped():
det = [-0.5]
tracks, total, _ = track_by_flow(1, det, [1.0], [1.0], {})
assert tracks == [] and total == 0.0
tracks, total, _ = track_by_flow(1, [-2.5], [1.0], [1.0], {})
assert tracks == [[0]] and abs(total + 0.5) < 1e-12
def test_scene_with_misses_and_false_alarms():
rng = random.Random(7)
starts = [(0.0, 0.0), (0.0, 4.0), (0.0, 8.0)]
vel = (1.0, 0.0)
dets, truth = [], []
for f in range(10):
for k, (x0, y0) in enumerate(starts):
if (k, f) in ((0, 4), (2, 6)): # two missed detections
continue
dets.append((f, x0 + f * vel[0] + rng.gauss(0, 0.2), y0 + rng.gauss(0, 0.2), rng.uniform(0.8, 0.95)))
truth.append(k)
if f in (2, 5, 8): # false alarms with a low score
dets.append((f, rng.uniform(0, 10), rng.uniform(-2, 10), rng.uniform(0.5, 0.65)))
truth.append(-1)
det, enter, leave, links = detection_costs(dets, sigma=0.5, speed=vel)
tracks, total, _ = track_by_flow(len(dets), det, enter, leave, links)
assert len(tracks) == 3
for tr in tracks:
labels = {truth[i] for i in tr}
assert len(labels) == 1 and -1 not in labels
assert len(tr) == 10 - (1 if labels & {0, 2} else 0)
def test_empty():
assert track_by_flow(0, [], [], [], {}) == ([], 0.0, [])
assert INF > 0
History
Linear programming and flow formulations of data association appeared in the 2000s, and Jiang, Fels and Little used linear programming for multiple object tracking in 2007. In 2008, Li Zhang, Yuan Li and Ramakant Nevatia wrote the association of all detections as a min-cost flow, with two nodes per detection, derived the costs from a MAP model, and searched over the amount of flow. In 2011, Pirsiavash, Ramanan and Fowlkes showed how to compute the solution with successive shortest paths and dynamic programming, and gave a fast greedy version. In the same year, Berclaz, Fleuret, Türetken and Fua tracked people on an occupancy grid with K-shortest paths. These papers made global optimization a standard part of tracking-by-detection, and later work kept the flow solver and learned the costs.
References
- Li Zhang, Yuan Li and Ramakant Nevatia, Global data association for multi-object tracking using network flows, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2008, 1 to 8, the whole paper (the MAP formulation, the flow network with two nodes per detection, and the costs of entry, exit, detection and link)
- Hamed Pirsiavash, Deva Ramanan and Charless C. Fowlkes, Globally-optimal greedy algorithms for tracking a variable number of objects, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2011, 1201 to 1208, the whole paper (successive shortest paths on the tracking network and a greedy approximation by dynamic programming)
- Jérôme Berclaz, François Fleuret, Engin Türetken and Pascal Fua, Multiple object tracking using K-shortest paths optimization, IEEE Transactions on Pattern Analysis and Machine Intelligence 33(9), 2011, 1806 to 1819, the whole paper (tracking on an occupancy grid as disjoint shortest paths)
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 4Z2N0P Edit this page History Report an error Markdown