Algorithm Search⌘K

Algorithmadvanced

Graph cut stereo

Also called Kolmogorov-Zabih stereo.

Solve stereo by minimizing an energy with data, smoothness, occlusion and uniqueness terms over sets of pixel matches, by expansion moves that are each one minimum cut.

Time
O(k D (F + n)) worst · averageO(D (F + n)) best
Space
O(n) extra
Where
D = the number of disparities; F = the time of one max flow on O(n) nodes and O(n) edges; k = the number of cycles over the disparities; n = the number of pixels W H
Properties
deterministicnot exactofflineiterative
Origin
Vladimir Kolmogorov, Ramin Zabih, 2001

Graph cut stereo treats stereo matching as the minimization of one energy over the whole image, and minimizes it by minimum cuts. The simplest form gives each pixel a disparity label, with a data cost for the label and a Potts cost for neighbors with different labels, and runs alpha-expansion. The form of Kolmogorov and Zabih (2001), which this page implements, goes further. Its variables are not labels but assignments, possible matches between a left pixel and a right pixel, each active or not. The energy has four parts: a data cost for each active match, a cost KK for each pixel of either image that is matched to nothing (an occluded pixel), a smoothness cost when one of two neighboring matches with the same disparity is active and the other is not, and an infinite cost if a pixel takes part in two matches. The last term enforces uniqueness in both images, so occlusions are found by the energy itself and treat both images alike. An expansion move on a disparity α\alpha may drop old matches and switch matches of disparity α\alpha on or off. The best such move is a regular binary energy, so one minimum cut finds it, by the Kolmogorov-Zabih theorem. The method stops at a configuration that no expansion move improves. It costs one maximum flow per disparity and cycle, which is much more than semi-global matching.

In plain words

We want to match pixels of the left image with pixels of the right image in the same row. Each match costs the difference of the two colors. A pixel that stays unmatched pays a fixed price, because it might be hidden in the other view. Neighboring pixels like to move together, so we pay a little when one neighbor uses a certain shift and the other does not. No pixel may be in two matches. Start with nothing matched. Then, for one shift at a time, ask which old matches to drop and which new matches with this shift to add, all at once. A minimum cut in a graph answers this question exactly. Repeat for all shifts until nothing improves.

The problem

Input. A rectified pair of W×HW \times H images ILI_L and IRI_R, disparities 0,…,D−10, \dots, D - 1, an occlusion cost K≥0K \ge 0, a smoothness weight λ≥0\lambda \ge 0, and a data cost cap.

An assignment a=(p,d)a = (p, d) matches left pixel p=(u,v)p = (u, v) with right pixel (u−d,v)(u - d, v). A configuration is a set AA of active assignments. Two assignments are neighbors if they have the same disparity and their left pixels are 4-neighbors. The energy is

E(A)=∑a∈AD(a)+K⋅#{unmatched pixels of both images}+∑{a1,a2}∈NVa1a2[ ∣{a1,a2}∩A∣=1 ]+∞⋅[a pixel is in two active assignments].E(A) = \sum_{a \in A} D(a) + K \cdot \#\{\text{unmatched pixels of both images}\} + \sum_{\{a_1, a_2\} \in \mathcal{N}} V_{a_1 a_2} [\,|\{a_1, a_2\} \cap A| = 1\,] + \infty \cdot [\text{a pixel is in two active assignments}].

Here D(a)=min⁡(∣IL(p)−IR(q)∣,cutoff)D(a) = \min(|I_L(p) - I_R(q)|, \text{cutoff}), and Va1a2=3λV_{a_1 a_2} = 3\lambda if both the left and the right intensity differences of the two pixel pairs are below 8, and λ\lambda otherwise, as in the IPOL version of the method.

Output. A unique configuration that no expansion move improves, and from it a disparity for each left pixel, or "occluded".

The algorithm

