Algorithm Search⌘K

Algorithmcore

Census transform

Also called census matching cost.

Replace each pixel by the bit string of whether each neighbor is darker than it, and match pixels by the Hamming distance of their strings.

Time
Θ(W H (r^2 + 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; r = the radius of the census window
Properties
deterministicexactofflineiterative
Origin
Ramin Zabih, John Woodfill, 1994

The census transform replaces each pixel by a string of bits, one for each neighbor in a small window, where a bit is 1 if that neighbor is darker than the center pixel. Two pixels then match well if their strings differ in few bits, and the Hamming distance of the strings is the matching cost. The string depends only on the order of the intensities in the window, so any strictly increasing change of brightness, such as a different gain, offset or gamma of the second camera, leaves it the same. Zabih and Woodfill (1994) introduced it with the rank transform, and it is the usual cost of semi-global matching and of hardware stereo. On the word RAM the transform costs Θ(WHr2)\Theta(W H r^2) and each cost of the cost volume costs O(1)O(1), one XOR and one popcount of a word.

In plain words

Look at a small square around a pixel. For each other pixel in the square, write 1 if it is darker than the middle one and 0 if not. The list of ones and zeros is the census of the pixel. To compare a pixel in the left image with one in the right image, compare their two lists and count the places where they differ. Fewer differences mean a better match. If one camera makes the whole picture brighter, darker or more contrasty, every comparison inside the square comes out the same, so the lists do not change. The price is that the list says only "darker or not", and not by how much.

The problem

Input. A rectified pair of grayscale images ILI_L, IRI_R of W×HW \times H pixels, with integer or real values. Pixel (u,v)(u, v) is in column uu and row vv; in code it is img[v][u]. A window radius r≥1r \ge 1 and a disparity range 0≤d<D0 \le d < D.

Output. For each pixel pp of each image, the census string T(p)T(p) of n=(2r+1)2−1n = (2r + 1)^2 - 1 bits:

T(p)=∥o∈O  ξ(I(p),I(p+o)),ξ(a,b)={1b<a0b≥aT(p) = \big\Vert_{o \in O} \; \xi\big(I(p), I(p + o)\big), \qquad \xi(a, b) = \begin{cases} 1 & b < a \\ 0 & b \ge a \end{cases}

where OO is the list of offsets (du,dv)(du, dv) of the window without (0,0)(0, 0), in row-major order, and ∥\Vert joins the bits, the first one most significant. For each left pixel p=(u,v)p = (u, v) and disparity dd with u−d≥0u - d \ge 0, the census cost

C(p,d)=popcount⁡(TL(u,v)⊕TR(u−d,v)).C(p, d) = \operatorname{popcount}\big(T_L(u, v) \oplus T_R(u - d, v)\big).

At the image border, a neighbor outside the image takes the value of the nearest border pixel. This is a choice of the code; other programs skip the border pixels.

The algorithm

  1. CENSUS(I, r)
  2. 1for each pixel p = (u, v) of I do
  3. 2c ← 0
  4. 3for each offset o of the window, o ≠ (0, 0), in row-major order do
  5. 4c ← 2c + [I(p + o) < I(p)] ▷ append one bit
  6. 5T(p) ← c
  7. 6return T
  8. COST(T_L, T_R, u, v, d)
  9. 7return popcount(T_L(u, v) xor T_R(u - d, v))

Line L4 shifts the string left by one and appends the new bit, so after the loop of line L3 the string holds the bits of all nn offsets in order. Line L7 marks the bits where the two strings differ with an XOR and counts them. A stereo method calls COST for each pixel and each disparity to fill the cost volume, then aggregates and chooses disparities, as block matching or semi-global matching do. The code also gives the census cost volume and a winner-takes-all disparity map over a small box.

Example

Take r=1r = 1, so n=8n = 8 bits, and these 3×33 \times 3 windows around a left pixel and a right pixel, both with center 14:

left: (1215920141473013),right: (10161118141282915).\text{left: } \begin{pmatrix} 12 & 15 & 9 \\ 20 & \mathbf{14} & 14 \\ 7 & 30 & 13 \end{pmatrix}, \qquad \text{right: } \begin{pmatrix} 10 & 16 & 11 \\ 18 & \mathbf{14} & 12 \\ 8 & 29 & 15 \end{pmatrix}.

In row-major order the left neighbors are 12,15,9,20,14,7,30,1312, 15, 9, 20, 14, 7, 30, 13. Those less than 14 give the bits 1,0,1,0,0,1,0,11, 0, 1, 0, 0, 1, 0, 1, so TL=101001012=165T_L = 10100101_2 = 165. The neighbor 14 equals the center and gives 0. The right neighbors 10,16,11,18,12,8,29,1510, 16, 11, 18, 12, 8, 29, 15 give TR=101011002=172T_R = 10101100_2 = 172. Then TL⊕TR=000010012T_L \oplus T_R = 00001001_2, and the cost is 2: the two windows differ in the order of two neighbors against the center. The rank of the left center, the number of neighbors less than it, is popcount⁡(165)=4\operatorname{popcount}(165) = 4.

Now add 20 to every value of the left window, or square every value: the order inside the window stays the same, so TLT_L stays 165, and the cost stays 2. The sum of absolute differences of the two windows would change from 13 to 181 after adding 20.

Correctness

The full proof is in proofs/correctness.md. It shows three facts. First, after the loop of lines L3 and L4 the integer cc is the string T(p)T(p) read as a binary number, by an invariant on the number of offsets done. Second, line L7 returns the number of offsets at which the two strings differ, because a bit of the XOR is 1 exactly when the two bits differ. Third, for any strictly increasing function gg, the census of g∘Ig \circ I equals the census of II, so the census cost of a pair does not change when each image gets its own strictly increasing change of brightness. The proof also shows that a turn of the image by 90°90° permutes the bits of each interior string.

Proof: Correctness of the census transform and the census costfull

Fix a radius r≥1r \ge 1 and let o1,…,ono_1, \ldots, o_n be the offsets of the window without (0,0)(0, 0) in row-major order, n=(2r+1)2−1n = (2r + 1)^2 - 1. Write ξ(a,b)=1\xi(a, b) = 1 if b<ab < a and 00 otherwise. For a pixel pp of an image II, the census string is the bit string T(p)=ξ(I(p),I(p+o1))…ξ(I(p),I(p+on))T(p) = \xi(I(p), I(p + o_1)) \ldots \xi(I(p), I(p + o_n)), the first bit most significant, where a position outside the image takes the value of the nearest border pixel. We identify a bit string b1…bkb_1 \ldots b_k with the integer ∑i=1kbi2k−i\sum_{i=1}^{k} b_i 2^{k - i}.

Lemma 1. Lines L2 to L5 compute T(p)T(p)

Invariant. After the loop of line L3 has handled the offsets o1,…,oko_1, \ldots, o_k, the integer cc equals the string β1…βk\beta_1 \ldots \beta_k with βi=ξ(I(p),I(p+oi))\beta_i = \xi(I(p), I(p + o_i)).

Start. Before the loop, k=0k = 0 and c=0c = 0, the empty string.

Step. If c=β1…βk=∑i≤kβi2k−ic = \beta_1 \ldots \beta_k = \sum_{i \le k} \beta_i 2^{k - i}, line L4 sets cc to 2c+βk+1=∑i≤kβi2k+1−i+βk+1202c + \beta_{k+1} = \sum_{i \le k} \beta_i 2^{k + 1 - i} + \beta_{k + 1} 2^0, which is the string β1…βk+1\beta_1 \ldots \beta_{k+1}.

End. After k=nk = n steps, c=T(p)c = T(p), and line L5 stores it. Each value is less than 2n2^n, so it fits a word of w≥nw \ge n bits. □\square

Lemma 2. Line L7 returns the number of differing bits

Let a=a1…ana = a_1 \ldots a_n and b=b1…bnb = b_1 \ldots b_n. Bit ii of a⊕ba \oplus b is ai⊕bia_i \oplus b_i, which is 1 exactly when ai≠bia_i \ne b_i. Popcount counts the 1 bits. So line L7 returns ∣{i:ai≠bi}∣\lvert \{ i : a_i \ne b_i \} \rvert, the Hamming distance of aa and bb. □\square

The Hamming distance is a metric on strings of nn bits: it is zero exactly for equal strings, it is symmetric, and it satisfies the triangle inequality because a position where aa and cc differ is a position where aa and bb differ or bb and cc differ. So the census cost satisfies 0≤C(p,d)≤n0 \le C(p, d) \le n.

Theorem 1. Invariance to strictly increasing changes

Let gg be a strictly increasing function on the values of the image, and I′=g∘II' = g \circ I. Then T′(p)=T(p)T'(p) = T(p) for every pixel pp.

Proof. For any two values aa and bb, g(b)<g(a)g(b) < g(a) holds exactly when b<ab < a: if b<ab < a then g(b)<g(a)g(b) < g(a) because gg is strictly increasing, and if b≥ab \ge a then g(b)≥g(a)g(b) \ge g(a) for the same reason. So ξ(g(a),g(b))=ξ(a,b)\xi(g(a), g(b)) = \xi(a, b). The border rule picks the same source pixel in II and I′I', so every bit of T′(p)T'(p) equals the bit of T(p)T(p) at the same offset. □\square

Corollary. If IL′=gL∘ILI'_L = g_L \circ I_L and IR′=gR∘IRI'_R = g_R \circ I_R with two strictly increasing functions gLg_L and gRg_R, possibly different, then the census cost C′(p,d)C'(p, d) of the new pair equals C(p,d)C(p, d) of the old pair for every pixel and disparity, by Theorem 1 and Lemma 2. Any method that depends only on the costs, such as winner-takes-all on box sums of costs, then gives the same disparity map.

The theorem needs one function for the whole image. A change of brightness that varies across the window, such as a strong vignetting edge, can change the order of values inside it, and then the strings change.

Theorem 2. Shifts and turns permute nothing or permute bits

Shift. Let I′(u,v)=I(u−s,v)I'(u, v) = I(u - s, v) for an integer ss. For a pixel p=(u,v)p = (u, v) such that the windows of pp in I′I' and of (u−s,v)(u - s, v) in II lie inside the images, every term ξ(I′(p),I′(p+o))\xi(I'(p), I'(p + o)) equals ξ(I(p−(s,0)),I(p−(s,0)+o))\xi(I(p - (s, 0)), I(p - (s, 0) + o)), so T′(p)=T(p−(s,0))T'(p) = T(p - (s, 0)). This is why a disparity ss between two images of the same flat textured surface gives the cost 0 at disparity ss.

Turn by 90 degrees. Let II have HH rows and put I′(x,y)=I(y,H−1−x)I'(x, y) = I(y, H - 1 - x). The pixel (x,y)(x, y) of I′I' is the pixel (u,v)=(y,H−1−x)(u, v) = (y, H - 1 - x) of II, and the offset (du′,dv′)(du', dv') in I′I' moves to (u+dv′,v−du′)(u + dv', v - du') in II, the offset (dv′,−du′)(dv', -du'). The map (du′,dv′)↦(dv′,−du′)(du', dv') \mapsto (dv', -du') is a bijection of the window offsets without (0,0)(0, 0). So, for a pixel whose window lies inside the image, the bit of T′T' at offset o′o' equals the bit of TT at the image of o′o': the string of the turned image is a fixed permutation of the bits of the string of the original. □\square

The rank transform

The rank of pp is ∣{i:I(p+oi)<I(p)}∣=∑iβi\lvert \{ i : I(p + o_i) < I(p) \} \rvert = \sum_i \beta_i, which is popcount⁡(T(p))\operatorname{popcount}(T(p)) by the definition of T(p)T(p). So the rank is a function of the census, and two pixels with equal census strings have equal ranks. The converse is false: the strings 1010 and 0101 have the same rank 1.

The code

The function census follows lines L1 to L6 with the bits in the order of window_offsets, and Lemma 1 applies. The function hamming is line L7, and Lemma 2 applies; popcount counts the characters 1 in the binary form of the integer, which is the number of 1 bits. The function census_cost_volume gives C(p,d)C(p, d) for u−d≥0u - d \ge 0 and the value n+1>Cn + 1 > C otherwise, so an invalid entry is never smaller than a valid one. The function census_disparity sums these costs over a box clamped to the image and keeps the smallest disparity with the least sum, which is winner-takes-all with ties to the smallest dd.

Complexity

The model is the word RAM with words of ww bits and n=(2r+1)2−1≤wn = (2r + 1)^2 - 1 \le w, so each string fits one word. For r=3r = 3 the string has 48 bits, and a 9×79 \times 7 window has 62 bits; both fit a 64-bit word. Popcount of one word is O(1)O(1), as an instruction or by the SWAR popcount in O(log⁡w)O(\log w) word operations, which is O(1)O(1) for a fixed ww.

  • The transform. Lines L1 to L5 do nn comparisons and shifts per pixel, so Θ(WHr2)\Theta(W H r^2) time for each image, and Θ(WH)\Theta(W H) words for the strings.
  • The costs. Line L7 is O(1)O(1), so the full cost volume of WHDW H D entries takes Θ(WHD)\Theta(W H D) time, the same as the absolute difference cost.
  • Total. The transform of both images and the full cost volume take Θ(WH(r2+D))\Theta(W H (r^2 + D)) time, the bound in the front matter.
  • Larger windows. If n>wn > w, each string takes ⌈n/w⌉\lceil n / w \rceil words and each cost O(n/w)O(n / w) time.

Properties

  • Order only. The census depends only on the order of the values in the window (a theorem). It is unchanged by any strictly increasing change of the image, so it tolerates differences in gain, offset, gamma and exposure between the two cameras, as long as the change is the same over the window.
  • Robust near depth edges. A neighbor on another surface changes at most one bit, whatever its value, so it adds at most 1 to the cost. With the sum of squared differences, one such pixel can dominate the sum. Zabih and Woodfill gave this as the motivation for both transforms.
  • Loses magnitude. Two windows with the same order but very different contrast get cost 0. In flat areas with noise, neighbors close to the center flip their bits at random, so the census of a flat area is noisy.
  • Not symmetric in the center. A neighbor equal to the center gives 0, the same as a brighter one. On images with large flat areas of equal values this treats "equal" as "brighter".
  • Benchmark result. Hirschmüller and Scharstein (2009) compared matching costs on images with changes of exposure and light, and census was among the best overall. This is an empirical finding on their data, not a theorem.

Variants and improvements

  • Rank transform. Zabih and Woodfill also proposed the rank transform: replace each pixel by the number of neighbors less than it, popcount⁡(T(p))\operatorname{popcount}(T(p)), and match the ranks by absolute differences. It keeps less information than the census, because many strings have the same count.
  • Sparse census. Use only every second offset in each direction. The string is about four times shorter, and the cost is close to that of the full window.
  • Center-symmetric census. Compare pairs of pixels that are symmetric about the center, instead of each pixel with the center. The string has half the bits and does not depend on the center value alone.
  • Ternary census. Use three states, darker, similar (within a threshold ϵ\epsilon) and brighter. It is more stable in flat areas, at the price of the threshold.
  • Modified census. Compare each pixel of the window with the mean of the window instead of the center pixel.
  • Census with aggregation. The census cost of one pixel is noisy, so it is summed over a window, as in block matching, or smoothed along paths, as in semi-global matching. This is what the code's census_disparity does with a box.

When to use it

Use the census cost when the two cameras do not have the same response, which is the normal case outside the lab: different exposure, automatic gain, vignetting or a light that hits the two lenses differently. It is cheap in integer hardware, so FPGA and ASIC stereo cameras use it. Use normalized cross-correlation when the change of brightness is affine and you want to keep the contrast information, and the absolute difference or the Birchfield-Tomasi cost when the two images are radiometrically close and fine texture matters. The census is a cost, not a full matcher: it still needs aggregation and a choice of disparities.

Pitfalls

  • Strict or not strict. Use << in both images. Using ≤\le in one and << in the other adds a bit of cost at every flat neighbor.
  • Bit order. Both images must use the same order of offsets, or the Hamming distance compares unrelated bits.
  • Words too short. A 9×99 \times 9 window has 80 bits and does not fit a 64-bit word. Code that packs it into one word silently drops bits.
  • Border. Pixels within rr of the border have windows outside the image. Clamping, as here, gives them strings that repeat the border; skipping them leaves a frame of invalid costs. Either way, do not trust the costs there.
  • Unmatched columns. For u−d<0u - d < 0 the right pixel does not exist. Give that cost a value larger than any real cost, here n+1n + 1, so winner-takes-all never picks it.
  • Flat areas. In a textureless area all costs are small and the census does not help. That is a limit of all local costs, not a bug.

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.

census_transform.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/census-transform/. The authors are listed in prov/GZ7T8F.jsonl.
"""The census transform of Zabih and Woodfill (1994) and the census
matching cost for rectified stereo.

An image is a list of rows of integers (or of any values that can be
ordered); the value at pixel (u, v), column u and row v, is img[v][u].

The census string of pixel p with radius r has one bit for each pixel q of
the (2r + 1) x (2r + 1) window centered on p, except p itself. The bit is 1
if I(q) < I(p) and 0 otherwise. The bits are taken in row-major order of
the offsets (dv, du), from (-r, -r) to (r, r), and the first offset gives
the most significant bit. A neighbor outside the image takes the value of
the nearest border pixel (the coordinates are clamped).

The cost of matching the left pixel (u, v) with the right pixel
(u - d, v) is the Hamming distance of their census strings, the number of
bits in which they differ.
"""

from __future__ import annotations

from typing import List, Sequence, Tuple


def _clamp(x: int, lo: int, hi: int) -> int:
    return lo if x < lo else hi if x > hi else x


def window_offsets(r: int) -> List[Tuple[int, int]]:
    """The offsets (du, dv) of the census window of radius r, without
    (0, 0), in the order of the bits (most significant first)."""
    return [(du, dv) for dv in range(-r, r + 1) for du in range(-r, r + 1)
            if (du, dv) != (0, 0)]


def census(img: Sequence[Sequence[int]], r: int = 2) -> List[List[int]]:
    """The census transform of img with window radius r >= 1. Each entry
    is an integer of (2r + 1)^2 - 1 bits."""
    if r < 1:
        raise ValueError("the radius must be at least 1")
    h, w = len(img), len(img[0])
    offs = window_offsets(r)
    out = []
    for v in range(h):  # @line L1
        row = []
        for u in range(w):  # @line L1
            c = 0  # @line L2
            center = img[v][u]
            for du, dv in offs:  # @line L3
                q = img[_clamp(v + dv, 0, h - 1)][_clamp(u + du, 0, w - 1)]
                c = (c << 1) | (1 if q < center else 0)  # @line L4
            row.append(c)  # @line L5
        out.append(row)
    return out  # @line L6


def popcount(x: int) -> int:
    """The number of 1 bits of the integer x >= 0."""
    return bin(x).count("1")


def hamming(a: int, b: int) -> int:
    """The Hamming distance of two census strings."""
    return popcount(a ^ b)  # @line L7


def census_cost_volume(left: Sequence[Sequence[int]], right: Sequence[Sequence[int]],
                       D: int, r: int = 2) -> List[List[List[int]]]:
    """The census cost C[v][u][d] = hamming(TL[v][u], TR[v][u - d]) for
    0 <= d < D. If u - d < 0 the right pixel does not exist, and the cost
    is the number of bits n + 1, larger than any real cost."""
    tl, tr = census(left, r), census(right, r)
    n = (2 * r + 1) ** 2 - 1
    h, w = len(left), len(left[0])
    return [[[hamming(tl[v][u], tr[v][u - d]) if u - d >= 0 else n + 1
              for d in range(D)] for u in range(w)] for v in range(h)]


def census_disparity(left: Sequence[Sequence[int]], right: Sequence[Sequence[int]],
                     D: int, r: int = 2, a: int = 0) -> List[List[int]]:
    """The winner-takes-all disparity map of the census cost, summed over a
    (2a + 1) x (2a + 1) box (a = 0: no sum). The box is clamped to the
    image. Ties go to the smallest disparity."""
    cv = census_cost_volume(left, right, D, r)
    h, w = len(left), len(left[0])
    out = []
    for v in range(h):
        row = []
        for u in range(w):
            best, bd = None, 0
            for d in range(D):
                s = 0
                for y in range(max(v - a, 0), min(v + a, h - 1) + 1):
                    for x in range(max(u - a, 0), min(u + a, w - 1) + 1):
                        s += cv[y][x][d]
                if best is None or s < best:
                    best, bd = s, d
            row.append(bd)
        out.append(row)
    return out


def rank(img: Sequence[Sequence[int]], r: int = 2) -> List[List[int]]:
    """The rank transform: the number of neighbors in the window that are
    less than the center, which is the popcount of the census string."""
    return [[popcount(c) for c in row] for row in census(img, r)]
test_census_transform.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/census-transform/. The authors are listed in prov/GZ7T8F.jsonl.

import random

import pytest

from census_transform import (
    census,
    census_cost_volume,
    census_disparity,
    hamming,
    popcount,
    rank,
    window_offsets,
)


def brute_census(img, r):
    """A second implementation: list the bits as characters, then parse."""
    h, w = len(img), len(img[0])
    out = []
    for v in range(h):
        row = []
        for u in range(w):
            bits = []
            for dv in range(-r, r + 1):
                for du in range(-r, r + 1):
                    if du == 0 and dv == 0:
                        continue
                    y = min(max(v + dv, 0), h - 1)
                    x = min(max(u + du, 0), w - 1)
                    bits.append("1" if img[y][x] < img[v][u] else "0")
            row.append(int("".join(bits), 2))
        out.append(row)
    return out


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


def test_worked_example():
    left = [[12, 15, 9], [20, 14, 14], [7, 30, 13]]
    right = [[10, 16, 11], [18, 14, 12], [8, 29, 15]]
    cl = census(left, 1)[1][1]
    cr = census(right, 1)[1][1]
    assert cl == 0b10100101 == 165
    assert cr == 0b10101100 == 172
    assert hamming(cl, cr) == 2
    assert rank(left, 1)[1][1] == 4


def test_matches_brute_force():
    rng = random.Random(1)
    for r in (1, 2, 3):
        img = random_image(rng, 11, 8, 0, 9)
        assert census(img, r) == brute_census(img, r)


def test_bit_count_and_constant_image():
    for r in (1, 2, 3):
        offs = window_offsets(r)
        assert len(offs) == (2 * r + 1) ** 2 - 1
        assert len(set(offs)) == len(offs)
    flat = [[7] * 6 for _ in range(5)]
    assert all(c == 0 for row in census(flat, 2) for c in row)
    with pytest.raises(ValueError):
        census(flat, 0)


def test_invariant_to_monotone_change():
    rng = random.Random(2)
    img = random_image(rng, 12, 9)
    for f in (lambda x: 3 * x + 7, lambda x: x * x, lambda x: (x // 1) + 1000):
        img2 = [[f(x) for x in row] for row in img]
        assert census(img2, 2) == census(img, 2)
    # a change that is not monotone does change the string
    img3 = [[255 - x for x in row] for row in img]
    assert census(img3, 2) != census(img, 2)


def test_shift_commutes_in_the_interior():
    rng = random.Random(3)
    img = random_image(rng, 20, 10)
    s = 3
    shifted = [[row[max(u - s, 0)] for u in range(20)] for row in img]
    r = 2
    a, b = census(img, r), census(shifted, r)
    for v in range(10):
        for u in range(s + r, 20 - r):
            assert b[v][u] == a[v][u - s]


def test_rotation_permutes_the_bits():
    rng = random.Random(4)
    h, w, r = 9, 11, 2
    img = random_image(rng, w, h)
    # out[y][x] = img[h - 1 - x][y]: a turn by 90 degrees, w rows and h columns
    rot = [[img[h - 1 - x][y] for x in range(h)] for y in range(w)]
    offs = window_offsets(r)
    n = len(offs)
    pos = {o: n - 1 - i for i, o in enumerate(offs)}
    a, b = census(img, r), census(rot, r)
    for y in range(r, w - r):
        for x in range(r, h - r):
            c = b[y][x]
            u, v = y, h - 1 - x
            for du, dv in offs:
                bit_rot = (c >> pos[(du, dv)]) & 1
                bit_img = (a[v][u] >> pos[(dv, -du)]) & 1
                assert bit_rot == bit_img


def test_hamming_and_popcount():
    assert popcount(0) == 0
    assert popcount(0b1011) == 3
    assert popcount((1 << 48) - 1) == 48
    assert hamming(0b1011, 0b0110) == 3
    rng = random.Random(5)
    for _ in range(100):
        x, y = rng.getrandbits(48), rng.getrandbits(48)
        assert hamming(x, y) == sum(((x >> i) & 1) != ((y >> i) & 1) for i in range(48))


def test_cost_volume_against_brute_force():
    rng = random.Random(6)
    left, right = random_image(rng, 10, 6), random_image(rng, 10, 6)
    D, r = 4, 1
    cv = census_cost_volume(left, right, D, r)
    tl, tr = brute_census(left, r), brute_census(right, r)
    for v in range(6):
        for u in range(10):
            for d in range(D):
                want = bin(tl[v][u] ^ tr[v][u - d]).count("1") if u >= d else 9
                assert cv[v][u][d] == want


def test_disparity_survives_a_gain_and_offset_change():
    rng = random.Random(7)
    w, h, true_d, D = 30, 12, 3, 8
    scene = random_image(rng, w + true_d, h)
    right = [[scene[v][u] for u in range(w)] for v in range(h)]
    left = [[scene[v][u - true_d] if u >= true_d else scene[v][0] for u in range(w)] for v in range(h)]
    # the right camera is brighter and has more gain: a monotone change
    right = [[2 * x + 30 for x in row] for row in right]
    disp = census_disparity(left, right, D, r=2, a=1)
    margin = D + 3
    for v in range(h):
        for u in range(margin, w - 3):
            assert disp[v][u] == true_d

History

Zabih and Woodfill (1994) proposed the rank and the census transforms as non-parametric local transforms, to make correspondence robust against changes of brightness and against the outliers that a window collects near a depth edge. Woodfill later built census stereo into hardware. Hirschmüller and Scharstein (2009) found census to be one of the most robust costs in their evaluation, and census became the usual cost of semi-global matching in embedded and automotive stereo.

References

  1. Ramin Zabih and John Woodfill, Non-parametric local transforms for computing visual correspondence, Computer Vision, ECCV '94, Lecture Notes in Computer Science 801, Springer, 1994, 151-158, the whole paper (the rank transform, the census transform, and the Hamming distance as the cost of the census)
  2. Heiko Hirschmüller and Daniel Scharstein, Evaluation of stereo matching costs on images with radiometric differences, IEEE Transactions on Pattern Analysis and Machine Intelligence 31(9), 2009, the comparison of census with other matching costs under changes of exposure and light
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (the matching costs of local methods, among them the census transform)

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