Algorithm Search⌘K

Algorithmadvanced

Adaptive support weights

Also called Yoon-Kweon adaptive weights.

Aggregate costs with weights that fall off with color difference and distance from the center pixel, like a bilateral filter on the cost volume.

Time
Θ(W H D r^2) worst · average · best
Space
Θ(W H r^2) extra
Where
D = the number of disparities; H = the image height in pixels; W = the image width in pixels; r = the radius of the window
Properties
deterministicnot exactofflineiterative
Origin
Kuk Jin Yoon, In So Kweon, 2005

Adaptive support weights is a local stereo method that sums the matching costs of a window with a weight for each pixel of the window, where the weight is high for pixels close to the center in color and in position and low for the others. A pixel on the far side of a depth edge usually has another color, so it gets almost no weight, and the window behaves as if it followed the edge. Yoon and Kweon (2005, 2006) took the weight of a pixel as the product of its weight in the left window and the weight of its match in the right window, and chose disparities by winner-takes-all. It is block matching with the box replaced by a bilateral filter of the cost volume, and the weights must be computed for each window, so it costs Θ(WHDr2)\Theta(W H D r^2) on the real RAM, not Θ(WHD)\Theta(W H D).

In plain words

Block matching adds up the differences over a whole square. If the square sits on the edge of a near object, half of it shows the background, and that half pulls the answer the wrong way. Adaptive support weights asks each pixel of the square how much it looks like the center pixel. A pixel of the same color and close by gets a weight near one; a pixel of a clearly different color gets a weight near zero. It does this in both images and multiplies the two weights. Then it averages the differences with these weights. The square now counts only the part that probably lies on the same surface as the center.

The problem

Input. A rectified pair of color images ILI_L and IRI_R of W×HW \times H pixels, the right camera to the right of the left one, so the left pixel (u,v)(u, v) matches the right pixel (u−d,v)(u - d, v). A number of disparities DD, a window radius rr, two positive constants γc\gamma_c and γp\gamma_p, and a truncation threshold TT.

Output. For each left pixel p=(u,v)p = (u, v), the disparity d∗(p)=min⁡arg min⁡0≤d≤min⁡(D−1,u)E(p,d)d^*(p) = \min \operatorname{arg\,min}_{0 \le d \le \min(D - 1, u)} E(p, d), with

E(p,d)=∑qw(p,q) w(pˉd,qˉd) e(q,qˉd)∑qw(p,q) w(pˉd,qˉd),w(p,q)=exp⁡ ⁣(−(Δcpqγc+Δgpqγp)).E(p, d) = \frac{\sum_{q} w(p, q)\, w(\bar p_d, \bar q_d)\, e(q, \bar q_d)}{\sum_{q} w(p, q)\, w(\bar p_d, \bar q_d)}, \qquad w(p, q) = \exp\!\left(-\left(\frac{\Delta c_{pq}}{\gamma_c} + \frac{\Delta g_{pq}}{\gamma_p}\right)\right).

Here q=p+oq = p + o runs over the offsets oo of the (2r+1)×(2r+1)(2r + 1) \times (2r + 1) window such that qq is in the left image and qˉd=q−(d,0)\bar q_d = q - (d, 0) is in the right image, and pˉd=p−(d,0)\bar p_d = p - (d, 0). The color distance Δcpq\Delta c_{pq} is the Euclidean distance of the colors of pp and qq in CIELab, computed within one image, and Δgpq=∥o∥\Delta g_{pq} = \lVert o \rVert is the distance of the positions. The raw cost e(q,qˉ)=min⁡(∑c∈{R,G,B}∣IL,c(q)−IR,c(qˉ)∣,T)e(q, \bar q) = \min\big(\sum_{c \in \{R, G, B\}} |I_{L,c}(q) - I_{R,c}(\bar q)|, T\big) is the truncated absolute difference. The outer min⁡\min breaks ties toward the smallest disparity.