For a disparity α\alpha, an α\alpha-expansion of AA is any configuration that keeps a subset of the active assignments with disparity other than α\alpha and adds any set of assignments with disparity α\alpha.

  1. KZ-STEREO(I_L, I_R, D, K, λ)
  2. 1A ← ∅ (every pixel occluded)
  3. 2repeat
  4. 3success ← false
  5. 4for each disparity α do
  6. 5build the binary energy of the α-expansion: a variable per active assignment with d ≠ α (keep or drop) and per assignment with d = α (on or off)
  7. 6A' ← the configuration of a minimizer, found by one minimum cut
  8. 7if E(A') < E(A) then A ← A'; success ← true
  9. 8until success = false
  10. 9return the disparity of the active assignment of each left pixel, or occluded

For line L5, a kept old assignment has x=0x = 0 and an active new one has x=1x = 1. With this choice every term is regular. A pixel covered by an old assignment a0a_0 and by the new assignment aαa_\alpha gets the term θ(xa0,xaα)\theta(x_{a_0}, x_{a_\alpha}) with θ(1,0)=K\theta(1, 0) = K (both off: occluded), θ(0,1)=∞\theta(0, 1) = \infty (both on: uniqueness fails) and 0 otherwise. A neighbor pair with the same disparity gets V[x1≠x2]V [x_1 \ne x_2]. The data costs and the pixels with only one candidate give unary terms. The code uses a number larger than the current energy in place of ∞\infty.

Example

One row, IL=(10,50,50,90)I_L = (10, 50, 50, 90), IR=(50,50,90,20)I_R = (50, 50, 90, 20), D=2D = 2, K=10K = 10, λ=2\lambda = 2. The right row is the left row moved by one pixel, with a new value at the end.

step active assignments (left pixel, dd) EE
start none: 8 pixels occluded 80
α=0\alpha = 0 (1, 0) 64
α=1\alpha = 1 (1, 1), (2, 1), (3, 1) 20
second cycle no move lowers EE 20

In the move on α=0\alpha = 0, only left pixel 1 and right pixel 1 have equal values, so one match is added. It costs 0 for the data, saves 2K=202K = 20 of occlusion cost, and pays λ=2\lambda = 2 twice, for its two neighbors at disparity 0 that stay off: E=60+4=64E = 60 + 4 = 64. In the move on α=1\alpha = 1, the cut drops (1,0)(1, 0), because it shares left pixel 1 with (1,1)(1, 1), and switches on three exact matches. Left pixel 0 and right pixel 3 stay occluded, for E=2K=20E = 2K = 20. All 128 configurations of this row give at least 20, so here the result is the global minimum.

Correctness

The full proof is in proofs/correctness.md. The variables of a move are in one-to-one correspondence with its move space. Each part of the energy is written as a term of at most two variables: two assignments with disparity α\alpha never share a pixel, and two old assignments do not either, so a pixel can only be claimed by one old and one new assignment. Every pair term is regular, so one minimum cut gives a minimizer. The current configuration is in the move space and has finite energy, so the minimizer never pays the stand-in for ∞\infty and is unique, and its energy is the least in the move space. The energy falls with each accepted move, so the method stops, at a configuration that no expansion move improves.

Proof: Correctness of graph cut stereo with expansion movesfull

We use the notation of the page. An assignment a=(p,d)a = (p, d) pairs left pixel p=(u,v)p = (u, v) with right pixel q=(u−d,v)q = (u - d, v). A configuration is a set AA of active assignments, and

E(A)=∑a∈AD(a)+K⋅#{pixels of both images covered by no a∈A}+∑{a1,a2}∈NVa1a2[ ∣{a1,a2}∩A∣=1 ]+∞⋅[a pixel is covered twice],E(A) = \sum_{a \in A} D(a) + K \cdot \#\{\text{pixels of both images covered by no } a \in A\} + \sum_{\{a_1, a_2\} \in \mathcal{N}} V_{a_1 a_2} [\,|\{a_1, a_2\} \cap A| = 1\,] + \infty \cdot [\text{a pixel is covered twice}],

with all costs D(a),K,Va1a2≥0D(a), K, V_{a_1 a_2} \ge 0. AA is unique if no pixel is covered twice; only unique configurations have finite energy. We prove that each expansion move returns the configuration of least energy in its move space, that the algorithm stops, and that it returns a unique configuration that no expansion move improves.

The move space and its variables

Fix a unique AA and a disparity α\alpha. Let A0={a∈A:d(a)≠α}A^0 = \{a \in A : d(a) \ne \alpha\} and let AαA^\alpha be the set of all assignments of disparity α\alpha. The α\alpha-expansions of AA are the sets A′=A0′∪Aα′A' = A'_0 \cup A'_\alpha with A0′⊆A0A'_0 \subseteq A^0 and Aα′⊆AαA'_\alpha \subseteq A^\alpha: old assignments can only be dropped, and assignments of disparity α\alpha can be switched on or off freely. AA itself is one of them.

Give each a∈A0a \in A^0 a variable xax_a, with xa=0x_a = 0 meaning a∈A′a \in A', and each a∈Aαa \in A^\alpha a variable xax_a, with xa=1x_a = 1 meaning a∈A′a \in A'. This is a bijection between {0,1}A0∪Aα\{0, 1\}^{A^0 \cup A^\alpha} and the move space. Write A′(x)A'(x) for the configuration of xx, and x0x^0 for the vector of AA itself.

The binary energy

Build B(x)B(x) as the sum of the following terms.

  1. Data. For a∈A0a \in A^0, the unary term D(a)D(a) at xa=0x_a = 0; for a∈Aαa \in A^\alpha, D(a)D(a) at xa=1x_a = 1.
  2. Pixels. Each pixel ss of either image is covered in A′(x)A'(x) only by the assignment of A0A^0 that covers it in AA (at most one, since AA is unique), call it a0a_0, or by the one assignment of disparity α\alpha that contains it, call it aαa_\alpha, if that assignment lies inside the image. Two assignments of disparity α\alpha never share a pixel, because the left pixel and α\alpha fix the right pixel and the other way round. Every other assignment that contains ss is not in A′(x)A'(x). So:
    • if both a0a_0 and aαa_\alpha exist, add the pair term θ(xa0,xaα)\theta(x_{a_0}, x_{a_\alpha}) with θ(0,0)=0\theta(0,0) = 0, θ(0,1)=β\theta(0,1) = \beta, θ(1,0)=K\theta(1,0) = K and θ(1,1)=0\theta(1,1) = 0. Here (0,1)(0, 1) means both cover ss, and (1,0)(1, 0) means neither does. β\beta is a number larger than E(A)E(A), used in place of ∞\infty;
    • if only a0a_0 exists, add KK at xa0=1x_{a_0} = 1; if only aαa_\alpha exists, add KK at xaα=0x_{a_\alpha} = 0; if neither exists, add the constant KK.
  3. Smoothness. A neighbor pair {a1,a2}\{a_1, a_2\} has one disparity dd. If d=αd = \alpha, both are variables with the same meaning of xx, so add V[xa1≠xa2]V [x_{a_1} \ne x_{a_2}]. If d≠αd \ne \alpha and both are in A0A^0, the same term works, because both use x=0x = 0 for active. If exactly one, say a1a_1, is in A0A^0, then a2∉Aa_2 \notin A has d≠αd \ne \alpha and stays inactive, so add VV at xa1=0x_{a_1} = 0. If neither is in A0A^0, both stay inactive and the term is 0.

Claim 1. If A′(x)A'(x) is unique, B(x)=E(A′(x))B(x) = E(A'(x)). If not, B(x)≥β>E(A)B(x) \ge \beta > E(A).

