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.
- Solves
- Stereo matching
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , the cost of giving pixel the disparity . Along a straight line through the image, a dynamic program finds the best disparity sequence under a smoothness model with two penalties: a small for a change of one disparity step, and a large 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 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 for the pixels of a image and the disparities , penalties , and a set 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
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 , the path cost of pixel is
with when is outside the image.
SGM(C, P1, P2, R)- 1
S(p, d) ← 0 for all pixels p and disparities d - 2
for each direction r in R do - 3
for each pixel p, in an order that visits p - r before p do - 4
if p - r is outside the image then L_r(p, d) ← C(p, d) for all d - 5
else m ← min over k of L_r(p - r, k) - 6
for 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 - 7
S(p, d) ← S(p, d) + L_r(p, d) for all d - 8
for each pixel p: f_p ← the least d with the least S(p, d) - 9
return f
The 8 directions are the horizontal, vertical and diagonal steps in both senses; the 16 directions add the eight knight moves such as . The subtraction of in line L6 does not change which is best along the path, but it keeps the values bounded.
Example
A row of three pixels with , , and the costs below. The middle pixel is noisy: alone, its best disparity is 1, while its neighbors clearly want 0.
| pixel | 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 and : for the best is , so ; for it is , so ; for it is , so . At pixel 2, is subtracted: . The sum picks disparity 0 at pixel 1, where winner-takes-all on 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 , with equal to 0, or . The subtraction removes a constant from all at each pixel, and the constants add up along the ray, so equals the least chain energy of the ray ending at with disparity , minus a number that does not depend on . Each step adds a value between 0 and to , which gives the bound .
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 and pixel , the path cost equals, up to a constant that does not depend on , the least energy of a disparity sequence along the ray that ends at with disparity ; and its values stay in . Then and the winner-takes-all step are plain sums and minima.
Setup
The cost volume gives for . Fix a direction and a pixel . Walking back from by until the next step would leave the image gives the ray with . Define the jump cost if , if , and otherwise, with . (With the usual choice this is for a jump of one.) The chain energy of a sequence is
and is its least value over all sequences with .
Lemma 1 (the recursion without subtraction)
, and for
Proof. A sequence ending with at is a sequence ending with some at , followed by the jump from to and the cost . The best choice of the earlier part, for a fixed , has energy . Take the least value over .
Lemma 2 (the four candidates)
For any vector over the disparities with ,
where the terms are left out if the index is outside the range.
Proof. Call the two sides and . The terms of are for , for , and for the other .
: each term of is at least some term of . is a term of . If , then ; otherwise it is . And .
: each term of is at least some term of . is a term of . . Finally, let attain ; since , the term of is at most .
Lemma 3 (the subtraction only shifts)
Let be computed by the algorithm, with . Then for all and ,
Proof. By induction on . For both sides are (line L4). For , line L6 computes , where by Lemma 2 the minimum equals . By the induction hypothesis is minus a constant , and a constant shift passes through the minimum. With Lemma 1,
So for each pixel and direction, and the exact chain minimum differ by a constant, and they have the same order over . The code visits rows in the order of the sign of the row step of and columns in the order of the sign of its column step; then is visited before , 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 and , . In particular , where is the largest cost.
Proof. At the first pixel of a ray, . Otherwise, with and , the value added to is . Every candidate is at least , because , so the value is at least 0. The last candidate is , so the value is at most .
This is the bound 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 over the directions, and line L8 takes the least with the least sum. Both are exact. By Lemmas 3 and 4, with independent of , so the winner-takes-all choice is the that minimizes the sum over the directions of the exact chain minima ending at with disparity . Since each appears once in every , this sum counts the data cost of itself times; this is part of the definition of the method and does not change with the subtraction.
Cost
For each direction, each of the pixels takes one minimum over values and updates with four candidates, which is . So the path costs of directions take time, and the sum needs memory.
Complexity
The model is the word RAM with integer costs.
- Time. Each direction does work per pixel, so per direction and in total. The time does not depend on the data.
- Space. for , plus the cost volume. A direction needs only the previous pixel of each path, so the path costs of one direction take 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, , 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 allows slanted surfaces, and a large 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 . Hirschmüller (2008) divides by the intensity difference of the neighbors along the path, , keeping , 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 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.
- . Then a jump of one costs more than a large jump, and the model no longer makes sense. Keep , also after adapting .
- Order of traversal. For each direction, must be computed before . With diagonal and knight directions, choose the order of rows and columns from the signs of the direction.
- Penalties and cost scale. and 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.
# 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 . 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NJ87X5 Edit this page History Report an error Markdown