Algorithm Search⌘K

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
Properties
deterministicexactiterativenot localoffline
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 nn detections, each with a frame number, a position and a confidence, and the costs of a model:

  • ci=ln⁡(βi/(1−βi))c_i = \ln(\beta_i / (1 - \beta_i)) for using detection ii, where βi\beta_i is the probability that detection ii is false, so a confident detection has a negative cost;
  • cenc_{\text{en}} and cexc_{\text{ex}} for starting and ending a track, the negative logs of the probabilities of entry and exit;
  • cij=−ln⁡Plink(j∣i)c_{ij} = -\ln P_{\text{link}}(j \mid i) for detection jj following detection ii 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 ss, the sink tt, and two nodes uiu_i and viv_i per detection, so V=2n+2V = 2n + 2. Its edges, all of capacity 1, are ui→viu_i \to v_i with cost cic_i, s→uis \to u_i with cost cenc_{\text{en}}, vi→tv_i \to t with cost cexc_{\text{ex}}, and vi→ujv_i \to u_j with cost cijc_{ij} for each of the LL allowed links, so E=3n+LE = 3n + L. The capacity 1 on ui→viu_i \to v_i makes each detection belong to at most one track.

The algorithm

  1. NETWORK-FLOW-TRACKING(the detections, the costs c_i, c_en, c_ex, c_ij)
  2. 1build the nodes s, t, u_i, v_i and the edges u_i → v_i of cost c_i, all of capacity 1
  3. 2add 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
  4. 3start with the zero flow
  5. 4repeat: find a shortest s-t path P in the residual graph, with Bellman-Ford
  6. 5if there is no path or cost(P) ≥ 0, stop
  7. 6push one unit of flow along P
  8. 7decompose 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 aa and bb, and frame 1 has cc and dd. Every detection costs −2-2, and entry and exit cost 1 each. The allowed links cost a→ca \to c: 1.0, a→da \to d: 0.1, b→cb \to c: 5.0, and b→db \to d: 0.2. A track of two detections costs 1−2+cij−2+1=cij−21 - 2 + c_{ij} - 2 + 1 = c_{ij} - 2.

  • The first shortest path is s,a,d,ts, a, d, t, with cost −1.9-1.9. A greedy method would keep it and stop there, because bb and cc alone cost 0 each and b→cb \to c is expensive: total −1.9-1.9.
  • The second shortest path in the residual graph is s→ub→vb→ud→va→uc→vc→ts \to u_b \to v_b \to u_d \to v_a \to u_c \to v_c \to t. It takes dd for bb, goes back along the reverse of the link a→da \to d at cost −0.1-0.1, and gives cc to aa. Its cost is 1−2+0.2−0.1+1.0−2+1=−0.91 - 2 + 0.2 - 0.1 + 1.0 - 2 + 1 = -0.9.
  • The third search finds no path of negative cost, so the method stops with the tracks (a,c)(a, c) and (b,d)(b, d) and the total −1.9−0.9=−2.8-1.9 - 0.9 = -2.8. That is (1.0−2)+(0.2−2)(1.0 - 2) + (0.2 - 2).

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 −12.63-12.63, −12.0-12.0 and −11.0-11.0, 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 kk correspond to the sets of kk disjoint tracks, with the same cost.
  • Theorem: each step is optimal. After kk augmentations, the flow has the least cost among all flows of value kk, and the residual graph has no cycle of negative cost, so Bellman-Ford is correct at every step.
  • Theorem: convexity. The least cost F(k)F(k) of a flow of value kk is convex in kk, and the cost of the (k+1)(k + 1)-th augmenting path is F(k+1)−F(k)F(k + 1) - F(k). So the first path of nonnegative cost marks the minimum of FF over all kk, 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 GG has the nodes ss, tt, uiu_i, viv_i for i=1,…,ni = 1, \ldots, n, and the edges ui→viu_i \to v_i (cost cic_i), s→uis \to u_i (cost cenc_{\text{en}}), vi→tv_i \to t (cost cexc_{\text{ex}}) and vi→ujv_i \to u_j for each allowed link (cost cijc_{ij}), all of capacity 1. Links go from an earlier frame to a later one. A track is a sequence of detections i1,…,iri_1, \ldots, i_r with r≥1r \ge 1 in which each (iq,iq+1)(i_q, i_{q+1}) is an allowed link. Its cost is cen+∑qciq+∑qciqiq+1+cexc_{\text{en}} + \sum_q c_{i_q} + \sum_q c_{i_q i_{q+1}} + c_{\text{ex}}. 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 kk tracks gives an integral flow of value kk with the same cost, and every integral flow of value kk gives a track set with kk tracks and the same cost.

Proof. A track i1,…,iri_1, \ldots, i_r is the ss-tt path s,ui1,vi1,ui2,…,vir,ts, u_{i_1}, v_{i_1}, u_{i_2}, \ldots, v_{i_r}, t, and the cost of the path is the cost of the track. Disjoint tracks use disjoint edges ui→viu_i \to v_i and so disjoint edges overall, since every other edge touches one uiu_i or viv_i of a single track. So the sum of the paths is a flow with values 0 or 1, of value kk, and its cost is the sum of the track costs.

