Algorithm Search⌘K

Algorithmcore

Semi-global matching

Also called SGM, Hirschmuller semi-global matching.

Sum, over 8 or 16 directions, 1D dynamic programs on the cost volume with small and large jump penalties, then take the best disparity per pixel.

Time
Θ(W H D R) worst · average · best
Space
Θ(W H D) extra
Where
D = the number of disparities; H = the image height in pixels; R = the number of path directions; W = the image width in pixels
Properties
deterministicnot exactofflineiterative
Origin
Heiko Hirschmüller, 2005

Semi-global matching (SGM) is a method for dense stereo matching that sits between local and global methods. It starts from a cost volume C(p,d)C(p, d), the cost of giving pixel pp the disparity dd. Along a straight line through the image, a dynamic program finds the best disparity sequence under a smoothness model with two penalties: a small P1P_1 for a change of one disparity step, and a large P2P_2 for any larger jump. SGM runs this program along 8 or 16 directions that end at each pixel, adds the results, and gives each pixel the disparity of least sum. Each direction costs Θ(WHD)\Theta(W H D) and the work is regular, so SGM is fast and maps well to hardware. It is one of the most used stereo methods in practice, in robotics, cars and aerial mapping, and it is far less streaky than dynamic programming on single scanlines.

In plain words

For each pixel we have a cost for every possible depth. Choosing the cheapest depth for each pixel alone gives noisy results. So we want neighboring pixels to agree, but we also want to allow real depth edges. Imagine walking along a line toward a pixel. As you walk, you keep the best total cost for each depth, where a small change of depth from one pixel to the next costs a little and a big jump costs more. Do this from 8 or 16 directions, add the totals at each pixel, and pick the depth with the smallest sum. Each direction is cheap, and together they smooth the result in every direction.

The problem

Input. A cost volume C(p,d)≥0C(p, d) \ge 0 for the pixels pp of a W×HW \times H image and the disparities d∈{0,…,D−1}d \in \{0, \dots, D - 1\}, penalties 0≤P1≤P20 \le P_1 \le P_2, and a set RR of directions. The cost comes from a matching cost: Hirschmüller used mutual information, and the census transform is a common choice.

Output. A disparity map. Hirschmüller (2008) defines the energy

E(f)=∑pC(p,fp)+∑{p,q}∈N(P1[ ∣fp−fq∣=1 ]+P2[ ∣fp−fq∣>1 ]),E(f) = \sum_p C(p, f_p) + \sum_{\{p,q\} \in \mathcal{N}} \Big(P_1 [\,|f_p - f_q| = 1\,] + P_2 [\,|f_p - f_q| > 1\,]\Big),

whose exact minimum over a 2D grid is NP-hard to find in general. SGM does not minimize it. It minimizes it exactly along each 1D path and combines the paths.

The algorithm

For a direction rr, the path cost of pixel pp is

Lr(p,d)=C(p,d)+min⁡(Lr(p−r,d), Lr(p−r,d−1)+P1, Lr(p−r,d+1)+P1, min⁡kLr(p−r,k)+P2)−min⁡kLr(p−r,k),L_r(p, d) = C(p, d) + \min\big(L_r(p - r, d),\ L_r(p - r, d - 1) + P_1,\ L_r(p - r, d + 1) + P_1,\ \min_k L_r(p - r, k) + P_2\big) - \min_k L_r(p - r, k),

with Lr(p,d)=C(p,d)L_r(p, d) = C(p, d) when p−rp - r is outside the image.

  1. SGM(C, P1, P2, R)
  2. 1S(p, d) ← 0 for all pixels p and disparities d
  3. 2for each direction r in R do
  4. 3for each pixel p, in an order that visits p - r before p do
  5. 4if p - r is outside the image then L_r(p, d) ← C(p, d) for all d
  6. 5else m ← min over k of L_r(p - r, k)
  7. 6for each d: L_r(p, d) ← C(p, d) + min(L_r(p - r, d), L_r(p - r, d ± 1) + P1, m + P2) - m
  8. 7S(p, d) ← S(p, d) + L_r(p, d) for all d
  9. 8for each pixel p: f_p ← the least d with the least S(p, d)
  10. 9return f

