Data structurecore
Cost volume
Also called disparity space image.
A 3D array of matching costs indexed by pixel column, row and disparity, on which aggregation and optimization run.
- Time
- Θ(W H D) buildΘ(1) query
- Space
- Θ(W H D) extra
- Where
- D = the number of disparities; H = the image height in pixels; W = the image width in pixels
- Model
- Word RAM
- Properties
- deterministicexactnot static
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stephen S. Intille, Aaron F. Bobick, 1994
A cost volume, also called a disparity space image, is the three dimensional array that holds the matching cost of the left pixel at each disparity of a rectified stereo pair, for all pixels and disparities. It is the common data of almost all dense stereo matching methods: a matching cost fills it, cost aggregation filters it, an optimizer such as semi-global matching or winner-takes-all reads a disparity map out of it, and subpixel refinement reads the costs next to the chosen disparity. Each entry is read or written in time; the price is entries of memory. Plane sweep stereo builds the same kind of volume with planes in place of disparities.
In plain words
Stack images on top of each other. Image number of the stack says, for each pixel of the left image, how badly it matches the pixel columns to its left in the right image. A column through the stack, at one pixel, lists the costs of all candidate disparities of that pixel; its lowest entry is the best match of that pixel alone. A layer of the stack is an ordinary image, so image filters can smooth it. Every step of a stereo program works on this stack, which is why it gets its own name.
The abstract type
The cost volume is an array over the index set with these operations:
- BUILD sets , the cost of the left pixel against the right pixel , and when .
- GET and SET read and write one entry.
- SLICE and SET-SLICE read and write the image of one disparity, which is what aggregation filters.
- WTA() returns for each pixel the least with the least cost.
- RIGHT-VIEW() returns the volume with the right image as reference, , which is when .
Representation
The code stores the volume in one flat array of numbers. Entry is at position , so the disparity is the fastest index and the costs of one pixel are next to each other. This order suits winner-takes-all, subpixel refinement and the path updates of semi-global matching, which all read the whole column of a pixel. The other common order puts the disparity first, at , so that each slice is a contiguous image; it suits filters that work on slices. The two orders hold the same numbers; changing between them is a transpose.
Invalid entries, those whose right pixel is outside the image, hold in the code. A program with integer costs uses the largest value of the type instead. The value must be larger than any valid cost, and larger than any sum of valid costs if aggregation sums over invalid entries.
Learned stereo methods keep a 4D volume: instead of one cost per pixel and disparity, a feature vector of length , built by joining or correlating the features of the two images (Kendall et al. 2017). Networks then turn it into a 3D cost volume.
Operations
INDEX(u, v, d)- 1
return (v · W + u) · D + d BUILD(I_L, I_R, D, c)- 2
for each pixel (u, v) in row-major order do - 3
for d ← 0 to D - 1 do - 4
C[INDEX(u, v, d)] ← c(u, v, d) if u - d ≥ 0, else ∞ WTA(C)- 5
for each pixel (u, v) do - 6
best ← C(u, v, 0); disp(u, v) ← 0 - 7
for d ← 1 to D - 1 do if C(u, v, d) < best then best ← C(u, v, d); disp(u, v) ← d - 8
return disp RIGHT-VIEW(C)- 9
for each pixel (x, v) do - 10
for d ← 0 to D - 1 do - 11
C_R(x, v, d) ← C(x + d, v, d) if x + d < W, else ∞
BUILD visits each entry once in the order of the array and costs calls of the cost function. WTA reads each column once and keeps the first minimum, so ties go to the smallest disparity. RIGHT-VIEW uses that the right pixel at disparity is matched with the left pixel , the same pair as the left entry . So the volume of the right image costs no new cost evaluations, which is how semi-global matching and others get the second disparity map for a left-right consistency check. It is a shear of the volume along .
Example
Take one row, the left row , the right row , and the absolute difference cost. BUILD gives these columns, one per left pixel ( marks invalid entries):
| WTA | ||||
|---|---|---|---|---|
| 0 | 0 | 0 | ||
| 1 | 40 | 0 | 1 | |
| 2 | 40 | 0 | 40 | 1 |
| 3 | 80 | 0 | 40 | 1 |
| 4 | 0 | 0 | 80 | 0 |
| 5 | 0 | 0 | 0 | 0 |
The true disparity is 1 everywhere. WTA is right where the column has one clear minimum and wrong at and , where flat pixels tie and the tie goes to 0; at the true match is outside the right image. Slice is the row . RIGHT-VIEW gives the columns , , , , , for ; for instance .
Size. A pair with has entries: 78.6 MB with 16-bit costs, 157.3 MB with 32-bit costs.
Correctness
The full proof is in proofs/correctness.md. INDEX is a bijection from the index set onto , so every entry has its own cell. BUILD writes each cell exactly once with the value of the definition. WTA keeps, for each pixel, the invariant that after the disparities it holds the least cost and the least disparity that reaches it. RIGHT-VIEW is correct because the pair (right , left ) is the pair of the left entry , and is exactly the condition that this left entry exists.
Proof: Correctness of the cost volume operationsfull
Let and .
Lemma 1. INDEX is a bijection from onto
For , the value satisfies . Conversely, given in this range, and , then and . Division with remainder is unique, so has exactly one preimage, and INDEX is one to one and onto.
So each triple has its own cell, and writing one entry never changes another.
Lemma 2. BUILD writes each entry once with its value
The loops of lines L2 and L3 visit each triple of exactly once. Line L4 writes when and otherwise into the cell of the triple, and by Lemma 1 no other visit writes that cell. After BUILD every cell holds the value of the definition. The code visits the triples in increasing order of INDEX, so it writes the array from position 0 to with a running counter, which by Lemma 1 is the same as computing INDEX.
Lemma 3. WTA returns the least disparity with the least cost
Fix a pixel. Invariant. After line L7 has handled the disparities up to , and is the least that reaches it. Line L6 makes it true for . If , it is the new least value and is the only disparity that reaches it, and line L7 records it. Otherwise the least value and the least disparity that reaches it do not change. After , the claim is the definition of WTA. Invalid entries hold , which is never less than a valid cost, so WTA picks an invalid disparity only when all the column is invalid, which cannot happen because is valid for every pixel.
Lemma 4. RIGHT-VIEW is the volume of the right image
With the right image as reference, the right pixel at disparity is compared with the left pixel : if the left pixel matches the right pixel , then the right pixel matches the left pixel . The left entry compares exactly this pair, and it exists in if and only if , the test of line L11. Its value is the cost of the pair for any cost that is symmetric in the two pixels compared, such as the absolute difference or the Hamming distance of census strings. When the left pixel is outside the image, and line L11 writes , the invalid value.
For a cost that is not symmetric in the two images, such as the one-sided term of the Birchfield-Tomasi measure, the right view holds the cost of the same pair with the same roles, which is still the cost of that pair but not the cost the method would compute with the right image as the first argument.
Slices
SLICE reads the cells of all triples with this in row-major order of the pixels, and SET-SLICE writes into the cell of . By Lemma 1 these cells are distinct and are not cells of other disparities, so a slice can be filtered and written back without changing the other slices.
Complexity
| operation | time | notes |
|---|---|---|
| INDEX, GET, SET | ||
| BUILD | cost evaluations | each for AD or census, for a window cost computed directly |
| SLICE, SET-SLICE | ||
| WTA | ||
| RIGHT-VIEW | no cost evaluations | |
| space | 4D learned volumes: |
The model is the word RAM with costs that fit a word. Block matching avoids the space by keeping one slice at a time and a running best per pixel, but then it cannot run an optimizer that needs all the costs of a pixel at once.
Variants
- Reduced volumes. Keep only the best candidates of each pixel, or a coarse volume at a lower resolution, to save memory. Hierarchical and learned methods refine from coarse to fine.
- Plane sweep volumes. For many views or unrectified images, index the volume by depth planes instead of disparities; see plane sweep stereo.
- Feature volumes. Learned methods join the feature vectors of the two images per disparity (a 4D volume) or store their dot product (a correlation volume), then process it with 3D convolutions.
- Soft argmin. Instead of WTA, take with . It is differentiable and gives a fractional disparity; Kendall et al. (2017) used it to train networks end to end. With a cost column that has two minima it returns a value between them.
When to use it
Build the full volume when a later step needs the costs of all disparities of a pixel at once: edge-aware aggregation slice by slice, semi-global matching, a uniqueness test on the best and second best costs, subpixel refinement, or the right view for a consistency check. When memory is short, as on small processors or for large , keep one slice at a time as block matching does, or use a reduced volume.
Pitfalls
- Memory. grows fast. A 2-megapixel pair with and 32-bit costs needs 2 GB. Choose the type of the costs and the disparity range with this in mind.
- Invalid entries. The first columns have no match at disparity . If they hold 0 instead of a large value, WTA chooses them. If they hold the largest integer, a sum over a window overflows.
- Layout and cache. Filtering slices of a volume stored with the disparity as the fastest index jumps by entries per pixel. Choose the order for the step that dominates the time.
- Sign of the right view. The right pixel matches the left pixel , not . Getting this wrong makes every left-right check fail.
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/cost-volume/. The authors are listed in prov/YWMV35.jsonl.
"""The cost volume of a rectified stereo pair.
An image is a list of rows; the value at pixel (u, v), column u and row v,
is img[v][u]. The left pixel (u, v) at disparity d is compared with the
right pixel (u - d, v). The volume has W * H * D entries in one flat list,
with the disparity as the fastest index: entry (u, v, d) is at
(v * W + u) * D + d. An entry whose right pixel is outside the image holds
INVALID (infinity), so that winner-takes-all never picks it.
"""
from __future__ import annotations
import math
from typing import Callable, List, Sequence
INVALID = math.inf
def absolute_difference(left, right, u: int, v: int, d: int) -> float:
return abs(left[v][u] - right[v][u - d])
class CostVolume:
"""A W x H x D array of matching costs."""
def __init__(self, W: int, H: int, D: int, fill: float = INVALID):
if W < 1 or H < 1 or D < 1:
raise ValueError("W, H and D must be positive")
self.W, self.H, self.D = W, H, D
self.data: List[float] = [fill] * (W * H * D)
def index(self, u: int, v: int, d: int) -> int:
if not (0 <= u < self.W and 0 <= v < self.H and 0 <= d < self.D):
raise IndexError((u, v, d))
return (v * self.W + u) * self.D + d # @line L1
def get(self, u: int, v: int, d: int) -> float:
return self.data[self.index(u, v, d)]
def set(self, u: int, v: int, d: int, c: float) -> None:
self.data[self.index(u, v, d)] = c
@classmethod
def build(cls, left: Sequence[Sequence[float]], right: Sequence[Sequence[float]], D: int,
cost: Callable = absolute_difference) -> "CostVolume":
"""BUILD: C(u, v, d) = cost(u, v, d) if u - d >= 0, else INVALID."""
H, W = len(left), len(left[0])
cv = cls(W, H, D)
k = 0
for v in range(H): # @line L2
for u in range(W): # @line L2
for d in range(D): # @line L3
if u - d >= 0: # @line L4
cv.data[k] = cost(left, right, u, v, d) # @line L4
k += 1
return cv
def slice(self, d: int) -> List[List[float]]:
"""The H x W image of the costs at one disparity."""
D, W = self.D, self.W
return [[self.data[(v * W + u) * D + d] for u in range(W)] for v in range(self.H)]
def set_slice(self, d: int, img: Sequence[Sequence[float]]) -> None:
D, W = self.D, self.W
for v in range(self.H):
for u in range(W):
self.data[(v * W + u) * D + d] = img[v][u]
def wta(self) -> List[List[int]]:
"""WTA: for each pixel the least d with the least cost."""
D, W, data = self.D, self.W, self.data
out = []
for v in range(self.H): # @line L5
row = []
for u in range(W): # @line L5
base = (v * W + u) * D
best, bd = data[base], 0 # @line L6
for d in range(1, D): # @line L7
if data[base + d] < best: # @line L7
best, bd = data[base + d], d # @line L7
row.append(bd) # @line L8
out.append(row)
return out
def right_view(self) -> "CostVolume":
"""RIGHT-VIEW: the volume with the right image as reference,
C_R(x, v, d) = C(x + d, v, d) if x + d < W, else INVALID."""
out = CostVolume(self.W, self.H, self.D)
for v in range(self.H): # @line L9
for x in range(self.W): # @line L9
for d in range(self.D): # @line L10
if x + d < self.W: # @line L11
out.data[out.index(x, v, d)] = self.get(x + d, v, d) # @line L11
return out
def nbytes(self, bytes_per_entry: int) -> int:
return self.W * self.H * self.D * bytes_per_entry
test_cost_volume.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cost-volume/. The authors are listed in prov/YWMV35.jsonl.
import math
import random
import pytest
from cost_volume import INVALID, CostVolume
def random_image(rng, w, h, lo=0, hi=255):
return [[rng.randint(lo, hi) for _ in range(w)] for _ in range(h)]
def nested(left, right, D):
"""A second representation: C[v][u][d] as nested lists."""
H, W = len(left), len(left[0])
return [[[abs(left[v][u] - right[v][u - d]) if u >= d else math.inf for d in range(D)]
for u in range(W)] for v in range(H)]
def test_worked_example():
left = [[10, 10, 50, 90, 10, 10]]
right = [[10, 50, 90, 10, 10, 10]]
cv = CostVolume.build(left, right, 3)
rows = [[cv.get(u, 0, d) for d in range(3)] for u in range(6)]
assert rows == [[0, INVALID, INVALID], [40, 0, INVALID], [40, 0, 40],
[80, 0, 40], [0, 0, 80], [0, 0, 0]]
assert cv.wta() == [[0, 1, 1, 1, 0, 0]]
rv = cv.right_view()
assert [[rv.get(x, 0, d) for d in range(3)] for x in range(6)] == [
[0, 0, 40], [40, 0, 40], [40, 0, 80], [80, 0, 0], [0, 0, INVALID], [0, INVALID, INVALID]]
def test_layout_is_a_bijection():
cv = CostVolume(5, 4, 3)
seen = {cv.index(u, v, d) for v in range(4) for u in range(5) for d in range(3)}
assert seen == set(range(60))
with pytest.raises(IndexError):
cv.index(5, 0, 0)
with pytest.raises(IndexError):
cv.index(0, 0, 3)
with pytest.raises(ValueError):
CostVolume(0, 1, 1)
def test_build_and_wta_against_nested_lists():
rng = random.Random(1)
for W, H, D in ((9, 5, 4), (7, 3, 7), (12, 6, 1)):
left, right = random_image(rng, W, H, 0, 15), random_image(rng, W, H, 0, 15)
cv = CostVolume.build(left, right, D)
ref = nested(left, right, D)
for v in range(H):
for u in range(W):
for d in range(D):
assert cv.get(u, v, d) == ref[v][u][d]
want = [[ref[v][u].index(min(ref[v][u])) for u in range(W)] for v in range(H)]
assert cv.wta() == want
def test_right_view_is_the_volume_of_the_swapped_pair():
# the right view equals the volume built with the right image as
# reference and the match (x + d, v) in the left image
rng = random.Random(2)
W, H, D = 10, 4, 5
left, right = random_image(rng, W, H), random_image(rng, W, H)
rv = CostVolume.build(left, right, D).right_view()
for v in range(H):
for x in range(W):
for d in range(D):
want = abs(right[v][x] - left[v][x + d]) if x + d < W else INVALID
assert rv.get(x, v, d) == want
def test_slices_round_trip():
rng = random.Random(3)
W, H, D = 6, 5, 4
cv = CostVolume.build(random_image(rng, W, H), random_image(rng, W, H), D)
for d in range(D):
s = cv.slice(d)
assert s == [[cv.get(u, v, d) for u in range(W)] for v in range(H)]
cv.set_slice(d, [[x * 2 for x in row] for row in s])
assert cv.slice(d) == [[x * 2 for x in row] for row in s]
def test_shifted_pair_gives_the_true_disparity():
rng = random.Random(4)
W, H, D, true_d = 30, 6, 8, 5
scene = random_image(rng, W + 10, H)
right = [[scene[v][x + true_d] for x in range(W)] for v in range(H)]
left = [[scene[v][u] for u in range(W)] for v in range(H)]
cv = CostVolume.build(left, right, D)
for v in range(H):
for u in range(true_d, W):
assert cv.get(u, v, true_d) == 0
# a 3 x 3 box sum on each slice, then winner-takes-all
for d in range(D):
s = cv.slice(d)
box = [[sum(s[y][x] for y in range(max(v - 1, 0), min(v + 2, H))
for x in range(max(u - 1, 0), min(u + 2, W)))
for u in range(W)] for v in range(H)]
cv.set_slice(d, box)
disp = cv.wta()
for v in range(H):
for u in range(D + 1, W):
assert disp[v][u] == true_d
def test_memory_size():
cv = CostVolume(4, 3, 2)
assert cv.nbytes(2) == 48
assert 640 * 480 * 128 * 2 == 78643200
History
Intille and Bobick (1994) introduced the disparity space image of a scanline, the costs of each column at each disparity, to find occlusions in stereo. Scharstein and Szeliski (2002) made the 3D disparity space image the common data of all methods in their taxonomy, with aggregation as a filter on it and optimization as a search in it. Hosni et al. (2013) framed local stereo as filtering of the cost volume with an edge-aware filter, and Kendall et al. (2017) brought the cost volume into deep networks as a 4D array of features.
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 the disparity space image C(x, y, d), aggregation as filtering of this volume, and winner-takes-all
- Stephen S. Intille and Aaron F. Bobick, Disparity-space images and large occlusion stereo, Computer Vision, ECCV '94, Lecture Notes in Computer Science 801, Springer, 1994, the disparity space image of a scanline and its use for occlusions
- 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, its filtering slice by slice, and winner-takes-all
- Alex Kendall, Hayk Martirosyan, Saumitro Dasgupta, Peter Henry, Ryan Kennedy, Abraham Bachrach and Adam Bry, End-to-end learning of geometry and context for deep stereo regression, IEEE International Conference on Computer Vision, 2017, the 4D feature cost volume, 3D convolutions on it, and the soft argmin
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (the disparity space image and the cost volume)
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 | W4 complete |
|
Tag YWMV35 Edit this page History Report an error Markdown