Proof. The data, occlusion and smoothness parts of E(A′(x))E(A'(x)) are split above by assignment, by pixel and by neighbor pair, and each part is written as a term of BB that takes the same value for every xx, except for the value β\beta in item 2. A pixel is covered twice in A′(x)A'(x) only if it is covered by both a0a_0 and aαa_\alpha: two assignments of A0A^0 cannot share a pixel because AA is unique, and two of disparity α\alpha cannot either. That is exactly the case (xa0,xaα)=(0,1)(x_{a_0}, x_{a_\alpha}) = (0, 1) of item 2, which adds β\beta, while all other terms are nonnegative. If A′(x)A'(x) is unique, that case never happens and all terms equal those of EE. □\square

Claim 2. Every pair term of BB is regular: θ(0,0)+θ(1,1)≤θ(0,1)+θ(1,0)\theta(0,0) + \theta(1,1) \le \theta(0,1) + \theta(1,0).

Proof. Item 2 gives 0+0≤β+K0 + 0 \le \beta + K, and item 3 gives 0+0≤V+V0 + 0 \le V + V. □\square

Each move is optimal

By Claim 2 and the Kolmogorov-Zabih construction (see graph-representable energies), one minimum cut on a graph with a node per variable gives a minimizer x∗x^* of BB. By Claim 1, B(x∗)≤B(x0)=E(A)<βB(x^*) \le B(x^0) = E(A) < \beta, so A′(x∗)A'(x^*) is unique, and for every unique A′(x)A'(x) we have E(A′(x∗))=B(x∗)≤B(x)=E(A′(x))E(A'(x^*)) = B(x^*) \le B(x) = E(A'(x)). Non-unique configurations have infinite energy. So A′(x∗)A'(x^*) has the least energy in the move space, and E(A′(x∗))≤E(A)E(A'(x^*)) \le E(A).

Termination and the final state