The 8 directions are the horizontal, vertical and diagonal steps in both senses; the 16 directions add the eight knight moves such as (2,1)(2, 1). The subtraction of mm in line L6 does not change which dd is best along the path, but it keeps the values bounded.

Example

A row of three pixels with D=3D = 3, P1=2P_1 = 2, P2=6P_2 = 6 and the costs below. The middle pixel is noisy: alone, its best disparity is 1, while its neighbors clearly want 0.

pixel C(p,⋅)C(p, \cdot) L→L_{\rightarrow} L←L_{\leftarrow} SS winner
0 (0, 5, 9) (0, 5, 9) (0, 6, 12) (0, 11, 21) 0
1 (4, 3, 9) (4, 5, 15) (4, 5, 15) (8, 10, 30) 0
2 (0, 5, 9) (0, 6, 12) (0, 5, 9) (0, 11, 21) 0

From left to right at pixel 1, with L→(0)=(0,5,9)L_{\rightarrow}(0) = (0, 5, 9) and m=0m = 0: for d=0d = 0 the best is min⁡(0,5+2,0+6)=0\min(0, 5 + 2, 0 + 6) = 0, so L=4+0L = 4 + 0; for d=1d = 1 it is min⁡(5,0+2,9+2,6)=2\min(5, 0 + 2, 9 + 2, 6) = 2, so L=3+2=5L = 3 + 2 = 5; for d=2d = 2 it is min⁡(9,5+2,6)=6\min(9, 5 + 2, 6) = 6, so L=15L = 15. At pixel 2, m=4m = 4 is subtracted: L→(2,1)=5+min⁡(5,4+2,15+2,4+6)−4=6L_{\rightarrow}(2, 1) = 5 + \min(5, 4 + 2, 15 + 2, 4 + 6) - 4 = 6. The sum SS picks disparity 0 at pixel 1, where winner-takes-all on CC alone picks 1.

Correctness

The full proof is in proofs/correctness.md. SGM is not exact for the 2D energy; what can be proved is that each path cost is exact for its 1D problem. Without the subtraction, the recursion is the Viterbi recursion for the chain of pixels along the ray: the four candidates of line L6 are exactly the least value of Lr(p−r,k)+V(k,d)L_r(p - r, k) + V(k, d), with VV equal to 0, P1P_1 or P2P_2. The subtraction removes a constant from all dd at each pixel, and the constants add up along the ray, so Lr(p,d)L_r(p, d) equals the least chain energy of the ray ending at pp with disparity dd, minus a number that does not depend on dd. Each step adds a value between 0 and P2P_2 to C(p,d)C(p, d), which gives the bound C(p,d)≤Lr(p,d)≤Cmax⁡+P2C(p, d) \le L_r(p, d) \le C_{\max} + P_2.

Proof: Correctness of semi-global matchingfull

Semi-global matching does not claim to minimize the two-dimensional energy. What we prove is that it computes what it is defined to compute: for each direction rr and pixel pp, the path cost Lr(p,⋅)L_r(p, \cdot) equals, up to a constant that does not depend on dd, the least energy of a disparity sequence along the ray that ends at pp with disparity dd; and its values stay in [C(p,d),C(p,d)+P2][C(p, d), C(p, d) + P_2]. Then SS and the winner-takes-all step are plain sums and minima.

Setup

The cost volume gives C(p,d)≥0C(p, d) \ge 0 for d∈{0,…,D−1}d \in \{0, \dots, D - 1\}. Fix a direction rr and a pixel pp. Walking back from pp by −r-r until the next step would leave the image gives the ray p0,p1,…,pt=pp_0, p_1, \dots, p_t = p with ps=ps−1+rp_{s} = p_{s-1} + r. Define the jump cost V(a,b)=0V(a, b) = 0 if a=ba = b, min⁡(P1,P2)\min(P_1, P_2) if ∣a−b∣=1|a - b| = 1, and P2P_2 otherwise, with P1,P2≥0P_1, P_2 \ge 0. (With the usual choice P2≥P1P_2 \ge P_1 this is P1P_1 for a jump of one.) The chain energy of a sequence d0,…,dtd_0, \dots, d_t is