Conversely, take an integral flow ff of value kk. All capacities are 1, so ff is 0 or 1 on each edge. The graph GG has no directed cycle: number the nodes by frame and put uiu_i before viv_i, then every edge other than those at ss and tt 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 kk ss-tt paths, each with flow 1. Node uiu_i has a single outgoing edge, of capacity 1, so at most one path passes through uiu_i, and any path through uiu_i continues to viv_i. Node viv_i has a single incoming edge, so a path that reaches viv_i came from uiu_i. So each path has the form s,ui1,vi1,…,vir,ts, u_{i_1}, v_{i_1}, \ldots, v_{i_r}, t with allowed links in between, which is a track, and no two paths share a detection. The cost of ff is the sum of the path costs, which is the cost of the track set. □\square

The empty track set is the zero flow, of cost 0. So the least cost over all track sets is min⁡kF(k)\min_k F(k), where F(k)F(k) is the least cost of an integral flow of value kk (and F(k)=∞F(k) = \infty if no flow of value kk exists).

Claim 2: each augmentation keeps the flow optimal for its value

Let fkf_k be the flow after kk augmentations. Then fkf_k has the least cost among all flows of value kk, the residual graph GfkG_{f_k} has no cycle of negative cost, and fkf_k is integral.

Proof. By induction on kk. The zero flow is the only flow of value 0, and Gf0=GG_{f_0} = G has no cycle at all. Assume the claim for kk. A flow of value kk 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 GfkG_{f_k} has no negative cycle, Bellman-Ford computes correct shortest distances from ss, and the path PP it returns is a shortest ss-tt 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 fk+1f_{k+1} is of least cost for value k+1k + 1, and by the optimality condition Gfk+1G_{f_{k+1}} has no negative cycle. All residual capacities are integers and the path carries one unit, so fk+1f_{k+1} is integral. □\square

Claim 3: the cost is convex in the number of tracks, so the stopping rule is right

Let dk+1d_{k+1} be the cost of the shortest path found in step k+1k + 1. Then F(k+1)=F(k)+dk+1F(k + 1) = F(k) + d_{k+1}, and FF is convex on the values kk for which a flow exists. So d1≤d2≤…d_1 \le d_2 \le \ldots, and if the method stops before step k+1k + 1 because dk+1≥0d_{k+1} \ge 0 or no path exists, then F(k)=min⁡jF(j)F(k) = \min_j F(j).

Proof. By Claim 2, F(k+1)=cost⁡(fk+1)=cost⁡(fk)+dk+1=F(k)+dk+1F(k + 1) = \operatorname{cost}(f_{k+1}) = \operatorname{cost}(f_k) + d_{k+1} = F(k) + d_{k+1}.

For convexity, let Fˉ(x)\bar F(x) be the least cost of a flow of value xx with real flows allowed, the optimal value of a linear program whose constraints are Af=xbA f = x b, 0≤f≤10 \le f \le 1, with AA the node-edge incidence matrix and bb the vector with 11 at ss and −1-1 at tt. If ff and gg are optimal for the values xx and yy, then θf+(1−θ)g\theta f + (1 - \theta) g is feasible for the value θx+(1−θ)y\theta x + (1 - \theta) y, so Fˉ(θx+(1−θ)y)≤θFˉ(x)+(1−θ)Fˉ(y)\bar F(\theta x + (1 - \theta) y) \le \theta \bar F(x) + (1 - \theta) \bar F(y), and Fˉ\bar F is convex. The incidence matrix of a directed graph is totally unimodular, so for an integer value kk the linear program has an integral optimal solution (flow integrality), and Fˉ(k)=F(k)\bar F(k) = F(k). So FF restricted to the integers is convex: F(k+1)−F(k)≥F(k)−F(k−1)F(k + 1) - F(k) \ge F(k) - F(k - 1), which is dk+1≥dkd_{k+1} \ge d_k.

If dk+1≥0d_{k+1} \ge 0, then F(j+1)−F(j)=dj+1≥0F(j + 1) - F(j) = d_{j+1} \ge 0 for every j≥kj \ge k, so F(j)≥F(k)F(j) \ge F(k) for all j≥kj \ge k. For j<kj < k, F(k)−F(j)=dj+1+…+dk<0F(k) - F(j) = d_{j+1} + \ldots + d_k < 0, because every path that was augmented had negative cost. If no path exists, no flow of value k+1k + 1 exists, and by the same argument for j<kj < k the minimum is at kk. □\square

Together, the three claims give the result: the method stops after at most n+1n + 1 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 V=2n+2V = 2n + 2 nodes and E=3n+LE = 3n + L edges. Each augmentation adds one track, so there are at most K+1≤n+1K + 1 \le n + 1 shortest path searches. Bellman-Ford costs O(VE)=O(n(n+L))O(V E) = O(n (n + L)) per search, so the total is O(Kn(n+L))O(K n (n + L)) time. The first search can use shortest paths on a DAG in O(n+L)O(n + L), 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 O(E+Vlog⁡V)O(E + V \log V), for O(K(L+nlog⁡n))O(K (L + n \log n)) in all. The code keeps Bellman-Ford for every search, which is simpler, and needs at least one search, so its best case is O(n(n+L))O(n (n + L)). The space is O(n+L)O(n + L) for the graph. With LL links per detection to the few next frames, LL grows linearly in nn, 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 cijc_{ij} 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 cen+cex+ci<0c_{\text{en}} + c_{\text{ex}} + c_i < 0 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 LL 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.

network_flow_tracking.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • 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