The algorithm starts from A=∅A = \emptyset, which is unique, and replaces AA only by a move result of strictly lower energy, which is unique by the last section. There are finitely many configurations and the energy drops strictly at each change, so no configuration repeats and the loop stops. With integer costs it stops after at most E(∅)=2KWHE(\emptyset) = 2 K W H changes. It stops after a cycle over all α\alpha in which no move lowered the energy. In that cycle AA did not change, and each move returned the best configuration in its move space, which contains AA; so no α\alpha-expansion of the final AA has lower energy, for any α\alpha. □\square

What is not claimed

The result is a local minimum for expansion moves, not a global minimum. The factor 2c2c of alpha-expansion is proved for energies with one label per site and a metric pairwise term; this energy has binary variables per assignment and a uniqueness constraint, so that bound does not apply to it as stated.

Complexity

The model is the real RAM. Let n=WHn = W H.

  • One move. There are at most nn old assignments, one per left pixel, and at most nn assignments of disparity α\alpha. The graph has O(n)O(n) nodes and O(n)O(n) edges, and building it costs O(n)O(n). Then one max flow costs FF; with the Boykov-Kolmogorov algorithm this is fast in practice on such grids, although its worst case bound is not polynomial in nn alone.
  • All moves. A cycle has DD moves, so the total is O(kD(F+n))O(k D (F + n)). With integer costs, k≤2Kn+1k \le 2 K n + 1, because E(∅)=2KnE(\emptyset) = 2 K n and each cycle except the last lowers EE by at least 1. In practice a few cycles suffice; this is an observation.
  • Space. O(n)O(n) for the configuration and the graph of one move.

The reference code builds each move over all assignments, which costs O(nD)O(n D) per move, and uses Edmonds-Karp for the cut.

Properties

  • Symmetric occlusions. Both images are treated alike: uniqueness holds in both, and occluded pixels in either image are part of the result.
  • No ordering constraint. Unlike dynamic programming stereo, matches need not keep their order, so thin objects can be matched.
  • Local minimum. The result is optimal only for single expansion moves, and the factor 2c2c of alpha-expansion does not apply to this energy as it stands.
  • Depends on the order. The order of the disparities and the start can change the result.
  • Edges follow intensity. The smoothness weight is larger where the image is uniform, so depth edges tend to line up with intensity edges.

Variants and improvements

  • Labels instead of assignments. Give each pixel a disparity, use a Potts or truncated linear smoothness term and run alpha-expansion or alpha-beta swap, as in Boykov, Veksler and Zabih (2001). This is simpler but has no symmetric occlusion model.
  • Exact convex models. For a convex smoothness term on ordered disparities, Ishikawa (2003) finds the global minimum with one minimum cut on a graph with a layer per disparity; Roy and Cox (1998) gave an earlier max-flow formulation of stereo of this kind. Convex terms smooth depth edges too much.
  • Choice of KK and λ\lambda. The IPOL version sets λ=K/5\lambda = K / 5 by default and chooses KK by a heuristic from the data costs (its Section 4.2).
  • Several cameras. The same idea extends to more than two views, with visibility terms.

When to use it

Use it when accuracy at occlusion boundaries matters more than speed, for example for offline reconstruction or to produce reference results. For real time use, take semi-global matching. When you only need disparity labels with a smoothness term and no occlusion model, plain alpha-expansion on labels is simpler.

Pitfalls

  • Wrong encoding of a move. If old and new assignments use the same meaning of xx, the uniqueness and occlusion terms are not regular and the cut is wrong. Old assignments must use x=0x = 0 for "kept", new ones x=1x = 1 for "on".
  • Infinite capacities. Use a finite number larger than any finite energy for ∞\infty, and make sure the current configuration is a valid point of the move, so the minimum is finite.
  • Accepting worse moves. Accept a move only if the energy drops; with ties the method may cycle.
  • Balance of KK and λ\lambda. A small KK gives large occluded areas; a large KK forces matches in true occlusions. Scale both with the data cost and its cap.
  • Large disparity ranges. Each cycle costs one cut per disparity, so the time grows with DD; restrict the range or work coarse to fine.

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.

