Algorithmintro
Block matching stereo
Also called window-based stereo, SAD block matching.
Give each pixel the disparity whose window in the other image has the least sum of absolute or squared differences.
- Solves
- Stereo matching
- Time
- Θ(W H D) worst · average · best
- Space
- Θ(W H) 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
- Daniel Scharstein, Richard Szeliski, 2002
Block matching stereo gives each pixel of the left image the disparity for which the square window around it best matches the window around column in the right image, measured by the sum of absolute differences (SAD) or of squared differences (SSD). It is the simplest local method for stereo matching: a pixel matching cost, a box aggregation of the cost, and winner-takes-all over the disparities. With an integral image or running sums the window sums cost each, so the whole method takes time on the word RAM, independent of the window size. It differs from template matching, which searches one template over a whole image in two dimensions; here every pixel has its own window and the search is along one row.
In plain words
Take a small square around a pixel of the left image, say 7 by 7 pixels. Slide the same square along the same row of the right image, one pixel at a time, and at each place add up how different the two squares are. The place with the smallest total is the match, and the number of pixels slid is the disparity. Do this for every pixel. A larger square sees more texture and makes fewer wild mistakes, but it blurs the edges of objects. A smaller square keeps the edges but gets confused where the image is plain.
The problem
Input. A rectified pair of grayscale images and of pixels with integer values of bits, the right camera to the right of the left one. A window radius and a number of disparities . Pixel is in column and row ; in code it is img[v][u].
Output. For each left pixel the disparity
with the pixel cost for SAD, or its square for SSD, and with positions outside the image clamped to the nearest border pixel (written with bars). The outer breaks ties toward the smallest disparity. The definitions at the border are choices of the code; other programs leave a frame of pixels, and the first columns, without a value.
The algorithm
BLOCK-MATCH(L, R, D, r)- 1
for each pixel p do best[p] ← ∞; disp[p] ← 0 - 2
for d ← 0 to D - 1 do - 3
e(u, v) ← |L(u, v) - R(max(u - d, 0), v)| for every pixel ▷ or the square - 4
S ← the integral image of e, padded by r on each side by copying the border - 5
for each pixel p = (u, v) do - 6
c ← S[v + k][u + k] - S[v][u + k] - S[v + k][u] + S[v][u] ▷ k = 2r + 1 - 7
if c < best[p] then best[p] ← c; disp[p] ← d - 8
return disp
The loop over disparities is outside, so only one image of pixel costs and one integral image are alive at a time, together with the best cost and disparity of each pixel. Line L4 builds the integral image , the sum of the padded cost image over the rows before and the columns before . Line L6 reads the window sum with four lookups, the identity of the integral image page. Line L7 keeps the smallest cost so far, and the strict test keeps the first, smallest disparity on ties. The same loop with running sums along rows and columns, or with a box blur of , gives the same sums.
Example
Take three equal rows, so the window of only sums each column three times. The left row is and the right row , the left row shifted by one, and . The window costs at the middle row are:
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| 120 | 240 | 480 | 360 | 240 | 0 | |
| 0 | 0 | 0 | 0 | 0 | 0 | |
| 0 | 120 | 240 | 480 | 360 | 240 | |
| 1 | 1 | 1 | 1 | 1 | 0 |
At , the pixel alone gives the costs , and the window gives : the texture at columns 2 to 4 makes the minimum clear. At , the window covers columns 4 and 5 (column 6 is clamped to 5), which are all 10 in both images at and . The tie goes to , which is wrong. At the costs at and both use column 0 of the right image, by the border rule, and are both 0; the tie goes to , which is right by luck. These are the two classic failures: no texture, and the left border, where the true match is outside the right image.
Correctness
The full proof is in proofs/correctness.md. It has two parts. First, line L6 returns : the padded image at row and column is at the clamped position , so the window of in the original image is the block of rows to and columns to of the padded image, and the four lookups give the sum of that block. Second, the loop of line L2 keeps the invariant that after the disparities , is the least of and is the least disparity that reaches it. At the end this is .
Proof: Correctness of block matching stereofull
We prove that BLOCK-MATCH returns, for each left pixel , the least disparity in with the least window cost , where , , and is the pixel cost of line L3.
Lemma 1. Line L6 returns
Let be the padded image of line L4: it has rows and columns, and . Let for and .
The code builds row by row: with the running sum of row , it sets and . By induction on , this is the sum above.
For any and , the block of rows and columns has the sum , by inclusion and exclusion: the first term counts the block together with the rows above it and the columns left of it, the next two terms remove those, and the last term adds back the corner that was removed twice.
With , , , , , the block is for , and
So line L6 returns exactly .
Lemma 2. The loop invariant of line L2
Invariant. Before the iteration for disparity , for every pixel : (or if ), and is the least with (or 0 if ).
Start. Line L1 sets and , which is the claim for .
Step. In the iteration for , line L6 gives by Lemma 1. If , then is the new least value and is the only disparity so far that reaches it, so the update of line L7 restores the invariant for . If , the least value does not change, and the least disparity that reaches it is still , because any earlier disparity is less than . So the invariant holds for without a change. The pixels are independent of each other, so the order of line L5 does not matter.
End. After the iteration for , is the least in with , which is .
Theorem
BLOCK-MATCH returns for every pixel. This follows from Lemma 2 at the end of the loop. It holds for SAD and SSD alike, because the proof uses only the values of , and for any other pixel cost put in line L3.
What the theorem does not say
The theorem says that the code returns the minimizer of the window cost. It does not say that this minimizer is the true disparity. Where a window holds two depths, where the image has no texture, or where the true match is hidden or outside the right image, the minimizer can be wrong while the code is correct. The tests show both: the code equals the brute force definition on random images, and it recovers the true disparity away from depth edges and borders on synthetic scenes.
Exactness
All quantities are integers. The largest value is an entry of , at most . On the word RAM with words of bits it fits if , so the computation is exact, with no rounding.
Complexity
The model is the word RAM. An SAD window sum is at most , and an SSD sum at most , and an integral image entry at most times the largest pixel cost. With 8-bit pixels and images of a few million pixels these fit a 64-bit word.
- Time. For each of the disparities, lines L3, L4 and L5 to L7 take time for less than and , so the total is . The window size does not appear, which is the point of the integral image.
- Space. One cost image, one integral image of words, and two arrays of entries: extra space. A program that stores the full cost volume needs instead.
- Brute force. Summing each window directly takes time. The code has it as the reference for the tests.
Properties
- Box support. Every pixel of the window counts the same. This assumes that all pixels of the window have the same disparity, which is false near depth edges (a heuristic assumption).
- Foreground fattening. Near a depth edge, the window of a background pixel contains part of the near object, which has strong texture and a larger disparity. The near object then wins, and the disparity map shows the object larger than it is, by up to pixels. This is a known failure of box windows, measured in the benchmark of Scharstein and Szeliski.
- No smoothness. Each pixel decides alone. Neighbors agree only because their windows overlap.
- SAD or SSD. SSD is the maximum likelihood cost for Gaussian noise; SAD is less hurt by single outliers. Neither tolerates a change of brightness between the cameras, for which the census transform or normalized cross-correlation is better.
Variants and improvements
- Other costs. Replace the pixel cost of line L3 by the census Hamming distance, the Birchfield-Tomasi cost, or a truncated difference. The rest of the method is unchanged.
- Zero mean and normalized windows. Subtract the window mean (ZSAD, ZSSD) or use normalized cross-correlation, to cancel an offset or a gain between the cameras.
- Weighted windows. Weight the pixels of the window by their similarity to the center, as in adaptive support weights or the guided filter of Hosni et al. (2013). This reduces foreground fattening at a higher cost per pixel or with a more complex filter.
- Shiftable and multiple windows. Take the best of several windows that contain the pixel but are not centered on it, so a pixel near an edge can use a window that stays on its own side.
- Adaptive window size. Kanade and Okutomi (1994) chose the window size per pixel from the local texture and disparity variation.
- Post-processing. A left-right consistency check, a test on the texture of the window, a uniqueness test on the ratio of the best and second best costs, subpixel refinement and a median filter of the map. OpenCV's StereoBM is block matching with such tests.
When to use it
Use block matching when speed and simplicity matter more than quality: on small processors, as a first estimate for a slower method, or on images with rich texture. It runs in real time with SIMD instructions because every step is integer adds. Use semi-global matching when the scene has large textureless areas or many depth edges, and an edge-aware aggregation when you want a local method that keeps edges.
Pitfalls
- Window size. No single size works everywhere: small windows fail in flat areas, large ones fatten objects. Choose it for the data, and say so; typical sizes are 5 by 5 to 21 by 21.
- Left border. For the true match is outside the right image. Mark the first columns invalid, or at least do not trust them.
- Ties and flat areas. In a flat area all costs are equal, and the tie rule picks the answer. Report such pixels as invalid by a texture test.
- Overflow. SSD sums of 8-bit images over large windows exceed 16 and 32 bits quickly. Check the bound in the complexity section for your word size.
- Unrectified input. The method assumes that matches lie in the same row. A rectification error of one pixel already hurts, so check the vertical offset of known matches.
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/block-matching-stereo/. The authors are listed in prov/VSCW79.jsonl.
"""Block matching stereo: the sum of absolute (or squared) differences over
a square window, and winner-takes-all over the disparities.
An image is a list of rows of integers; the value at pixel (u, v), column u
and row v, is img[v][u]. The pair is rectified and the right camera is to
the right of the left one, so the left pixel (u, v) matches the right
pixel (u - d, v) with d >= 0.
Definitions used by both the fast and the brute force code:
- e_d(u, v) = |L(u, v) - R(max(u - d, 0), v)| (or its square): the cost of
one pixel. A right column left of the image takes the value of column 0.
- The window cost S_d(u, v) is the sum of e_d over the (2r + 1) x (2r + 1)
window centered on (u, v), where a position outside the image takes the
value of e_d at the nearest border pixel (the coordinates are clamped).
- The disparity of (u, v) is the least d in [0, D) with the least S_d(u, v).
"""
from __future__ import annotations
from typing import List, Sequence
def _clamp(x: int, lo: int, hi: int) -> int:
return lo if x < lo else hi if x > hi else x
def pixel_cost(left: Sequence[Sequence[int]], right: Sequence[Sequence[int]],
d: int, squared: bool = False) -> List[List[int]]:
"""The image e_d of the costs of single pixels at disparity d."""
h, w = len(left), len(left[0])
out = []
for v in range(h):
lrow, rrow = left[v], right[v]
row = []
for u in range(w):
x = lrow[u] - rrow[u - d if u >= d else 0]
row.append(x * x if squared else abs(x))
out.append(row)
return out
def padded_integral(e: Sequence[Sequence[int]], r: int) -> List[List[int]]:
"""The integral image S of e padded by r pixels on each side by
copying the border. S has (H + 2r + 1) rows and (W + 2r + 1) columns,
and S[y][x] is the sum of the padded image over rows < y and columns
< x."""
h, w = len(e), len(e[0])
ph, pw = h + 2 * r, w + 2 * r
S = [[0] * (pw + 1) for _ in range(ph + 1)]
for y in range(ph):
src = e[_clamp(y - r, 0, h - 1)]
acc = 0
above, cur = S[y], S[y + 1]
for x in range(pw):
acc += src[_clamp(x - r, 0, w - 1)]
cur[x + 1] = above[x + 1] + acc
return S
def block_match(left: Sequence[Sequence[int]], right: Sequence[Sequence[int]],
D: int, r: int, squared: bool = False) -> List[List[int]]:
"""The disparity map of block matching with a (2r + 1) x (2r + 1)
window and D disparities, in Theta(W H D) time."""
if D < 1 or r < 0:
raise ValueError("need D >= 1 and r >= 0")
h, w = len(left), len(left[0])
k = 2 * r + 1
best = [[None] * w for _ in range(h)] # @line L1
disp = [[0] * w for _ in range(h)] # @line L1
for d in range(D): # @line L2
e = pixel_cost(left, right, d, squared) # @line L3
S = padded_integral(e, r) # @line L4
for v in range(h): # @line L5
top, bot = S[v], S[v + k]
brow, drow = best[v], disp[v]
for u in range(w): # @line L5
c = bot[u + k] - top[u + k] - bot[u] + top[u] # @line L6
if brow[u] is None or c < brow[u]: # @line L7
brow[u] = c # @line L7
drow[u] = d # @line L7
return disp # @line L8
def window_cost(left: Sequence[Sequence[int]], right: Sequence[Sequence[int]],
u: int, v: int, d: int, r: int, squared: bool = False) -> int:
"""S_d(u, v) by the definition, in Theta(r^2) time."""
h, w = len(left), len(left[0])
s = 0
for dv in range(-r, r + 1):
y = _clamp(v + dv, 0, h - 1)
for du in range(-r, r + 1):
x = _clamp(u + du, 0, w - 1)
diff = left[y][x] - right[y][x - d if x >= d else 0]
s += diff * diff if squared else abs(diff)
return s
def block_match_brute(left: Sequence[Sequence[int]], right: Sequence[Sequence[int]],
D: int, r: int, squared: bool = False) -> List[List[int]]:
"""The same disparity map by the definition, in Theta(W H D r^2) time."""
h, w = len(left), len(left[0])
out = []
for v in range(h):
row = []
for u in range(w):
costs = [window_cost(left, right, u, v, d, r, squared) for d in range(D)]
row.append(costs.index(min(costs)))
out.append(row)
return out
test_block_matching_stereo.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/block-matching-stereo/. The authors are listed in prov/VSCW79.jsonl.
import random
import pytest
from block_matching_stereo import (
block_match,
block_match_brute,
padded_integral,
pixel_cost,
window_cost,
)
def random_image(rng, w, h, lo=0, hi=255):
return [[rng.randint(lo, hi) for _ in range(w)] for _ in range(h)]
def shifted_pair(scene, w, h, d):
"""A left image whose pixel (u, v) is the scene point at column u - d of
the right image, so the true disparity is d everywhere."""
right = [[scene[v][u] for u in range(w)] for v in range(h)]
left = [[scene[v][max(u - d, 0)] for u in range(w)] for v in range(h)]
return left, right
def test_worked_example():
left = [[10, 10, 50, 90, 10, 10]] * 3
right = [[10, 50, 90, 10, 10, 10]] * 3
assert [window_cost(left, right, 3, 1, d, 1) for d in range(3)] == [360, 0, 480]
assert [window_cost(left, right, 5, 1, d, 1) for d in range(3)] == [0, 0, 240]
# the textureless pixel u = 5 has a tie, and the tie goes to d = 0
assert block_match(left, right, 3, 1) == [[1, 1, 1, 1, 1, 0]] * 3
def test_matches_brute_force():
rng = random.Random(1)
for w, h, D, r in ((9, 7, 4, 1), (12, 6, 5, 2), (7, 5, 3, 0), (10, 8, 6, 3)):
left, right = random_image(rng, w, h, 0, 20), random_image(rng, w, h, 0, 20)
for squared in (False, True):
assert block_match(left, right, D, r, squared) == block_match_brute(left, right, D, r, squared)
def test_padded_integral_gives_window_sums():
rng = random.Random(2)
e = random_image(rng, 6, 5, 0, 9)
r = 2
S = padded_integral(e, r)
k = 2 * r + 1
for v in range(5):
for u in range(6):
want = sum(e[min(max(v + j, 0), 4)][min(max(u + i, 0), 5)]
for j in range(-r, r + 1) for i in range(-r, r + 1))
assert S[v + k][u + k] - S[v][u + k] - S[v + k][u] + S[v][u] == want
def test_recovers_a_constant_disparity():
rng = random.Random(3)
w, h, D, r = 40, 12, 10, 2
for true_d in (0, 3, 7):
left, right = shifted_pair(random_image(rng, w, h), w, h, true_d)
disp = block_match(left, right, D, r)
for v in range(h):
for u in range(D + r, w):
assert disp[v][u] == true_d
def test_two_layer_scene():
# a background plane at disparity 2 and a square in front at disparity 6
rng = random.Random(4)
w, h, D, r = 48, 30, 9, 2
back = random_image(rng, w + 10, h)
front = random_image(rng, w + 10, h, 100, 255)
x0, x1, y0, y1 = 20, 34, 9, 21 # the square in the left image
def in_square(u, v):
return y0 <= v < y1 and x0 <= u < x1
# the left pixel u sees back[v][u] or front[v][u]; the same scene point
# is at column u - 2 or u - 6 of the right image
left = [[front[v][u] if in_square(u, v) else back[v][u] for u in range(w)] for v in range(h)]
right = [[front[v][x + 6] if in_square(x + 6, v) else back[v][x + 2] for x in range(w)]
for v in range(h)]
truth = [[6 if in_square(u, v) else 2 for u in range(w)] for v in range(h)]
disp = block_match(left, right, D, r)
for v in range(h):
for u in range(D + r, w):
near_edge = y0 - r - 1 <= v < y1 + r + 1 and x0 - 4 - r - 1 <= u < x1 + r + 1
inside = y0 + r <= v < y1 - r and x0 + r <= u < x1 - r
if inside or not near_edge:
assert disp[v][u] == truth[v][u]
# the background just left of the square is hidden in the right image:
# the left pixels x0 - 4 to x0 - 1 have no true match
assert any(disp[v][u] != truth[v][u] for v in range(y0, y1) for u in range(x0 - 4, x0))
def test_flat_images_give_zero():
flat = [[5] * 8 for _ in range(4)]
assert block_match(flat, flat, 4, 1) == [[0] * 8 for _ in range(4)]
def test_pixel_cost_and_window_of_radius_zero():
left = [[1, 4, 9], [2, 2, 2]]
right = [[3, 3, 3], [0, 5, 1]]
assert pixel_cost(left, right, 1) == [[2, 1, 6], [2, 2, 3]]
assert pixel_cost(left, right, 1, squared=True) == [[4, 1, 36], [4, 4, 9]]
for v in range(2):
for u in range(3):
assert window_cost(left, right, u, v, 1, 0) == pixel_cost(left, right, 1)[v][u]
def test_bad_arguments():
img = [[0, 0], [0, 0]]
with pytest.raises(ValueError):
block_match(img, img, 0, 1)
with pytest.raises(ValueError):
block_match(img, img, 2, -1)
History
Matching windows along epipolar lines by correlation is the oldest computer stereo method and was used in photogrammetry before computer vision. Kanade and Okutomi (1994) adapted the window to the image. Scharstein and Szeliski (2002) described local methods as a matching cost, aggregation and winner-takes-all, and evaluated SAD and SSD with square windows on the Middlebury benchmark, where they showed the trade-off between window size and edge errors. Hosni et al. (2013) showed that replacing the box filter by an edge-aware filter on the cost volume gives a local method that keeps edges much better than the box, at the same cost.
References
- 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 parts on matching costs (absolute and squared differences), aggregation with a square window, winner-takes-all, and the results of these local methods on the benchmark
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (local methods and the sum of squared or absolute differences over a window)
- Asmaa Hosni, Christoph Rhemann, Michael Bleyer, Carsten Rother and Margrit Gelautz, Fast cost-volume filtering for visual correspondence and beyond, IEEE Transactions on Pattern Analysis and Machine Intelligence 35(2), 2013, 504-511, the cost volume, filter and winner-takes-all pipeline, of which the box filter is the simplest case
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 VSCW79 Edit this page History Report an error Markdown