Et(d0,…,dt)=∑s=0tC(ps,ds)+∑s=1tV(ds−1,ds),E_t(d_0, \dots, d_t) = \sum_{s=0}^{t} C(p_s, d_s) + \sum_{s=1}^{t} V(d_{s-1}, d_s),

and L~(p,d)\tilde L(p, d) is its least value over all sequences with dt=dd_t = d.

Lemma 1 (the recursion without subtraction)

L~(p0,d)=C(p0,d)\tilde L(p_0, d) = C(p_0, d), and for s≥1s \ge 1

L~(ps,d)=C(ps,d)+min⁡k(L~(ps−1,k)+V(k,d)).\tilde L(p_s, d) = C(p_s, d) + \min_{k} \big(\tilde L(p_{s-1}, k) + V(k, d)\big).

Proof. A sequence ending with dd at psp_s is a sequence ending with some kk at ps−1p_{s-1}, followed by the jump from kk to dd and the cost C(ps,d)C(p_s, d). The best choice of the earlier part, for a fixed kk, has energy L~(ps−1,k)\tilde L(p_{s-1}, k). Take the least value over kk. □\square

Lemma 2 (the four candidates)

For any vector xx over the disparities with m=min⁡kxkm = \min_k x_k,

min⁡k(xk+V(k,d))=min⁡(xd, xd−1+P1, xd+1+P1, m+P2),\min_k \big(x_k + V(k, d)\big) = \min\big(x_d,\ x_{d-1} + P_1,\ x_{d+1} + P_1,\ m + P_2\big),

where the terms xd±1x_{d \pm 1} are left out if the index is outside the range.

Proof. Call the two sides AA and BB. The terms of AA are xdx_d for k=dk = d, xd±1+min⁡(P1,P2)x_{d \pm 1} + \min(P_1, P_2) for k=d±1k = d \pm 1, and xk+P2x_k + P_2 for the other kk.

B≤AB \le A: each term of AA is at least some term of BB. xdx_d is a term of BB. If P1≤P2P_1 \le P_2, then xd±1+min⁡(P1,P2)=xd±1+P1x_{d \pm 1} + \min(P_1, P_2) = x_{d \pm 1} + P_1; otherwise it is xd±1+P2≥m+P2x_{d \pm 1} + P_2 \ge m + P_2. And xk+P2≥m+P2x_k + P_2 \ge m + P_2.

A≤BA \le B: each term of BB is at least some term of AA. xdx_d is a term of AA. xd±1+P1≥xd±1+min⁡(P1,P2)x_{d \pm 1} + P_1 \ge x_{d \pm 1} + \min(P_1, P_2). Finally, let k∗k^* attain mm; since V(k∗,d)≤P2V(k^*, d) \le P_2, the term xk∗+V(k∗,d)x_{k^*} + V(k^*, d) of AA is at most m+P2m + P_2. □\square

Lemma 3 (the subtraction only shifts)

Let LrL_r be computed by the algorithm, with ms=min⁡kLr(ps,k)m_s = \min_k L_r(p_s, k). Then for all ss and dd,

Lr(ps,d)=L~(ps,d)−∑s′<sms′.L_r(p_s, d) = \tilde L(p_s, d) - \sum_{s' < s} m_{s'}.

Proof. By induction on ss. For s=0s = 0 both sides are C(p0,d)C(p_0, d) (line L4). For s≥1s \ge 1, line L6 computes C(ps,d)+min⁡(… )−ms−1C(p_s, d) + \min(\dots) - m_{s-1}, where by Lemma 2 the minimum equals min⁡k(Lr(ps−1,k)+V(k,d))\min_k (L_r(p_{s-1}, k) + V(k, d)). By the induction hypothesis Lr(ps−1,⋅)L_r(p_{s-1}, \cdot) is L~(ps−1,⋅)\tilde L(p_{s-1}, \cdot) minus a constant cs−1=∑s′<s−1ms′c_{s-1} = \sum_{s' < s-1} m_{s'}, and a constant shift passes through the minimum. With Lemma 1,