graph_cut_stereo.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/graph-cut-stereo/. The authors are listed in prov/A0NX9X.jsonl.
"""Graph cut stereo with occlusions, after Kolmogorov and Zabih (2001).

The pair is rectified; left pixel (u, v) may match right pixel (u - d, v)
with d in [0, D). An assignment is a = (v, u, d) with u - d >= 0, and a
configuration is the set A of active assignments. Its energy is

    E(A) = sum_{a in A} Dcost(a)                         data
         + K * (pixels of either image covered by no a)  occlusion
         + sum over neighbor pairs {a1, a2} of V(a1, a2) [exactly one active]
         + infinity if a pixel is covered twice           uniqueness

Two assignments are neighbors when they have the same d and their left
pixels are 4-neighbors. Dcost(a) = min(|IL - IR|, cutoff), and V is
3 * lam when both the left and the right intensity differences of the
pair are below 8, and lam otherwise (the choice of the IPOL version).

An alpha-expansion move may drop any active assignment whose disparity is
not alpha and may switch any assignment of disparity alpha on or off. The
best move is a regular binary energy and is found by one minimum cut.
"""

from __future__ import annotations

from collections import deque
from typing import Dict, List, Optional, Sequence, Set, Tuple

Assignment = Tuple[int, int, int]  # (v, u, d)
INF = float("inf")


class Problem:
    def __init__(self, left, right, D: int, K: float, lam: float,
                 cutoff: float = 30):
        self.left, self.right, self.D = left, right, D
        self.H, self.W = len(left), len(left[0])
        self.K, self.lam, self.cutoff = K, lam, cutoff

    def valid(self, v: int, u: int, d: int) -> bool:
        return 0 <= v < self.H and 0 <= u < self.W and 0 <= u - d < self.W and 0 <= d < self.D

    def data(self, a: Assignment) -> float:
        v, u, d = a
        return min(abs(self.left[v][u] - self.right[v][u - d]), self.cutoff)

    def smooth(self, a1: Assignment, a2: Assignment) -> float:
        (v1, u1, d), (v2, u2, _) = a1, a2
        dl = abs(self.left[v1][u1] - self.left[v2][u2])
        dr = abs(self.right[v1][u1 - d] - self.right[v2][u2 - d])
        return 3 * self.lam if max(dl, dr) < 8 else self.lam

    def assignments(self) -> List[Assignment]:
        return [(v, u, d) for v in range(self.H) for u in range(self.W)
                for d in range(self.D) if u - d >= 0]

    def neighbor_pairs(self) -> List[Tuple[Assignment, Assignment]]:
        out = []
        for (v, u, d) in self.assignments():
            for (v2, u2) in ((v, u + 1), (v + 1, u)):
                if self.valid(v2, u2, d):
                    out.append(((v, u, d), (v2, u2, d)))
        return out


def energy(P: Problem, A: Set[Assignment]) -> float:
    left_cov: Dict[Tuple[int, int], int] = {}
    right_cov: Dict[Tuple[int, int], int] = {}
    e = 0.0
    for a in A:
        v, u, d = a
        left_cov[(v, u)] = left_cov.get((v, u), 0) + 1
        right_cov[(v, u - d)] = right_cov.get((v, u - d), 0) + 1
        e += P.data(a)
    if any(c > 1 for c in left_cov.values()) or any(c > 1 for c in right_cov.values()):
        return INF
    e += P.K * (2 * P.H * P.W - len(left_cov) - len(right_cov))
    for (a1, a2) in P.neighbor_pairs():
        if (a1 in A) != (a2 in A):
            e += P.smooth(a1, a2)
    return e


def _min_cut_source_side(nn: int, edges, s: int, t: int) -> List[bool]:
    """Edmonds-Karp max flow; return the nodes that s reaches at the end."""
    adj: List[List[int]] = [[] for _ in range(nn)]
    to: List[int] = []
    cap: List[float] = []
    for (u, v, c) in edges:
        adj[u].append(len(to))
        to.append(v)
        cap.append(c)
        adj[v].append(len(to))
        to.append(u)
        cap.append(0)
    while True:
        prev = [-1] * nn
        seen = [False] * nn
        seen[s] = True
        queue = deque([s])
        while queue and not seen[t]:
            u = queue.popleft()
            for e in adj[u]:
                if cap[e] > 0 and not seen[to[e]]:
                    seen[to[e]] = True
                    prev[to[e]] = e
                    queue.append(to[e])
        if not seen[t]:
            return seen
        path = []
        v = t
        while v != s:
            path.append(prev[v])
            v = to[prev[v] ^ 1]
        delta = min(cap[e] for e in path)
        for e in path:
            cap[e] -= delta
            cap[e ^ 1] += delta


