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
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and each cost of the cost volume costs , 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 , of pixels, with integer or real values. Pixel is in column and row ; in code it is img[v][u]. A window radius and a disparity range .
Output. For each pixel of each image, the census string of bits:
where is the list of offsets of the window without , in row-major order, and joins the bits, the first one most significant. For each left pixel and disparity with , the census cost
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
CENSUS(I, r)- 1
for each pixel p = (u, v) of I do - 2
c ← 0 - 3
for each offset o of the window, o ≠ (0, 0), in row-major order do - 4
c ← 2c + [I(p + o) < I(p)] ▷ append one bit - 5
T(p) ← c - 6
return T COST(T_L, T_R, u, v, d)- 7
return 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 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 , so bits, and these windows around a left pixel and a right pixel, both with center 14:
In row-major order the left neighbors are . Those less than 14 give the bits , so . The neighbor 14 equals the center and gives 0. The right neighbors give . Then , 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 .
Now add 20 to every value of the left window, or square every value: the order inside the window stays the same, so 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 is the string 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 , the census of equals the census of , 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 permutes the bits of each interior string.
Proof: Correctness of the census transform and the census costfull
Fix a radius and let be the offsets of the window without in row-major order, . Write if and otherwise. For a pixel of an image , the census string is the bit string , the first bit most significant, where a position outside the image takes the value of the nearest border pixel. We identify a bit string with the integer .
Lemma 1. Lines L2 to L5 compute
Invariant. After the loop of line L3 has handled the offsets , the integer equals the string with .
Start. Before the loop, and , the empty string.
Step. If , line L4 sets to , which is the string .
End. After steps, , and line L5 stores it. Each value is less than , so it fits a word of bits.
Lemma 2. Line L7 returns the number of differing bits
Let and . Bit of is , which is 1 exactly when . Popcount counts the 1 bits. So line L7 returns , the Hamming distance of and .
The Hamming distance is a metric on strings of bits: it is zero exactly for equal strings, it is symmetric, and it satisfies the triangle inequality because a position where and differ is a position where and differ or and differ. So the census cost satisfies .
Theorem 1. Invariance to strictly increasing changes
Let be a strictly increasing function on the values of the image, and . Then for every pixel .
Proof. For any two values and , holds exactly when : if then because is strictly increasing, and if then for the same reason. So . The border rule picks the same source pixel in and , so every bit of equals the bit of at the same offset.
Corollary. If and with two strictly increasing functions and , possibly different, then the census cost of the new pair equals 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 for an integer . For a pixel such that the windows of in and of in lie inside the images, every term equals , so . This is why a disparity between two images of the same flat textured surface gives the cost 0 at disparity .
Turn by 90 degrees. Let have rows and put . The pixel of is the pixel of , and the offset in moves to in , the offset . The map is a bijection of the window offsets without . So, for a pixel whose window lies inside the image, the bit of at offset equals the bit of at the image of : the string of the turned image is a fixed permutation of the bits of the string of the original.
The rank transform
The rank of is , which is by the definition of . 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 and 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 for and the value 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 .
Complexity
The model is the word RAM with words of bits and , so each string fits one word. For the string has 48 bits, and a window has 62 bits; both fit a 64-bit word. Popcount of one word is , as an instruction or by the SWAR popcount in word operations, which is for a fixed .
- The transform. Lines L1 to L5 do comparisons and shifts per pixel, so time for each image, and words for the strings.
- The costs. Line L7 is , so the full cost volume of entries takes time, the same as the absolute difference cost.
- Total. The transform of both images and the full cost volume take time, the bound in the front matter.
- Larger windows. If , each string takes words and each cost 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, , 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 ) 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_disparitydoes 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 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 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 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 the right pixel does not exist. Give that cost a value larger than any real cost, here , 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.
# 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GZ7T8F Edit this page History Report an error Markdown