The parameters are tuned, not derived, and the sources give two settings. The conference paper (Yoon and Kweon 2005) reports a 33×3333 \times 33 window with γc=7\gamma_c = 7 and γp=36\gamma_p = 36, with γp\gamma_p chosen by experiment. Richardt et al. (2010) give 35×3535 \times 35 (r=17r = 17), γc=5\gamma_c = 5 and γp=17.5\gamma_p = 17.5 as the default values of the method, and later papers use these. The code uses the second setting as its defaults. The threshold T=40T = 40 of the code is a choice of the code.

The algorithm

  1. ASW(I_L, I_R, D, r, γc, γp, T)
  2. 1for each left pixel p = (u, v) do
  3. 2for d ← 0 to min(D - 1, u) do
  4. 3num ← 0; den ← 0
  5. 4for each offset o of the window with q = p + o in I_L and q - (d, 0) in I_R do
  6. 5ω ← w(p, q) · w(p - (d, 0), q - (d, 0)) ▷ the left and the right weight
  7. 6num ← num + ω · e(q, q - (d, 0)); den ← den + ω
  8. 7E(d) ← num / den
  9. 8disp(p) ← the least d with the least E(d)
  10. 9return disp

Line L5 is the heart of the method. The left factor favors pixels like pp in the left image, and the right factor favors pixels like the candidate match in the right image. A pixel gets a large weight only if it looks like the center in both images, which is what is expected of a pixel on the same surface at the candidate disparity. Line L7 normalizes, so EE is a weighted mean of truncated costs. The weights w(p,q)w(p, q) of a pixel do not depend on dd, so the code computes them once per pixel and image and keeps them, (2r+1)2(2r + 1)^2 numbers per pixel.

Example

With γc=5\gamma_c = 5 and γp=17.5\gamma_p = 17.5, the weights of some neighbors qq of a red center pp with RGB color (200,30,30)(200, 30, 30) are:

color of qq distance ∥o∥\lVert o \rVert Δc\Delta c in CIELab w(p,q)w(p, q)
(200,30,30)(200, 30, 30) 1 0 0.9445
(200,30,30)(200, 30, 30) 3 0 0.8425
(210,40,35)(210, 40, 35) 1 3.04 0.5138
(190,60,40)(190, 60, 40) 2 12.96 0.0668
(30,30,200)(30, 30, 200) 1 130.12 4.7⋅10−124.7 \cdot 10^{-12}

The color term falls much faster than the distance term: a Lab difference of 13 already cuts the weight to under a tenth, while a distance of 3 pixels only cuts it to 0.84.

Now take a window of three pixels at one disparity. The center has raw cost 4 and joint weight 1⋅1=11 \cdot 1 = 1. A neighbor on the same red surface has raw cost 6 and joint weight 0.94452=0.8920.9445^2 = 0.892. A neighbor on a blue background has raw cost T=40T = 40, because at this disparity its match is wrong, and joint weight below 10−2010^{-20}. Then

E=1⋅4+0.892⋅6+10−20⋅401+0.892+10−20≈4.94,E = \frac{1 \cdot 4 + 0.892 \cdot 6 + 10^{-20} \cdot 40}{1 + 0.892 + 10^{-20}} \approx 4.94,

while the box mean is (4+6+40)/3≈16.7(4 + 6 + 40) / 3 \approx 16.7. The background pixel no longer decides the cost of the red center.

Correctness

The full proof is in proofs/correctness.md. It shows that the offset o=(0,0)o = (0, 0) is always in the sum of line L4, because d≤ud \le u, with joint weight 11, so den≥1\textit{den} \ge 1 and line L7 never divides by zero. It shows that lines L3 to L7 compute E(p,d)E(p, d) of the definition, that E(p,d)E(p, d) is a weighted mean of truncated costs and so lies in [0,T][0, T], that line L8 returns d∗(p)d^*(p), and that for γc,γp→∞\gamma_c, \gamma_p \to \infty all weights tend to 1 and EE tends to the box mean of block matching with the truncated cost.