def minimize_regular_binary(n: int, unary, terms) -> List[int]:
    """Minimize sum_p unary[p][x_p] + sum of terms (p, q, A, B, C, D), with
    A = theta(0,0), B = theta(0,1), C = theta(1,0), D = theta(1,1) and
    A + D <= B + C, over x in {0,1}^n, by one minimum cut (x_p = 0 is the
    source side)."""
    s, t = n, n + 1
    lin = [u1 - u0 for (u0, u1) in unary]
    edges = []
    for (p, q, A, B, C, Dd) in terms:
        k = B + C - A - Dd
        if k < 0:
            raise ValueError("nonregular term")
        lin[p] += C - A
        lin[q] += Dd - C
        if k > 0:
            edges.append((p, q, k))
    for p in range(n):
        if lin[p] > 0:
            edges.append((s, p, lin[p]))
        elif lin[p] < 0:
            edges.append((p, t, -lin[p]))
    side = _min_cut_source_side(n + 2, edges, s, t)
    return [0 if side[p] else 1 for p in range(n)]


def move_energy(P: Problem, A: Set[Assignment], alpha: int):
    """The binary energy of the alpha-expansion of A.

    Returns (variables, n_old, unary, terms, constant, big). Variable i is
    an assignment. The first n_old are the active ones with d != alpha:
    x = 0 keeps one and x = 1 drops it. The others are all assignments
    with d == alpha: x = 1 makes one active. The finite
    part of the binary energy plus the constant equals E of the result;
    `big` stands in for infinity."""
    old = sorted(a for a in A if a[2] != alpha)
    new = [a for a in P.assignments() if a[2] == alpha]
    var = old + new
    index = {a: i for i, a in enumerate(var)}
    n_old = len(old)
    big = 1 + P.K * 2 * P.H * P.W + sum(P.data(a) for a in var) \
        + sum(P.smooth(a1, a2) for (a1, a2) in P.neighbor_pairs())
    unary = [[0.0, 0.0] for _ in var]
    terms = []
    const = 0.0
    for i, a in enumerate(var):  # data
        if i < n_old:
            unary[i][0] += P.data(a)
        else:
            unary[i][1] += P.data(a)
    # each pixel: the old assignment and the alpha assignment covering it
    cover_old: Dict[Tuple[str, int, int], int] = {}
    for i, (v, u, d) in enumerate(old):
        cover_old[("L", v, u)] = i
        cover_old[("R", v, u - d)] = i
    for v in range(P.H):
        for u in range(P.W):
            for side in ("L", "R"):
                i = cover_old.get((side, v, u))
                a_new = (v, u, alpha) if side == "L" else (v, u + alpha, alpha)
                j = index.get(a_new) if P.valid(*a_new) else None
                if i is not None and j is not None:
                    # occluded if dropped and not switched on; both: forbidden
                    terms.append((i, j, 0.0, big, P.K, 0.0))
                elif i is not None:
                    unary[i][1] += P.K
                elif j is not None:
                    unary[j][0] += P.K
                else:
                    const += P.K
    for (a1, a2) in P.neighbor_pairs():  # smoothness
        w = P.smooth(a1, a2)
        i, j = index.get(a1), index.get(a2)
        if i is not None and j is not None:
            terms.append((i, j, 0.0, w, w, 0.0))
        elif i is not None:  # a2 stays inactive; pay w if a1 is active
            unary[i][0 if i < n_old else 1] += w
        elif j is not None:
            unary[j][0 if j < n_old else 1] += w
    return var, n_old, unary, terms, const, big


def result_of(var, n_old, x) -> Set[Assignment]:
    return {a for i, a in enumerate(var) if (x[i] == 0) == (i < n_old)}


def expansion_move(P: Problem, A: Set[Assignment], alpha: int) -> Set[Assignment]:
    var, n_old, unary, terms, _, _ = move_energy(P, A, alpha)  # @line L5
    x = minimize_regular_binary(len(var), unary, terms)  # @line L6
    return result_of(var, n_old, x)  # @line L6


def graph_cut_stereo(P: Problem, A: Optional[Set[Assignment]] = None,
                     order: Optional[Sequence[int]] = None
                     ) -> Tuple[Set[Assignment], int]:
    """Expansion moves over all disparities until none lowers E.
    Returns (active assignments, number of cycles)."""
    A = set() if A is None else set(A)  # @line L1
    e = energy(P, A)
    order = list(range(P.D)) if order is None else list(order)
    cycles = 0
    while True:  # @line L2
        cycles += 1
        success = False  # @line L3
        for alpha in order:  # @line L4
            A2 = expansion_move(P, A, alpha)
            e2 = energy(P, A2)
            if e2 < e:  # @line L7
                A, e, success = A2, e2, True  # @line L7
        if not success:  # @line L8
            return A, cycles