Lr(ps,d)=C(ps,d)+min⁡k(L~(ps−1,k)+V(k,d))−cs−1−ms−1=L~(ps,d)−∑s′<sms′.□L_r(p_s, d) = C(p_s, d) + \min_k\big(\tilde L(p_{s-1}, k) + V(k, d)\big) - c_{s-1} - m_{s-1} = \tilde L(p_s, d) - \sum_{s' < s} m_{s'}. \qquad \square

So for each pixel and direction, Lr(p,⋅)L_r(p, \cdot) and the exact chain minimum L~(p,⋅)\tilde L(p, \cdot) differ by a constant, and they have the same order over dd. The code visits rows in the order of the sign of the row step of rr and columns in the order of the sign of its column step; then p−rp - r is visited before pp, so line L6 reads a final value. The test file checks Lemma 3 against brute force over all sequences on small rays, for all 16 directions.

Lemma 4 (bounds)

For all pp and dd, C(p,d)≤Lr(p,d)≤C(p,d)+P2C(p, d) \le L_r(p, d) \le C(p, d) + P_2. In particular 0≤Lr(p,d)≤Cmax⁡+P20 \le L_r(p, d) \le C_{\max} + P_2, where Cmax⁡C_{\max} is the largest cost.

Proof. At the first pixel of a ray, Lr=CL_r = C. Otherwise, with x=Lr(p−r,⋅)x = L_r(p - r, \cdot) and m=min⁡xm = \min x, the value added to C(p,d)C(p, d) is min⁡(xd,xd±1+P1,m+P2)−m\min(x_d, x_{d \pm 1} + P_1, m + P_2) - m. Every candidate is at least mm, because P1,P2≥0P_1, P_2 \ge 0, so the value is at least 0. The last candidate is m+P2m + P_2, so the value is at most P2P_2. □\square

This is the bound L≤Cmax⁡+P2L \le C_{\max} + P_2 that Hirschmüller (2008) gives. It means that the path costs fit in a fixed number of bits, however long the path is.

The output

Line L7 adds Lr(p,d)L_r(p, d) over the directions, and line L8 takes the least dd with the least sum. Both are exact. By Lemmas 3 and 4, S(p,d)=∑rL~r(p,d)−K(p)S(p, d) = \sum_r \tilde L_r(p, d) - K(p) with K(p)K(p) independent of dd, so the winner-takes-all choice is the dd that minimizes the sum over the directions of the exact chain minima ending at pp with disparity dd. Since each C(p,d)C(p, d) appears once in every L~r(p,d)\tilde L_r(p, d), this sum counts the data cost of pp itself ∣R∣|R| times; this is part of the definition of the method and does not change with the subtraction.

Cost

For each direction, each of the WHW H pixels takes one minimum over DD values and DD updates with four candidates, which is O(D)O(D). So the path costs of ∣R∣|R| directions take Θ(WHD∣R∣)\Theta(W H D |R|) time, and the sum SS needs Θ(WHD)\Theta(W H D) memory. □\square

Complexity

The model is the word RAM with integer costs.

  • Time. Each direction does O(D)O(D) work per pixel, so Θ(WHD)\Theta(W H D) per direction and Θ(WHDR)\Theta(W H D R) in total. The time does not depend on the data.
  • Space. Θ(WHD)\Theta(W H D) for SS, plus the cost volume. A direction needs only the previous pixel of each path, so the path costs of one direction take Θ(WD)\Theta(W D) when the image is traversed row by row.

Properties

  • Not exact. The result is not the minimum of the 2D energy, and no bound relates its energy to the minimum.
  • Bounded values. With the subtraction, 0≤Lr≤Cmax⁡+P20 \le L_r \le C_{\max} + P_2, so path costs fit in small integers.
  • Regular and parallel. All pixels on the same front of a direction are independent, which suits SIMD, GPUs and FPGAs.
  • Edges. A small P1P_1 allows slanted surfaces, and a large P2P_2 prevents spurious jumps but still allows real depth edges.
  • Direction artifacts. With few directions, errors spread along the paths and show as streaks; Hirschmüller advises at least 8 directions and suggests 16.