Proof: Correctness of the adaptive support weight methodfull

Fix the images, DD, rr, γc>0\gamma_c > 0, γp>0\gamma_p > 0 and T>0T > 0. For a left pixel p=(u,v)p = (u, v) and a disparity dd with 0≤d≤min⁡(D−1,u)0 \le d \le \min(D - 1, u), let Ω(p,d)\Omega(p, d) be the set of offsets oo with ∣ou∣,∣ov∣≤r|o_u|, |o_v| \le r such that q=p+oq = p + o is in the left image and qˉd=q−(d,0)\bar q_d = q - (d, 0) is in the right image. We prove that ASW returns d∗(p)d^*(p), the least disparity with the least value of

E(p,d)=∑o∈Ω(p,d)ωo e(q,qˉd)∑o∈Ω(p,d)ωo,ωo=w(p,q) w(pˉd,qˉd).E(p, d) = \frac{\sum_{o \in \Omega(p, d)} \omega_o\, e(q, \bar q_d)}{\sum_{o \in \Omega(p, d)} \omega_o}, \qquad \omega_o = w(p, q)\, w(\bar p_d, \bar q_d).

Lemma 1. The denominator is at least 1

The offset o=(0,0)o = (0, 0) is in Ω(p,d)\Omega(p, d): q=pq = p is in the left image, and pˉd=(u−d,v)\bar p_d = (u - d, v) is in the right image because 0≤d≤u0 \le d \le u and the two images have the same size. For this offset Δc=0\Delta c = 0 and Δg=0\Delta g = 0 in both images, so ω(0,0)=e0⋅e0=1\omega_{(0,0)} = e^0 \cdot e^0 = 1. Every other ωo\omega_o is a product of two exponentials and so is positive. Hence ∑oωo≥1\sum_{o} \omega_o \ge 1, and line L7 never divides by zero. □\square

The restriction d≤ud \le u of line L2 is what makes this true: for d>ud > u the center pixel has no match in the right image, and the set Ω\Omega could be empty.

Lemma 2. Lines L3 to L7 compute E(p,d)E(p, d)

Line L3 sets num=den=0\textit{num} = \textit{den} = 0. The loop of line L4 visits each offset of the window once and skips exactly the offsets with qq outside the left image or qˉd\bar q_d outside the right image, that is, it visits exactly Ω(p,d)\Omega(p, d). In the code, an offset outside the left image has the weight None in the stored left weights of pp, and an offset with qˉd\bar q_d outside the right image has the weight None in the stored right weights of pˉd\bar p_d, because pˉd+o=qˉd\bar p_d + o = \bar q_d. For a visited offset, line L5 forms ωo\omega_o, and line L6 adds ωoe(q,qˉd)\omega_o e(q, \bar q_d) to num\textit{num} and ωo\omega_o to den\textit{den}. After the loop, by induction on the number of visited offsets, num\textit{num} and den\textit{den} are the two sums of the definition, and line L7 gives E(p,d)E(p, d). □\square

The stored weights are correct because w(p,q)w(p, q) depends only on the left image, pp and oo, and w(pˉd,qˉd)w(\bar p_d, \bar q_d) only on the right image, pˉd\bar p_d and oo. Neither depends on dd except through the pixel pˉd\bar p_d, so one table of weights per pixel and image serves all disparities.

Lemma 3. 0≤E(p,d)≤T0 \le E(p, d) \le T

Put λo=ωo/∑o′ωo′\lambda_o = \omega_o / \sum_{o'} \omega_{o'}. Then λo>0\lambda_o > 0 and ∑oλo=1\sum_o \lambda_o = 1, so E(p,d)=∑oλoe(q,qˉd)E(p, d) = \sum_o \lambda_o e(q, \bar q_d) is a convex combination of the raw costs. Each raw cost is a minimum of a sum of absolute values and TT, so it lies in [0,T][0, T], and so does every convex combination of them. □\square

Theorem. ASW returns d∗(p)d^*(p)

