Algorithmcore
Dynamic programming stereo
Match each pair of scanlines separately by dynamic programming over monotone matchings, with a cost for each occluded pixel, in O(W D) time per line.
- Solves
- Stereo matching
- Time
- Θ(W H D) worst · average · best
- Space
- Θ(W D) extra
- Where
- D = the number of disparities; H = the image height in pixels; W = the image width in pixels
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Yuichi Ohta, Takeo Kanade, 1985
Dynamic programming stereo solves stereo matching one scanline at a time. In a rectified pair, a pixel of a left row can only match a pixel of the same right row, a few columns to the left. The method looks for the best matching of the two rows as a whole, not pixel by pixel. A matching pairs left and right pixels in the same order in both rows (the ordering constraint), uses each pixel at most once, and leaves some pixels unmatched; these are the occluded pixels, which one camera sees and the other does not. Each matched pair pays a matching cost and each unmatched pixel pays a fixed occlusion cost . The best matching is a cheapest monotone path through a grid, the same structure as in edit distance and sequence alignment, and dynamic programming finds it exactly. Only a band of width around the diagonal is needed, so a row costs time and an image . The method was a standard global stereo method before semi-global matching and graph cuts; its main weakness is that the rows are solved independently, which leaves horizontal streaks.
In plain words
Take one row of the left image and the same row of the right image. You want to say which pixel on the left is which pixel on the right. Walk along both rows from left to right at the same time. At each step you either pair the next left pixel with the next right pixel, paying for how different they look, or you skip one pixel in one of the rows, paying a fixed price because that pixel is hidden in the other view. Pixels stay in the same order, so you never go back. A table that stores the best price for every pair of positions finds the cheapest walk. The distance between paired pixels is the disparity. Do this for every row.
The problem
Input. A rectified pair of images of width and height , a number of disparities, a match cost for two intensities, such as , and an occlusion cost . As on the other stereo pages, left pixel of a row may match right pixel of the same row with disparity .
Output. For each row, a matching : a set of pairs with that is strictly increasing in both and , with least cost
Each matched left pixel gets disparity . An unmatched left pixel is marked occluded.
The algorithm
is the least cost of matching the first left pixels with the first right pixels. Only points with are stored, as with .
DP-STEREO-LINE(l, r, D, κ)- 1
C(0, 0) ← 0 - 2
for i ← 0 to W do - 3
for k ← min(D - 1, i) down to 0 do (j = i - k; skip the point (0, 0)) - 4
match ← C(i - 1, j - 1) + c(l[i - 1], r[j - 1]) if j ≥ 1 - 5
left ← C(i - 1, j) + κ if k ≥ 1 - 6
right ← C(i, j - 1) + κ if j ≥ 1 and k + 1 ≤ D - 1 - 7
C(i, j) ← the least of these, and remember which one it was - 8
walk back from (W, W) to (0, 0) along the remembered steps; each match step into (i, j) sets d[i - 1] ← i - j - 9
return C(W, W) and d, with the unmatched left pixels marked occluded
A match step keeps , a left step raises it by 1 and a right step lowers it by 1. This is why runs downward in line L3: the right step reads of the same . The full image calls the procedure once per row.
Example
Take one row with , , , and . The right row is the left row moved one pixel to the left, with a new pixel at its end.
| point | match | left | right | |
|---|---|---|---|---|
| (1, 0) | 2 | |||
| (1, 1) | 4 | |||
| (2, 1) | 2 | |||
| (2, 2) | 4 | |||
| (3, 2) | 2 | |||
| (3, 3) | 4 | |||
| (4, 3) | 2 | |||
| (4, 4) | 4 |
The walk back from is: a right step (right pixel 3 is unmatched), match steps into , and , and a left step (left pixel 0 is unmatched). The result is with cost 4: three exact matches and two occluded pixels. Matching all pixels at disparity 0 would cost . Left pixel 0 is the strip at the left border that the right camera does not see.
Correctness
The full proof is in proofs/correctness.md. A matching is the same thing as a monotone path from to made of match, left and right steps, and the cost of the path is the cost of the matching. Every matching has such a path inside the band when : between two matches, first move the difference to the next value and then alternate left and right steps next to it. The last step into is one of three steps, so lines L4 to L7 give the least cost of a path to by induction, in an order in which all three inputs are already final. The walk back follows steps that attain the minimum, so it returns a path, and hence a matching, of the least cost .
Proof: Correctness of dynamic programming stereo on a scanlinefull
Fix one row of width , the left intensities , the right intensities , a disparity range , an occlusion cost and a match cost . A matching is a set of pairs with that is strictly increasing in both coordinates. Its cost is , since pixels of each image stay unmatched. We prove that the program returns a matching of least cost.
Paths and matchings
A path is a sequence of grid points from to in which each step is one of: a match step , allowed only if , with cost ; a left step with cost (left pixel unmatched); a right step with cost (right pixel unmatched). The match steps of a path, read as pairs , form a matching, because and only grow and a match step raises both. Each left pixel is passed by exactly one step that raises , so it is either matched once or skipped once by a left step, and the same holds for right pixels. So the cost of a path equals the cost of its matching. Conversely, every matching is the matching of some path: visit its pairs in order and, between two consecutive pairs and at the two ends, add the needed left and right steps.
The band lemma
Call in the band if . Claim: every matching is the matching of a path that stays in the band.
Let be the point just after a match (or ), and the point where the next match starts (or ). Both points are in the band: a match step keeps , and the ends have . Let and . Between them we need left steps, each raising by 1, and right steps, each lowering it by 1, with . First take steps of the needed kind to move from to ; all the values on the way lie between and , so in the band. The steps left over come in pairs of one left and one right step. Since , either or ; in the first case do each pair as left then right, and in the second as right then left. The difference then moves between and a neighbor in the band. So the whole path stays in the band. (With the band is the diagonal, and no pixel could be skipped; that is why the code requires .)
So the least cost of a matching equals the least cost of a path in the band.
The recurrence
Let be the least cost of a path in the band from to . Then , and for every other point in the band the last step of such a path is a match step from , a left step from or a right step from , from a point that must itself be in the band. Removing the last step leaves a path in the band to that point, so
over the terms whose start point exists and is in the band. These are the three candidates of lines L4 to L6: the match from has the same ; the left step comes from and needs ; the right step comes from in the same and needs and .
The loops visit in increasing order and, for each , in decreasing order. The point belongs to an earlier , and has the larger in the same , so every term is final when it is read. By induction over this order, the table holds at every point, and is the least cost of a matching.
The traceback
Line L7 stores which candidate gave the minimum. Starting at , line L8 follows the stored steps back. Each stored step leads to a point whose value plus the step cost equals the current value, so the steps form a path from to in the band of cost exactly . Its match steps are the returned matching, and each match gives the disparity of left pixel . By the first section this matching has cost , the least possible.
Cost
There are table entries, each found in time from three earlier entries, and the traceback has at most steps. So one row costs time and space, and an image of rows costs time.
Complexity
The model is the word RAM with integer intensities and costs.
- Time. Each row has table entries, each found in , and the walk back has at most steps: per row and per image, the size of the cost volume. The time does not depend on the data, so the worst, average and best cases are the same.
- Space. for the table and the remembered steps of one row, besides the output.
Properties
- Exact per row. The result is a least cost matching of each row, not an approximation.
- Occlusions in the model. Unmatched pixels are part of the answer. The strip at the left border that the right camera does not see can come out as occluded, as in the example, with no special code.
- Ordering constraint. Matches keep their order. This holds for most scenes, but fails for thin objects in front of a far background, such as a pole, where the order of points is different in the two views.
- Rows are independent. No term ties a row to the next one, so errors differ from row to row and show up as horizontal streaks.
- Uniqueness. Each pixel is matched at most once, in both images.
Variants and improvements
- Intervals instead of pixels. Ohta and Kanade (1985) matched intervals between edges and added an inter-scanline search over connected edges, which ties adjacent rows.
- Ties between rows. Cox et al. (1996) and later authors add costs for disparity jumps, also across rows, or use the edges of the image to guide where a jump may happen.
- Sampling-insensitive costs. Birchfield and Tomasi (1999) used a dissimilarity that does not change when the pixel grid is shifted by part of a pixel.
- Scanline optimization. The SO method of Scharstein and Szeliski (2002) drops the occlusion model and instead runs a Viterbi pass over the disparity labels of one row, with a cost for each jump. Semi-global matching runs such passes along 8 or 16 directions and adds them, which removes most streaks.
- Global methods. Graph cut stereo minimizes an energy with occlusions over the whole image at once.
When to use it
Use it when you need a fast method with an explicit model of occlusion along the baseline, for example on small embedded systems or as a teaching example of global stereo. For better quality at a similar cost, use semi-global matching. Use block matching when you need the simplest local method.
Pitfalls
- Disparity range of one. With the band is only the diagonal, so no pixel can be skipped and the band lemma fails. Use , or treat on its own.
- The direction of the shift. The code assumes that left pixel matches right pixel with . With the cameras the other way round, swap the images or mirror the rows.
- Choosing . A small makes skipping cheaper than matching, and the result is mostly occluded. A large forces matches, also in true occlusions. Set against the typical cost of a correct match.
- Streaks. Do not expect smooth results in the vertical direction. Filter the result across rows, or use a method that ties the rows.
- Thin foreground objects. The ordering constraint makes the method miss them; a left-right consistency check does not fix that.
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/scanline-dynamic-programming-stereo/. The authors are listed in prov/ZQ13H8.jsonl.
"""Dynamic programming stereo on each scanline, with occlusions.
The pair is rectified, and the left pixel i of a row matches the right
pixel j = i - d of the same row, with the disparity d in [0, D). A matching
of one row is a set of pairs (i, j) with 0 <= i - j < D that is strictly
increasing in both i and j: no pixel is matched twice (uniqueness), and
the order of the pixels is the same in both images (ordering). Its cost is
sum over the matched pairs of c(l[i], r[j]) + kappa * (unmatched pixels),
where the unmatched pixels of both images count, so a row of width W with
M matches has 2 (W - M) unmatched pixels. The default c is the absolute
difference. A matching is a monotone path from (0, 0) to (W, W) in the
grid of prefixes, and the dynamic program over the band 0 <= i - j < D
finds the cheapest one in O(W D) time.
"""
from __future__ import annotations
from typing import Callable, List, Optional, Sequence, Tuple
INF = float("inf")
START, MATCH, LEFT_OCC, RIGHT_OCC = 0, 1, 2, 3
def absolute_difference(a: float, b: float) -> float:
return abs(a - b)
def scanline_dp(lrow: Sequence[float], rrow: Sequence[float], D: int,
kappa: float,
cost: Callable[[float, float], float] = absolute_difference
) -> Tuple[float, List[Optional[int]], List[Tuple[int, int]]]:
"""Return (least cost, disparity of each left pixel or None if it is
unmatched, the matched pairs (i, j) in increasing order).
The state (i, j) is the cost of matching the prefixes l[:i] and r[:j];
it is stored as C[i][k] with k = i - j in [0, D). The band needs
D >= 2: with D = 1 a path in the band could not skip any pixel."""
W = len(lrow)
if len(rrow) != W or D < 2:
raise ValueError("rows must have the same width and D >= 2")
C = [[INF] * D for _ in range(W + 1)]
move = [[START] * D for _ in range(W + 1)]
C[0][0] = 0 # @line L1
for i in range(W + 1): # @line L2
for k in range(min(D - 1, i), -1, -1): # @line L3
j = i - k
if i == 0:
continue
best, how = INF, START
if j >= 1: # pair (i - 1, j - 1) has the same k # @line L4
c = C[i - 1][k] + cost(lrow[i - 1], rrow[j - 1]) # @line L4
if c < best:
best, how = c, MATCH
if k >= 1: # left pixel i - 1 unmatched, from (i - 1, j) # @line L5
c = C[i - 1][k - 1] + kappa # @line L5
if c < best:
best, how = c, LEFT_OCC
if j >= 1 and k + 1 <= D - 1: # right pixel j - 1 unmatched # @line L6
c = C[i][k + 1] + kappa # @line L6
if c < best:
best, how = c, RIGHT_OCC
C[i][k], move[i][k] = best, how # @line L7
disp: List[Optional[int]] = [None] * W
pairs: List[Tuple[int, int]] = []
i, k = W, 0
while i > 0 or k > 0: # walk back from (W, W) # @line L8
how = move[i][k]
if how == MATCH:
disp[i - 1] = k # @line L8
pairs.append((i - 1, i - 1 - k))
i -= 1
elif how == LEFT_OCC:
i, k = i - 1, k - 1
else:
k += 1
pairs.reverse()
return C[W][0], disp, pairs # @line L9
def matching_cost(lrow, rrow, pairs, kappa, cost=absolute_difference) -> float:
"""The cost of a given matching of one row."""
W = len(lrow)
return (sum(cost(lrow[i], rrow[j]) for (i, j) in pairs)
+ kappa * 2 * (W - len(pairs)))
def is_valid_matching(pairs, W: int, D: int) -> bool:
"""Pairs in range, in the band, and strictly increasing in i and j."""
for t, (i, j) in enumerate(pairs):
if not (0 <= j <= i < W and i - j < D):
return False
if t and not (pairs[t - 1][0] < i and pairs[t - 1][1] < j):
return False
return True
def dp_stereo(left: Sequence[Sequence[float]], right: Sequence[Sequence[float]],
D: int, kappa: float,
cost: Callable[[float, float], float] = absolute_difference
) -> List[List[Optional[int]]]:
"""Run the scanline program on every row; None marks unmatched pixels."""
return [scanline_dp(lrow, rrow, D, kappa, cost)[1]
for lrow, rrow in zip(left, right)]
test_scanline_dynamic_programming_stereo.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/scanline-dynamic-programming-stereo/. The authors are listed in prov/ZQ13H8.jsonl.
import random
from scanline_dynamic_programming_stereo import (
dp_stereo,
is_valid_matching,
matching_cost,
scanline_dp,
)
def all_matchings(W, D):
"""Every matching of one row: strictly increasing pairs in the band."""
out = []
def grow(last_i, last_j, cur):
out.append(list(cur))
for i in range(last_i + 1, W):
for j in range(max(last_j + 1, i - D + 1), i + 1):
cur.append((i, j))
grow(i, j, cur)
cur.pop()
grow(-1, -1, [])
return out
def test_least_cost_equals_brute_force():
rng = random.Random(1)
for _ in range(400):
W, D = rng.randint(1, 6), rng.randint(2, 4)
lrow = [rng.randint(0, 9) for _ in range(W)]
rrow = [rng.randint(0, 9) for _ in range(W)]
kappa = rng.choice([0, 1, 2, 3, 5, 10])
best, disp, pairs = scanline_dp(lrow, rrow, D, kappa)
assert is_valid_matching(pairs, W, D)
assert matching_cost(lrow, rrow, pairs, kappa) == best
brute = min(matching_cost(lrow, rrow, m, kappa) for m in all_matchings(W, D))
assert best == brute
for (i, j) in pairs:
assert disp[i] == i - j
assert sum(d is not None for d in disp) == len(pairs)
def test_worked_example():
lrow = [4, 5, 9, 1, 7, 7]
rrow = [5, 9, 1, 7, 7, 3]
best, disp, pairs = scanline_dp(lrow, rrow, 3, 2)
assert best == 4
assert disp == [None, 1, 1, 1, 1, 1]
assert pairs == [(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
def make_pair(rng, W, H, dmap, noise=0):
"""Left rows of random texture; the right row shows, at each column j,
the left pixel u with u - d(u) = j of the largest disparity (the
nearest surface). Columns that no left pixel reaches get new texture.
Returns (left, right, truth) where truth is None at left pixels that
are hidden in the right image."""
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 test_recovers_a_step_with_occlusion():
rng = random.Random(7)
W, H, D = 40, 6, 8
dmap = [[2 if u < 18 else 6 for u in range(W)] for _ in range(H)]
left, right, truth = make_pair(rng, W, H, dmap, noise=3)
disp = dp_stereo(left, right, D, kappa=20)
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
def test_rows_are_independent():
rng = random.Random(3)
left = [[rng.randint(0, 9) for _ in range(7)] for _ in range(3)]
right = [[rng.randint(0, 9) for _ in range(7)] for _ in range(3)]
disp = dp_stereo(left, right, 3, 2)
for v in range(3):
assert disp[v] == scanline_dp(left[v], right[v], 3, 2)[1]
def test_large_kappa_matches_everything_and_zero_kappa_matches_nothing():
rng = random.Random(4)
for _ in range(50):
W = rng.randint(1, 8)
lrow = [rng.randint(0, 9) for _ in range(W)]
rrow = [rng.randint(0, 9) for _ in range(W)]
_, disp, pairs = scanline_dp(lrow, rrow, 3, 100)
assert len(pairs) == W and disp == [0] * W
best, _, pairs = scanline_dp(lrow, rrow, 3, 0)
assert best == 0
History
Ohta and Kanade (1985) introduced dynamic programming for stereo: they matched intervals between edges on pairs of scanlines and searched across scanlines as well. Cox, Hingorani, Rao and Maggs (1996) derived a pixel-based cost with a fixed price per occluded pixel from a maximum likelihood model and minimized it by dynamic programming per row. Birchfield and Tomasi (1999) combined this kind of program with their sampling-insensitive dissimilarity to find depth discontinuities. Scharstein and Szeliski (2002) included dynamic programming and scanline optimization in their taxonomy and measured them on a common benchmark against local methods and graph cuts.
References
- Yuichi Ohta and Takeo Kanade, Stereo by intra- and inter-scanline search using dynamic programming, IEEE Transactions on Pattern Analysis and Machine Intelligence PAMI-7(2), 1985, 139-154, the matching of the edge intervals of a pair of scanlines as a path search by dynamic programming, and the inter-scanline search that ties the paths of adjacent lines
- Ingemar J. Cox, Sunita L. Hingorani, Satish B. Rao and Bruce M. Maggs, A maximum likelihood stereo algorithm, Computer Vision and Image Understanding 63(3), 1996, 542-567, the cost of a matching of two scanlines with occluded pixels, derived as a maximum likelihood, and its minimization by dynamic programming
- Stan Birchfield and Carlo Tomasi, Depth discontinuities by pixel-to-pixel stereo, International Journal of Computer Vision 35(3), 1999, 269-293, the pixel-to-pixel dynamic program with occlusions, and the use of a dissimilarity that is insensitive to image sampling
- 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 dynamic programming (DP) and scanline optimization (SO) methods of the taxonomy and their results on the benchmark
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (global optimization and dynamic programming along scanlines)
Where this leads
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 ZQ13H8 Edit this page History Report an error Markdown