Variants and improvements

  • Adaptive P2P_2. Hirschmüller (2008) divides P2P_2 by the intensity difference of the neighbors along the path, P2=P2′/∣Ip−Ip−r∣P_2 = P_2' / |I_p - I_{p-r}|, keeping P2≥P1P_2 \ge P_1, so that jumps are cheaper at image edges where depth edges are likely.
  • Post-processing. A left-right consistency check marks occlusions and mismatches, a median filter removes small errors, and subpixel refinement fits a parabola to SS around the winner.
  • Other costs. Mutual information in the original, and the census transform in many later systems.
  • Fewer directions. The directions that point forward in the scan order can all be computed in one pass over the image. Using only those saves memory and time, at some loss of quality.
  • Scanline optimization. One horizontal direction alone is the SO method of Scharstein and Szeliski (2002).

When to use it

Use SGM when you need dense depth from a rectified pair at high speed and good quality, for example in robotics, cars or aerial mapping. It is a strong default before learned methods. Use graph cut stereo when you need a global minimum of an energy with occlusions and can pay more time, and block matching when speed matters more than quality.

Pitfalls

  • Forgetting the subtraction. Without it, the values grow along the path and overflow small integers. The result is the same in exact arithmetic, but not in 16-bit code.
  • P2<P1P_2 < P_1. Then a jump of one costs more than a large jump, and the model no longer makes sense. Keep P2≥P1P_2 \ge P_1, also after adapting P2P_2.
  • Order of traversal. For each direction, p−rp - r must be computed before pp. With diagonal and knight directions, choose the order of rows and columns from the signs of the direction.
  • Penalties and cost scale. P1P_1 and P2P_2 must be on the same scale as the matching cost. After changing the cost function, choose them again.
  • Uniform data costs. In large areas with no texture, all directions bring the same weak information, and the result can be wrong over the whole area.

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.

semi_global_matching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semi-global-matching/. The authors are listed in prov/NJ87X5.jsonl.
"""Semi-global matching (Hirschmuller) on a given cost volume.

The cost volume is C[v][u][d], the matching cost of left pixel (u, v) at
disparity d in [0, D). For a direction r = (du, dv), the path cost is

    L_r(p, d) = C(p, d) + min(L_r(p - r, d),
                              L_r(p - r, d - 1) + P1,
                              L_r(p - r, d + 1) + P1,
                              min_k L_r(p - r, k) + P2)
                        - min_k L_r(p - r, k),

with L_r(p, d) = C(p, d) when p - r is outside the image. The costs of all
directions are added, S(p, d) = sum_r L_r(p, d), and each pixel takes the
least d with the least S(p, d) (winner-takes-all).
"""

from __future__ import annotations

from typing import List, Sequence, Tuple

DIRECTIONS_2 = [(1, 0), (-1, 0)]
DIRECTIONS_4 = DIRECTIONS_2 + [(0, 1), (0, -1)]
DIRECTIONS_8 = DIRECTIONS_4 + [(1, 1), (-1, -1), (1, -1), (-1, 1)]
DIRECTIONS_16 = DIRECTIONS_8 + [(2, 1), (-2, -1), (2, -1), (-2, 1),
                                (1, 2), (-1, -2), (1, -2), (-1, 2)]

Volume = Sequence[Sequence[Sequence[float]]]


def path_cost(C: Volume, P1: float, P2: float,
              r: Tuple[int, int]) -> List[List[List[float]]]:
    """L_r for all pixels and disparities, for one direction r."""
    H, W, D = len(C), len(C[0]), len(C[0][0])
    du, dv = r
    # p - r must come before p: rows in the order of dv, columns of du.
    rows = range(H) if dv >= 0 else range(H - 1, -1, -1)
    cols = range(W) if du >= 0 else range(W - 1, -1, -1)
    L = [[None] * W for _ in range(H)]
    for v in rows:  # @line L3
        for u in cols:  # @line L3
            pu, pv = u - du, v - dv
            c = C[v][u]
            if not (0 <= pu < W and 0 <= pv < H):  # @line L4
                L[v][u] = list(c)  # @line L4
                continue
            prev = L[pv][pu]
            m = min(prev)  # @line L5
            jump = m + P2
            out = [0.0] * D
            for d in range(D):  # @line L6
                best = prev[d]
                if d > 0 and prev[d - 1] + P1 < best:
                    best = prev[d - 1] + P1
                if d + 1 < D and prev[d + 1] + P1 < best:
                    best = prev[d + 1] + P1
                if jump < best:
                    best = jump
                out[d] = c[d] + best - m  # @line L6
            L[v][u] = out
    return L