For each pixel, line L8 keeps the first disparity whose value is strictly less than all values before it. By the same invariant as for block matching, after the loop of line L2 this is the least dd in [0,min⁡(D−1,u)][0, \min(D - 1, u)] with the least E(p,d)E(p, d), using Lemma 2 for the values. The pixels are handled independently. □\square

The limit of uniform weights

As γc→∞\gamma_c \to \infty and γp→∞\gamma_p \to \infty, each exponent tends to 0, so each ωo\omega_o tends to 1 and, the sums being finite, E(p,d)E(p, d) tends to ∣Ω(p,d)∣−1∑oe(q,qˉd)\lvert \Omega(p, d) \rvert^{-1} \sum_{o} e(q, \bar q_d), the mean of the truncated costs over the window. Inside the image, where Ω(p,d)\Omega(p, d) is the full window of (2r+1)2(2r + 1)^2 offsets, this mean is a fixed multiple of the box sum of block matching with the truncated cost, so the two methods choose the same disparities there. So adaptive support weights generalize box aggregation. □\square

Symmetry of the weights

w(p,q)=w(q,p)w(p, q) = w(q, p) for two pixels of the same image, because the Euclidean distances of colors and of positions are symmetric. The tests check this on random images.

What is not proved

The theorem says that the code chooses the minimizer of EE. That the minimizer is the true disparity near a depth edge depends on the assumption that a depth edge is also a color edge, which is a property of the scene and not a theorem. The tests show it on a synthetic scene where the assumption holds: near the edges of a red square on a blue background, the method makes no errors on the pixels that have a true match, while the box window with the same radius makes many.

Exactness

The method uses exp⁡\exp, square roots and divisions, so the code computes in floating point and is not exact. Two disparities whose values differ by less than the rounding error may be ordered wrongly. The model of the page is the real RAM, where these operations are exact.

Complexity

The model is the real RAM with exp⁡\exp and the square root at unit cost.

  • Weights. Each pixel of each image has (2r+1)2(2r + 1)^2 weights, each from one color distance and one exp⁡\exp: Θ(WHr2)\Theta(W H r^2) time and Θ(WHr2)\Theta(W H r^2) space for the stored weights. Without storing them, the time doubles and the space is Θ(WH)\Theta(W H).
  • Costs. Lines L4 to L6 run (2r+1)2(2r + 1)^2 times for each pixel and disparity, so the total is Θ(WHDr2)\Theta(W H D r^2) time. For the usual 35×3535 \times 35 window, that is 1225 weighted terms per pixel and disparity, against the four additions and subtractions per pixel and disparity of a box filter with an integral image.
  • No shortcut by sums. The weights change with the center pixel, so the window sum cannot be read from an integral image. That is the reason for the faster approximations below.

Properties

  • Bilateral filter on the cost volume. For a fixed dd, line L6 is a joint bilateral filter of the cost slice, with the range kernel taken from the two images instead of from the costs (a theorem by the form of the sum). The left and right weights make it symmetric in the two images.
  • Weighted mean. E(p,d)E(p, d) is a convex combination of the raw costs, so it lies between the least and the largest raw cost in the window, and in [0,T][0, T].
  • Edge preserving, by assumption. The method assumes that pixels of similar color near each other lie on the same surface, and that a depth edge is also a color edge. This is a heuristic. Where a surface has strong texture or two surfaces have the same color, the weights help less.
  • No smoothness term. Each pixel still decides by winner-takes-all. Large textureless areas of one color get large uniform supports, which helps, but there is no global constraint.

Variants and improvements

  • Guided filter aggregation. Hosni et al. (2013) filter each cost slice with the guided filter, which is edge-aware like the bilateral weights but runs in Θ(WH)\Theta(W H) per slice for any radius, with box sums. The whole method is Θ(WHD)\Theta(W H D).
  • Geodesic weights. Replace the color distance by a geodesic distance in the image, so that a pixel of the same color behind an edge of another color is not counted.
  • Weights from the left image only. Dropping the right factor halves the work. The result is close in many scenes but no longer symmetric.
  • Fast approximations. Bilateral grids, as in Richardt et al. (2010), separable approximations, and tree filters bring the cost close to Θ(WHD)\Theta(W H D).
  • With other costs. The truncated absolute difference can be replaced by a census cost or by gradients; the weights stay the same.