def disparity_map(P: Problem, A: Set[Assignment]) -> List[List[Optional[int]]]:
    """The disparity of each left pixel, or None where it is occluded."""
    out: List[List[Optional[int]]] = [[None] * P.W for _ in range(P.H)]
    for (v, u, d) in A:  # @line L9
        out[v][u] = d
    return out
test_graph_cut_stereo.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/graph-cut-stereo/. The authors are listed in prov/A0NX9X.jsonl.

import itertools
import random

from graph_cut_stereo import (
    INF,
    Problem,
    disparity_map,
    energy,
    expansion_move,
    graph_cut_stereo,
    move_energy,
    result_of,
)


def random_problem(rng, H, W, D):
    left = [[rng.choice([10, 20, 50, 90]) for _ in range(W)] for _ in range(H)]
    right = [[rng.choice([10, 20, 50, 90]) for _ in range(W)] for _ in range(H)]
    return Problem(left, right, D, K=rng.choice([5, 10, 20]), lam=rng.choice([1, 2, 4]))


def random_valid_configuration(rng, P):
    A, used_l, used_r = set(), set(), set()
    cand = P.assignments()
    rng.shuffle(cand)
    for (v, u, d) in cand:
        if rng.random() < 0.5 and (v, u) not in used_l and (v, u - d) not in used_r:
            A.add((v, u, d))
            used_l.add((v, u))
            used_r.add((v, u - d))
    return A


def binary_value(unary, terms, const, x):
    e = const + sum(unary[i][x[i]] for i in range(len(x)))
    for (p, q, A, B, C, Dd) in terms:
        e += ((A, B), (C, Dd))[x[p]][x[q]]
    return e


def test_move_energy_equals_the_stereo_energy():
    rng = random.Random(1)
    for _ in range(40):
        P = random_problem(rng, rng.randint(1, 2), rng.randint(2, 4), rng.randint(2, 3))
        A = random_valid_configuration(rng, P)
        alpha = rng.randrange(P.D)
        var, n_old, unary, terms, const, big = move_energy(P, A, alpha)
        for _ in range(30):
            x = [rng.randint(0, 1) for _ in var]
            e = energy(P, result_of(var, n_old, x))
            b = binary_value(unary, terms, const, x)
            if e == INF:
                assert b >= big
            else:
                assert b == e
        for (p, q, A_, B, C, Dd) in terms:
            assert A_ + Dd <= B + C  # every term is regular


def test_expansion_move_is_the_best_move():
    rng = random.Random(2)
    for _ in range(40):
        P = random_problem(rng, 1, rng.randint(2, 4), rng.randint(2, 3))
        A = random_valid_configuration(rng, P)
        alpha = rng.randrange(P.D)
        var, n_old, _, _, _, _ = move_energy(P, A, alpha)
        assert len(var) <= 10
        best = min(energy(P, result_of(var, n_old, x))
                   for x in itertools.product((0, 1), repeat=len(var)))
        A2 = expansion_move(P, A, alpha)
        assert energy(P, A2) == best <= energy(P, A)


def all_configurations(P):
    cand = P.assignments()
    for mask in range(1 << len(cand)):
        yield {cand[i] for i in range(len(cand)) if mask >> i & 1}


def test_result_is_a_local_minimum_and_never_below_the_optimum():
    rng = random.Random(3)
    for H, W, D in ((1, 3, 2), (1, 4, 2), (2, 3, 2), (1, 4, 3)):
        for _ in range(3):
            P = random_problem(rng, H, W, D)
            assert len(P.assignments()) <= 12
            A, cycles = graph_cut_stereo(P)
            e = energy(P, A)
            assert e < INF and e <= energy(P, set())
            for alpha in range(D):
                assert energy(P, expansion_move(P, A, alpha)) >= e
            opt = min(energy(P, B) for B in all_configurations(P))
            assert opt <= e


def make_pair(rng, W, H, dmap):
    """Random texture on the left; the right image shows at each column j
    the left pixel u with u - d(u) = j of the largest disparity."""
    left, right, truth = [], [], []
    for v in range(H):
        lrow = [rng.randint(0, 255) for _ in range(W)]
        owner = [None] * W
        for u in range(W):
            j = u - dmap[v][u]
            if j >= 0 and (owner[j] is None or dmap[v][owner[j]] < dmap[v][u]):
                owner[j] = u
        rrow = [lrow[owner[j]] if owner[j] is not None else rng.randint(0, 255)
                for j in range(W)]
        t = [None] * W
        for j in range(W):
            if owner[j] is not None:
                t[owner[j]] = dmap[v][owner[j]]
        left.append(lrow)
        right.append(rrow)
        truth.append(t)
    return left, right, truth