def aggregate(C: Volume, P1: float, P2: float,
              directions: Sequence[Tuple[int, int]] = DIRECTIONS_8
              ) -> List[List[List[float]]]:
    """S(p, d), the sum of L_r(p, d) over the directions."""
    H, W, D = len(C), len(C[0]), len(C[0][0])
    S = [[[0.0] * D for _ in range(W)] for _ in range(H)]  # @line L1
    for r in directions:  # @line L2
        L = path_cost(C, P1, P2, r)
        for v in range(H):
            for u in range(W):
                Sp, Lp = S[v][u], L[v][u]
                for d in range(D):
                    Sp[d] += Lp[d]  # @line L7
    return S


def winner_takes_all(S: Volume) -> List[List[int]]:
    """For each pixel, the least d with the least cost."""
    return [[min(range(len(s)), key=s.__getitem__) for s in row]  # @line L8
            for row in S]


def sgm(C: Volume, P1: float, P2: float,
        directions: Sequence[Tuple[int, int]] = DIRECTIONS_8) -> List[List[int]]:
    """The disparity map of semi-global matching."""
    return winner_takes_all(aggregate(C, P1, P2, directions))  # @line L9


def absolute_difference_volume(left, right, D: int) -> List[List[List[int]]]:
    """C[v][u][d] = |left(u, v) - right(u - d, v)|, where a right column
    left of the image takes the value of column 0."""
    return [[[abs(lrow[u] - rrow[u - d if u >= d else 0]) for d in range(D)]
             for u in range(len(lrow))]
            for lrow, rrow in zip(left, right)]
test_semi_global_matching.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semi-global-matching/. The authors are listed in prov/NJ87X5.jsonl.

import itertools
import random

from semi_global_matching import (
    DIRECTIONS_2,
    DIRECTIONS_4,
    DIRECTIONS_8,
    DIRECTIONS_16,
    absolute_difference_volume,
    aggregate,
    path_cost,
    sgm,
    winner_takes_all,
)


def random_volume(rng, H, W, D, hi=9):
    return [[[rng.randint(0, hi) for _ in range(D)] for _ in range(W)] for _ in range(H)]


def jump_cost(a, b, P1, P2):
    if a == b:
        return 0
    if abs(a - b) == 1:
        return min(P1, P2)
    return P2


def chain_minimum(costs, P1, P2, d_last):
    """Brute force: the least sum of costs and jump costs over all
    disparity sequences along the chain that end with d_last."""
    D = len(costs[0])
    best = None
    for seq in itertools.product(range(D), repeat=len(costs) - 1):
        seq = seq + (d_last,)
        e = sum(costs[t][seq[t]] for t in range(len(seq)))
        e += sum(jump_cost(seq[t - 1], seq[t], P1, P2) for t in range(1, len(seq)))
        if best is None or e < best:
            best = e
    return best


def test_path_cost_is_the_chain_minimum_minus_the_subtracted_minima():
    rng = random.Random(1)
    for _ in range(40):
        H, W, D = rng.randint(1, 3), rng.randint(1, 4), rng.randint(1, 4)
        C = random_volume(rng, H, W, D)
        P1 = rng.randint(0, 4)
        P2 = P1 + rng.randint(0, 6)
        r = rng.choice(DIRECTIONS_16)
        L = path_cost(C, P1, P2, r)
        for v in range(H):
            for u in range(W):
                path = [(u, v)]  # walk back along -r to the border
                while True:
                    pu, pv = path[-1][0] - r[0], path[-1][1] - r[1]
                    if not (0 <= pu < W and 0 <= pv < H):
                        break
                    path.append((pu, pv))
                path.reverse()
                offset = sum(min(L[pv][pu]) for (pu, pv) in path[:-1])
                costs = [C[pv][pu] for (pu, pv) in path]
                for d in range(D):
                    assert L[v][u][d] + offset == chain_minimum(costs, P1, P2, d)