When to use it

Use adaptive support weights as a reference local method, or when the scene has clear color edges at its depth edges and the image is small enough for the cost. For larger images and real time, use guided filter aggregation, which gives similar edge behavior at Θ(WHD)\Theta(W H D), or semi-global matching, which adds a smoothness term. Use plain block matching when speed matters more than edges.

Pitfalls

  • Cost. The usual window has 1225 pixels, each with an exponential, so the method does hundreds of times more arithmetic per cost than a box filter. Do not store all weights for large images without checking the memory: (2r+1)2(2r + 1)^2 numbers per pixel per image.
  • Color space. The color distance is defined in CIELab, which is closer to perceived differences than RGB. With 8-bit RGB distances, γc=5\gamma_c = 5 is far too small, and almost every weight is zero.
  • Gray images. With one channel, many surfaces share a gray level, and the weights separate them much less well.
  • Truncation. Without the threshold TT, a single bad pixel with a large weight still dominates the mean. With a small TT, the cost loses the power to tell a near miss from a far miss.
  • Occlusions. Near the left side of a near object, some background pixels have no match at all. The weights do not fix this; a left-right consistency check is still needed.

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.

adaptive_support_weights.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-support-weights/. The authors are listed in prov/WDQMCM.jsonl.
"""Adaptive support weights for stereo (Yoon and Kweon, 2006).

An image is a list of rows of RGB triples with values in 0..255; the value
at pixel (u, v), column u and row v, is img[v][u]. The pair is rectified
and the left pixel (u, v) matches the right pixel (u - d, v), d >= 0.

The weight of a pixel q in the window of a pixel p is

    w(p, q) = exp(-(dc(p, q) / gamma_c + dg(p, q) / gamma_p)),

where dc is the Euclidean distance of the two colors in CIELab and dg the
Euclidean distance of the two pixel positions. The cost of disparity d at
the left pixel p, with pd = p - (d, 0), is

    E(p, d) = sum_q w(p, q) w(pd, qd) e(q, qd) / sum_q w(p, q) w(pd, qd),

over the offsets o with |o_u|, |o_v| <= r such that q = p + o is in the left
image and qd = q - (d, 0) is in the right image. The raw cost e is the sum
over the three channels of the absolute RGB differences, truncated at T.
The disparity of p is the least d in [0, D) with d <= u that has the least
E(p, d).
"""

from __future__ import annotations

import math
from typing import List, Optional, Sequence, Tuple

Color = Tuple[float, float, float]


def _lin(c: float) -> float:
    c = c / 255.0
    return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4


def _f(t: float) -> float:
    e = 6.0 / 29.0
    return t ** (1.0 / 3.0) if t > e ** 3 else t / (3 * e * e) + 4.0 / 29.0


def rgb_to_lab(rgb: Sequence[float]) -> Color:
    """CIELab of an sRGB color with channels in 0..255 (D65 white)."""
    r, g, b = (_lin(float(c)) for c in rgb)
    x = 0.4124 * r + 0.3576 * g + 0.1805 * b
    y = 0.2126 * r + 0.7152 * g + 0.0722 * b
    z = 0.0193 * r + 0.1192 * g + 0.9505 * b
    fx, fy, fz = _f(x / 0.95047), _f(y / 1.0), _f(z / 1.08883)
    return (116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz))


