Algorithm Search⌘K

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
Properties
deterministicexactnot static
Origin
Stephen S. Intille, Aaron F. Bobick, 1994

A cost volume, also called a disparity space image, is the three dimensional array C(u,v,d)C(u, v, d) that holds the matching cost of the left pixel (u,v)(u, v) at each disparity dd of a rectified stereo pair, for all WHW H pixels and DD 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 O(1)O(1) time; the price is WHDW H D entries of memory. Plane sweep stereo builds the same kind of volume with planes in place of disparities.

In plain words

Stack DD images on top of each other. Image number dd of the stack says, for each pixel of the left image, how badly it matches the pixel dd 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 {0,…,W−1}×{0,…,H−1}×{0,…,D−1}\{0, \ldots, W - 1\} \times \{0, \ldots, H - 1\} \times \{0, \ldots, D - 1\} with these operations:

  • BUILD(IL,IR,D,c)(I_L, I_R, D, c) sets C(u,v,d)=c(u,v,d)C(u, v, d) = c(u, v, d), the cost of the left pixel (u,v)(u, v) against the right pixel (u−d,v)(u - d, v), and C(u,v,d)=∞C(u, v, d) = \infty when u−d<0u - d < 0.
  • GET(u,v,d)(u, v, d) and SET(u,v,d,x)(u, v, d, x) read and write one entry.
  • SLICE(d)(d) and SET-SLICE(d,A)(d, A) read and write the H×WH \times W image of one disparity, which is what aggregation filters.
  • WTA() returns for each pixel the least dd with the least cost.
  • RIGHT-VIEW() returns the volume with the right image as reference, CR(x,v,d)=C(x+d,v,d)C_R(x, v, d) = C(x + d, v, d), which is ∞\infty when x+d≥Wx + d \ge W.

Representation

The code stores the volume in one flat array of WHDW H D numbers. Entry (u,v,d)(u, v, d) is at position (vW+u)D+d(v W + u) D + d, 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 (dH+v)W+u(d H + v) W + u, 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 ∞\infty 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 FF, 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

  1. INDEX(u, v, d)
  2. 1return (v · W + u) · D + d
  3. BUILD(I_L, I_R, D, c)
  4. 2for each pixel (u, v) in row-major order do
  5. 3for d ← 0 to D - 1 do
  6. 4C[INDEX(u, v, d)] ← c(u, v, d) if u - d ≥ 0, else ∞
  7. WTA(C)
  8. 5for each pixel (u, v) do
  9. 6best ← C(u, v, 0); disp(u, v) ← 0
  10. 7for d ← 1 to D - 1 do if C(u, v, d) < best then best ← C(u, v, d); disp(u, v) ← d
  11. 8return disp
  12. RIGHT-VIEW(C)
  13. 9for each pixel (x, v) do
  14. 10for d ← 0 to D - 1 do
  15. 11C_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 WHDW H D 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 (x,v)(x, v) at disparity dd is matched with the left pixel (x+d,v)(x + d, v), the same pair as the left entry (x+d,v,d)(x + d, v, d). 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 uu.

Example

Take one row, the left row (10,10,50,90,10,10)(10, 10, 50, 90, 10, 10), the right row (10,50,90,10,10,10)(10, 50, 90, 10, 10, 10), D=3D = 3 and the absolute difference cost. BUILD gives these columns, one per left pixel (∞\infty marks invalid entries):

uu d=0d = 0 d=1d = 1 d=2d = 2 WTA
0 0 ∞\infty ∞\infty 0
1 40 0 ∞\infty 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 u=4u = 4 and u=5u = 5, where flat pixels tie and the tie goes to 0; at u=0u = 0 the true match is outside the right image. Slice d=1d = 1 is the row (∞,0,0,0,0,0)(\infty, 0, 0, 0, 0, 0). RIGHT-VIEW gives the columns (0,0,40)(0, 0, 40), (40,0,40)(40, 0, 40), (40,0,80)(40, 0, 80), (80,0,0)(80, 0, 0), (0,0,∞)(0, 0, \infty), (0,∞,∞)(0, \infty, \infty) for x=0,…,5x = 0, \ldots, 5; for instance CR(3,0,2)=C(5,0,2)=0C_R(3, 0, 2) = C(5, 0, 2) = 0.

Size. A 640×480640 \times 480 pair with D=128D = 128 has 39 321 60039\,321\,600 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 {0,…,WHD−1}\{0, \ldots, W H D - 1\}, 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 0,…,d0, \ldots, d it holds the least cost and the least disparity that reaches it. RIGHT-VIEW is correct because the pair (right (x,v)(x, v), left (x+d,v)(x + d, v)) is the pair of the left entry (x+d,v,d)(x + d, v, d), and x+d<Wx + d < W is exactly the condition that this left entry exists.