def test_bounds_of_the_path_cost():
    rng = random.Random(2)
    for _ in range(30):
        H, W, D = rng.randint(1, 5), rng.randint(1, 5), rng.randint(1, 6)
        C = random_volume(rng, H, W, D, hi=50)
        P1 = rng.randint(0, 10)
        P2 = P1 + rng.randint(0, 30)
        cmax = max(max(max(c) for c in row) for row in C)
        for r in DIRECTIONS_8:
            L = path_cost(C, P1, P2, r)
            for v in range(H):
                for u in range(W):
                    for d in range(D):
                        assert C[v][u][d] <= L[v][u][d] <= C[v][u][d] + P2 <= cmax + P2


def test_zero_penalties_give_winner_takes_all():
    rng = random.Random(3)
    C = random_volume(rng, 4, 5, 6)
    assert sgm(C, 0, 0) == winner_takes_all(C)


def test_one_direction_on_one_row_is_exact_at_the_end():
    rng = random.Random(4)
    for _ in range(30):
        W, D = rng.randint(1, 5), rng.randint(2, 4)
        C = random_volume(rng, 1, W, D)
        P1, P2 = 2, 5
        S = aggregate(C, P1, P2, [(1, 0)])
        best = min(chain_minimum(C[0], P1, P2, d) for d in range(D))
        offset = sum(min(path_cost(C, P1, P2, (1, 0))[0][u]) for u in range(W - 1))
        assert min(S[0][W - 1]) + offset == best


def make_pair(rng, W, H, dmap, noise):
    """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)]
        rrow = [min(255, max(0, x + rng.randint(-noise, noise))) for x in rrow]
        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 accuracy(disp, truth):
    good = total = 0
    for drow, trow in zip(disp, truth):
        for d, t in zip(drow, trow):
            if t is not None:
                total += 1
                good += d == t
    return good / total


def test_recovers_a_noisy_step_better_than_winner_takes_all():
    rng = random.Random(5)
    W, H, D = 32, 16, 8
    dmap = [[2 if u < 14 else 6 for u in range(W)] for _ in range(H)]
    left, right, truth = make_pair(rng, W, H, dmap, noise=30)
    C = absolute_difference_volume(left, right, D)
    wta = accuracy(winner_takes_all(C), truth)
    acc = accuracy(sgm(C, 20, 200), truth)
    assert wta < 0.6  # the noise makes single pixels unreliable
    assert acc >= 0.93
    assert accuracy(sgm(C, 20, 200, DIRECTIONS_2), truth) < acc


def test_direction_sets():
    assert len(DIRECTIONS_2) == 2 and len(DIRECTIONS_4) == 4
    assert len(DIRECTIONS_8) == 8 and len(DIRECTIONS_16) == 16
    assert len(set(DIRECTIONS_16)) == 16
    for (du, dv) in DIRECTIONS_16:
        assert (-du, -dv) in DIRECTIONS_16

History

Hirschmüller presented semi-global matching at CVPR 2005, with mutual information as the matching cost. The journal version of 2008 gave the energy, the path recursion with the subtraction and its bound, the advice on the number of paths and the adaptive P2P_2. The idea of aggregating 1D programs builds on scanline optimization and on dynamic programming stereo. SGM became one of the most used stereo methods in practice, and it was implemented in hardware for real time use.

References

  1. Heiko Hirschmüller, Stereo processing by semiglobal matching and mutual information, IEEE Transactions on Pattern Analysis and Machine Intelligence 30(2), 2008, 328-341, Equation 11 (the energy with the penalties P1 and P2), Equation 12 (the recursion of the path cost), Equation 13 (the same recursion with the minimum of the previous pixel subtracted), the bound L <= Cmax + P2, the advice that the number of paths must be at least 8 and should be 16, and the adaptation of P2 to the intensity gradient
  2. Heiko Hirschmüller, Accurate and efficient stereo processing by semi-global matching and mutual information, IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR 2005), 807-814, the first presentation of the method
  3. 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, the scanline optimization (SO) method, a single horizontal pass of the same kind of recursion
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (semi-global matching among the global and semi-global methods)

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