def support_weights(lab: Sequence[Sequence[Color]], u: int, v: int, r: int,
                    gamma_c: float, gamma_p: float) -> List[Optional[float]]:
    """The weights w(p, p + o) of the pixel p = (u, v) for the offsets o of
    the window in row-major order; None for an offset outside the image."""
    h, w = len(lab), len(lab[0])
    c0 = lab[v][u]
    out: List[Optional[float]] = []
    for dv in range(-r, r + 1):
        for du in range(-r, r + 1):
            x, y = u + du, v + dv
            if 0 <= x < w and 0 <= y < h:
                dc = math.dist(c0, lab[y][x])
                dg = math.hypot(du, dv)
                out.append(math.exp(-(dc / gamma_c + dg / gamma_p)))
            else:
                out.append(None)
    return out


def asw_disparity(left: Sequence[Sequence[Sequence[int]]], right: Sequence[Sequence[Sequence[int]]],
                  D: int, r: int = 17, gamma_c: float = 5.0, gamma_p: float = 17.5,
                  T: float = 40.0) -> List[List[int]]:
    """The winner-takes-all disparity map of the adaptive support weight
    cost, in O(W H D r^2) time."""
    if D < 1 or r < 0:
        raise ValueError("need D >= 1 and r >= 0")
    h, w = len(left), len(left[0])
    lab_l = [[rgb_to_lab(c) for c in row] for row in left]
    lab_r = [[rgb_to_lab(c) for c in row] for row in right]
    wl = [[support_weights(lab_l, u, v, r, gamma_c, gamma_p) for u in range(w)] for v in range(h)]
    wr = [[support_weights(lab_r, u, v, r, gamma_c, gamma_p) for u in range(w)] for v in range(h)]
    offs = [(du, dv) for dv in range(-r, r + 1) for du in range(-r, r + 1)]
    out = []
    for v in range(h):  # @line L1
        row = []
        for u in range(w):  # @line L1
            best, bd = math.inf, 0
            for d in range(min(D - 1, u) + 1):  # @line L2
                num = den = 0.0  # @line L3
                a, b = wl[v][u], wr[v][u - d]
                for k, (du, dv) in enumerate(offs):  # @line L4
                    if a[k] is None or b[k] is None:  # @line L4
                        continue
                    wt = a[k] * b[k]  # @line L5
                    cl = left[v + dv][u + du]
                    cr = right[v + dv][u + du - d]
                    e = min(abs(cl[0] - cr[0]) + abs(cl[1] - cr[1]) + abs(cl[2] - cr[2]), T)  # @line L6
                    num += wt * e  # @line L6
                    den += wt  # @line L6
                cost = num / den  # @line L7
                if cost < best:  # @line L8
                    best, bd = cost, d  # @line L8
            row.append(bd)  # @line L8
        out.append(row)
    return out  # @line L9


def asw_cost_brute(left, right, u: int, v: int, d: int, r: int, gamma_c: float,
                   gamma_p: float, T: float) -> float:
    """E(p, d) straight from the definition, for the tests."""
    h, w = len(left), len(left[0])
    lp, lpd = rgb_to_lab(left[v][u]), rgb_to_lab(right[v][u - d])
    num = den = 0.0
    for dv in range(-r, r + 1):
        for du in range(-r, r + 1):
            x, y = u + du, v + dv
            if not (0 <= y < h and 0 <= x < w and 0 <= x - d < w):
                continue
            g = math.sqrt(du * du + dv * dv)
            w1 = math.exp(-(math.dist(lp, rgb_to_lab(left[y][x])) / gamma_c + g / gamma_p))
            w2 = math.exp(-(math.dist(lpd, rgb_to_lab(right[y][x - d])) / gamma_c + g / gamma_p))
            e = min(sum(abs(p - q) for p, q in zip(left[y][x], right[y][x - d])), T)
            num += w1 * w2 * e
            den += w1 * w2
    return num / den
test_adaptive_support_weights.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-support-weights/. The authors are listed in prov/WDQMCM.jsonl.

import math
import random

import pytest

from adaptive_support_weights import (
    asw_cost_brute,
    asw_disparity,
    rgb_to_lab,
    support_weights,
)


def random_rgb(rng, w, h, lo=0, hi=255):
    return [[tuple(rng.randint(lo, hi) for _ in range(3)) for _ in range(w)] for _ in range(h)]