Proof: Correctness of the cost volume operationsfull

Let I={0,…,W−1}×{0,…,H−1}×{0,…,D−1}\mathcal I = \{0, \ldots, W - 1\} \times \{0, \ldots, H - 1\} \times \{0, \ldots, D - 1\} and N=WHDN = W H D.

Lemma 1. INDEX is a bijection from I\mathcal I onto {0,…,N−1}\{0, \ldots, N - 1\}

For (u,v,d)∈I(u, v, d) \in \mathcal I, the value k=(vW+u)D+dk = (v W + u) D + d satisfies 0≤k≤((H−1)W+W−1)D+D−1=N−10 \le k \le ((H - 1) W + W - 1) D + D - 1 = N - 1. Conversely, given kk in this range, d=k mod Dd = k \bmod D and q=⌊k/D⌋q = \lfloor k / D \rfloor, then u=q mod Wu = q \bmod W and v=⌊q/W⌋v = \lfloor q / W \rfloor. Division with remainder is unique, so kk has exactly one preimage, and INDEX is one to one and onto. □\square

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 I\mathcal I exactly once. Line L4 writes c(u,v,d)c(u, v, d) when u−d≥0u - d \ge 0 and ∞\infty 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 N−1N - 1 with a running counter, which by Lemma 1 is the same as computing INDEX. □\square

Lemma 3. WTA returns the least disparity with the least cost

Fix a pixel. Invariant. After line L7 has handled the disparities up to dd, best=min⁡d′≤dC(u,v,d′)\textit{best} = \min_{d' \le d} C(u, v, d') and disp(u,v)\textit{disp}(u, v) is the least d′≤dd' \le d that reaches it. Line L6 makes it true for d=0d = 0. If C(u,v,d+1)<bestC(u, v, d + 1) < \textit{best}, it is the new least value and d+1d + 1 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 d=D−1d = D - 1, the claim is the definition of WTA. Invalid entries hold ∞\infty, 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 C(u,v,0)C(u, v, 0) is valid for every pixel. □\square

Lemma 4. RIGHT-VIEW is the volume of the right image

With the right image as reference, the right pixel (x,v)(x, v) at disparity dd is compared with the left pixel (x+d,v)(x + d, v): if the left pixel (u,v)(u, v) matches the right pixel (u−d,v)(u - d, v), then the right pixel (x,v)=(u−d,v)(x, v) = (u - d, v) matches the left pixel (x+d,v)(x + d, v). The left entry (x+d,v,d)(x + d, v, d) compares exactly this pair, and it exists in I\mathcal I if and only if x+d≤W−1x + d \le W - 1, 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 x+d≥Wx + d \ge W the left pixel is outside the image, and line L11 writes ∞\infty, the invalid value. □\square

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(d)(d) reads the cells of all triples with this dd in row-major order of the pixels, and SET-SLICE(d,A)(d, A) writes A[v][u]A[v][u] into the cell of (u,v,d)(u, v, d). 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. □\square

Complexity

operation time notes
INDEX, GET, SET Θ(1)\Theta(1)
BUILD Θ(WHD)\Theta(W H D) cost evaluations each O(1)O(1) for AD or census, O(r2)O(r^2) for a window cost computed directly
SLICE, SET-SLICE Θ(WH)\Theta(W H)
WTA Θ(WHD)\Theta(W H D)
RIGHT-VIEW Θ(WHD)\Theta(W H D) no cost evaluations
space Θ(WHD)\Theta(W H D) 4D learned volumes: Θ(WHDF)\Theta(W H D F)

The model is the word RAM with costs that fit a word. Block matching avoids the Θ(WHD)\Theta(W H D) 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 D′≪DD' \ll D 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 d^=∑dd σd\hat d = \sum_d d \, \sigma_d with σ=softmax⁡(−C(u,v,⋅))\sigma = \operatorname{softmax}(-C(u, v, \cdot)). 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 DD, keep one slice at a time as block matching does, or use a reduced volume.

Pitfalls

  • Memory. WHDW H D grows fast. A 2-megapixel pair with D=256D = 256 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 dd columns have no match at disparity dd. 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 DD entries per pixel. Choose the order for the step that dominates the time.
  • Sign of the right view. The right pixel (x,v)(x, v) matches the left pixel (x+d,v)(x + d, v), not (x−d,v)(x - d, v). 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.

cost_volume.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.query
  • 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)
WritingW4 complete
  • a review of the text: no review record reviews/YWMV35/text.yaml