def test_recovers_a_step_with_occlusions():
    rng = random.Random(4)
    W, H, D = 14, 6, 5
    dmap = [[1 if u < 7 else 4 for u in range(W)] for _ in range(H)]
    left, right, truth = make_pair(rng, W, H, dmap)
    P = Problem(left, right, D, K=20, lam=4)
    A, cycles = graph_cut_stereo(P)
    disp = disparity_map(P, A)
    good = total = 0
    for v in range(H):
        for u in range(W):
            if truth[v][u] is not None:
                total += 1
                good += disp[v][u] == truth[v][u]
    assert good >= 0.95 * total
    hidden = sum(disp[v][u] is None for v in range(H) for u in range(W)
                 if truth[v][u] is None)
    assert hidden >= 1  # some truly occluded pixels come out as occluded


def test_worked_example():
    left = [[10, 50, 50, 90]]
    right = [[50, 50, 90, 20]]
    P = Problem(left, right, 2, K=10, lam=2)
    A, cycles = graph_cut_stereo(P)
    assert disparity_map(P, A) == [[None, 1, 1, 1]]
    assert energy(P, A) == 20
    assert energy(P, set()) == 80
    first = expansion_move(P, set(), 0)
    assert first == {(0, 1, 0)} and energy(P, first) == 64
    assert expansion_move(P, first, 1) == A
    assert min(energy(P, B) for B in all_configurations(P)) == 20

History

Roy and Cox (1998) solved stereo over a whole image with one maximum flow. Boykov, Veksler and Zabih (2001) introduced swap and expansion moves and used them for stereo with disparity labels, and Ishikawa (2003) gave an exact cut for convex priors. Kolmogorov and Zabih (2001) moved the variables from pixels to assignments, which allowed a symmetric model of occlusion with uniqueness, and showed that each expansion move of this energy is a minimum cut. Their later paper of 2004 gave the general condition, regularity, under which such moves are cuts. Kolmogorov, Monasse and Tan (2014) published a detailed description and a reference implementation in IPOL.

References

  1. Vladimir Kolmogorov and Ramin Zabih, Computing visual correspondence with occlusions using graph cuts, Proceedings of the Eighth IEEE International Conference on Computer Vision (ICCV 2001), volume 2, 508-515, the energy over assignments with data, occlusion, smoothness and uniqueness terms, and its minimization by expansion moves
  2. Vladimir Kolmogorov, Pascal Monasse and Pauline Tan, Kolmogorov and Zabih's graph cuts stereo matching algorithm, Image Processing On Line 4, 2014, 220-250, the detailed description of the energy and the graph of a move, the cap CUTOFF = 30 on the data cost, the smoothness weight 3 lambda when both intensity differences are below 8 and lambda otherwise, the default lambda = K / 5, and the choice of K in Section 4.2
  3. Vladimir Kolmogorov and Ramin Zabih, What energy functions can be minimized via graph cuts?, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(2), 2004, 147-159, Theorem 4.1 (regular binary energies of at most two variables per term are graph representable), used for each move
  4. Yuri Boykov, Olga Veksler and Ramin Zabih, Fast approximate energy minimization via graph cuts, IEEE Transactions on Pattern Analysis and Machine Intelligence 23(11), 2001, 1222-1239, Section 3 (expansion moves) and Section 8 (stereo with disparity labels and a Potts smoothness term)
  5. Sébastien Roy and Ingemar J. Cox, A maximum-flow formulation of the N-camera stereo correspondence problem, Proceedings of the Sixth International Conference on Computer Vision (ICCV 1998), 492-499, the first formulation of stereo as one maximum flow problem over the whole image
  6. Hiroshi Ishikawa, Exact optimization for Markov random fields with convex priors, IEEE Transactions on Pattern Analysis and Machine Intelligence 25(10), 2003, 1333-1336, the exact minimum cut for labels on a line with a convex pairwise term, which covers stereo with a convex smoothness term
  7. Daniel Scharstein and Richard Szeliski, A taxonomy and evaluation of dense two-frame stereo correspondence algorithms, International Journal of Computer Vision 47(1-3), 2002, 7-42, graph cuts (GC) among the global methods of the taxonomy and in the evaluation
  8. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (global optimization with graph cuts)

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