def wta_brute(left, right, D, r, gc, gp, T):
    h, w = len(left), len(left[0])
    out = []
    for v in range(h):
        row = []
        for u in range(w):
            costs = [asw_cost_brute(left, right, u, v, d, r, gc, gp, T) for d in range(min(D - 1, u) + 1)]
            row.append(costs.index(min(costs)))
        out.append(row)
    return out


def two_layer_scene(rng, w, h, box, d_back, d_front):
    """A bluish background at disparity d_back and a reddish square, the
    columns x0..x1 - 1 and rows y0..y1 - 1 of the left image, at d_front."""
    x0, x1, y0, y1 = box

    def inside(u, v):
        return y0 <= v < y1 and x0 <= u < x1

    def back():
        g = rng.randint(40, 120)
        return (g // 2, g // 2 + rng.randint(0, 20), g + rng.randint(0, 40))

    def front():
        g = rng.randint(120, 230)
        return (g, g // 3 + rng.randint(0, 30), g // 4)

    B = [[back() for _ in range(w + 10)] for _ in range(h)]
    F = [[front() for _ in range(w + 10)] for _ in range(h)]
    left = [[F[v][u] if inside(u, v) else B[v][u] for u in range(w)] for v in range(h)]
    right = [[F[v][x + d_front] if inside(x + d_front, v) else B[v][x + d_back] for x in range(w)]
             for v in range(h)]
    truth = [[d_front if inside(u, v) else d_back for u in range(w)] for v in range(h)]
    return left, right, truth


def test_lab_reference_colors():
    L, a, b = rgb_to_lab((255, 255, 255))
    assert L == pytest.approx(100.0, abs=0.05) and abs(a) < 0.05 and abs(b) < 0.05
    assert rgb_to_lab((0, 0, 0)) == pytest.approx((0.0, 0.0, 0.0), abs=1e-9)
    L, a, b = rgb_to_lab((128, 128, 128))
    assert abs(a) < 0.05 and abs(b) < 0.05
    # red has a large positive a
    assert rgb_to_lab((200, 30, 30))[1] > 50


def test_worked_example_weights():
    lab = [[rgb_to_lab(c) for c in [(200, 30, 30), (200, 30, 30), (30, 30, 200)]]]
    wts = support_weights(lab, 0, 0, 1, 5.0, 17.5)
    # offsets in row-major order; the middle row is index 3, 4, 5
    assert wts[4] == pytest.approx(1.0)
    assert wts[5] == pytest.approx(math.exp(-1 / 17.5))
    assert wts[3] is None and wts[0] is None
    wts = support_weights(lab, 1, 0, 1, 5.0, 17.5)
    assert wts[5] < 1e-11


def test_weights_are_symmetric():
    rng = random.Random(1)
    img = random_rgb(rng, 6, 5)
    lab = [[rgb_to_lab(c) for c in row] for row in img]
    r = 2
    for v in range(5):
        for u in range(6):
            wp = support_weights(lab, u, v, r, 7.0, 9.0)
            k = 0
            for dv in range(-r, r + 1):
                for du in range(-r, r + 1):
                    if wp[k] is not None:
                        wq = support_weights(lab, u + du, v + dv, r, 7.0, 9.0)
                        back = (r - dv) * (2 * r + 1) + (r - du)
                        assert wq[back] == pytest.approx(wp[k], rel=1e-12)
                    k += 1


def test_matches_brute_force():
    rng = random.Random(2)
    left, right = random_rgb(rng, 9, 6), random_rgb(rng, 9, 6)
    for r, gc, gp, T in ((1, 5.0, 17.5, 40.0), (2, 10.0, 3.0, 100.0), (0, 5.0, 17.5, 40.0)):
        assert asw_disparity(left, right, 4, r, gc, gp, T) == wta_brute(left, right, 4, r, gc, gp, T)


def test_uniform_weights_give_the_box_mean():
    rng = random.Random(3)
    left, right = random_rgb(rng, 8, 6), random_rgb(rng, 8, 6)
    r, T = 1, 60.0
    for u, v, d in ((4, 3, 2), (1, 0, 1), (7, 5, 3)):
        terms = []
        for dv in range(-r, r + 1):
            for du in range(-r, r + 1):
                x, y = u + du, v + dv
                if 0 <= y < 6 and 0 <= x < 8 and 0 <= x - d < 8:
                    terms.append(min(sum(abs(p - q) for p, q in zip(left[y][x], right[y][x - d])), T))
        mean = sum(terms) / len(terms)
        assert asw_cost_brute(left, right, u, v, d, r, 1e12, 1e12, T) == pytest.approx(mean, rel=1e-9)


def test_recovers_a_constant_disparity():
    rng = random.Random(4)
    w, h, D, true_d = 24, 10, 7, 4
    scene = random_rgb(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)]
    disp = asw_disparity(left, right, D, r=3)
    for v in range(h):
        for u in range(true_d, w):
            assert disp[v][u] == true_d


def test_keeps_depth_edges_better_than_a_box():
    rng = random.Random(4)
    w, h, D, r = 32, 20, 9, 4
    box = (14, 24, 6, 14)
    left, right, truth = two_layer_scene(rng, w, h, box, 2, 7)
    asw = asw_disparity(left, right, D, r)
    flat = asw_disparity(left, right, D, r, gamma_c=1e9, gamma_p=1e9)
    x0, x1, y0, y1 = box

    def near_edge(u, v):
        band = y0 - r <= v < y1 + r and x0 - r <= u < x1 + r
        core = y0 + r <= v < y1 - r and x0 + r <= u < x1 - r
        hidden = y0 <= v < y1 and x0 - 5 <= u < x0  # no true match
        return band and not core and not hidden

    def errors(m):
        return sum(m[v][u] != truth[v][u] for v in range(h) for u in range(D + r, w) if near_edge(u, v))

    assert errors(asw) == 0
    assert errors(flat) >= 10


def test_bad_arguments():
    img = [[(0, 0, 0)] * 3]
    with pytest.raises(ValueError):
        asw_disparity(img, img, 0)
    with pytest.raises(ValueError):
        asw_disparity(img, img, 2, r=-1)

History

Yoon and Kweon presented the method at CVPR 2005 and in the IEEE Transactions on Pattern Analysis and Machine Intelligence in 2006, following earlier work on windows that adapt their shape or size, such as the adaptive windows of Kanade and Okutomi. Their method showed that a local method with carefully weighted support could compete with global methods on depth edges, at a high cost per pixel. Later work aimed at the same quality at the speed of a box filter, with bilateral grids, geodesic weights and, most widely, the guided filter of Hosni et al. (2013).

References

  1. Kuk-Jin Yoon and In So Kweon, Adaptive support-weight approach for correspondence search, IEEE Transactions on Pattern Analysis and Machine Intelligence 28(4), 2006, 650-656, the whole paper (the support weight from the color difference in CIELab and the distance, the combination of the weights of both windows, and winner-takes-all)
  2. Kuk-Jin Yoon and In So Kweon, Locally adaptive support-weight approach for visual correspondence search, IEEE Conference on Computer Vision and Pattern Recognition, 2005, volume 2, 924-931, the conference version of the method (the weight of Eq. 9 and the parameter setting of the Middlebury tests)
  3. Christian Richardt, Douglas Orr, Ian Davies, Antonio Criminisi and Neil A. Dodgson, Real-time spatiotemporal stereo matching using the dual-cross-bilateral grid, European Conference on Computer Vision, 2010, the description of adaptive support weights and its default parameter values
  4. 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, edge-aware filtering of the cost volume with the guided filter, in time independent of the window size
  5. 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 part on aggregation and the problems of square windows near depth edges

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.average
  • a full proof of time.best
  • a full proof of time.worst
  • 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)
WritingW2 basic
  • a scene preset for the example