Algorithmadvanced
Voxel coloring
Also called Seitz-Dyer voxel coloring.
Visit voxels in layers of growing distance from the cameras and color each one whose still unexplained pixels agree. Needs no scene point inside the convex hull of the cameras.
- Solves
- Multi-view stereo
- Time
- Θ(N W H n) worst · average · best
- Space
- O(N W H n + n^3) extra
- Where
- H = the image height in pixels; N = the number of images; W = the image width in pixels; n = the number of voxels along each side of the grid
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Steven M. Seitz, Charles R. Dyer, 1997
Voxel coloring reconstructs a colored 3D scene from many calibrated images in a single pass over a voxel grid. It needs one condition on the cameras: no point of the scene may lie inside the convex hull of the camera centers. Then the voxels can be visited in layers of growing distance from the cameras, so that a voxel is always visited before every voxel it can hide. A voxel is kept and colored when the pixels that see it, and that no nearer kept voxel explains, agree in color. Space carving solves the same task without the condition on the cameras, but must repeat its passes until nothing changes. Voxel coloring returns the consistent scene that is nearest to the cameras, while space carving returns the largest one, the photo hull.
In plain words
Imagine several cameras that all look at a scene from one side, for example from above a table. Cut the space into thin slices, from the slice nearest to the cameras to the slice farthest away. Walk through the slices in that order. In each slice, look at each small cube and ask the cameras what color they see in its direction. Ignore the camera pixels that a cube in an earlier slice already explains, because those pixels show that earlier cube. If the remaining pixels all show the same color, keep the cube with that color and tick off those pixels. A cube is never seen through another cube, so one walk through the slices is enough.
The problem
Input.
- images of size . Each pixel has a gray value or the mark for background.
- The cameras, as , , with (see pinhole camera model).
- A grid of voxels that contains the scene, with voxels along each side, and a threshold .
The ordinal visibility constraint. There must be a function on the points of the scene such that whenever can hide from some camera. Seitz and Dyer show that the distance to the convex hull of the camera centers is such a function when no scene point lies inside that hull. The code takes the simplest case: all camera centers lie below the plane , the grid lies above it, and . The voxels with the same form a layer, and each pixel ray meets each layer in at most one voxel, at its point on the middle plane of the layer.
The test. A set of pixels passes if it has no background pixel and its largest and smallest values differ by at most . This is a monotone form of photo-consistency for a Lambertian scene.
Output. A set of colored voxels in which each voxel passes the test on the pixels that see it, and that explains every non-background pixel. The code also returns a flag that is false if some non-background pixel stays unexplained.
The algorithm
VOXEL-COLOR(rays, images, L, τ)- 1
S ← ∅; mark no pixel - 2
for k ← 0 to L - 1 do ▷ layers, nearest first - 3
for each voxel v of layer k do - 4
π(v) ← the unmarked pixels whose ray meets layer k at v - 5
if π(v) is not empty and passes the test then add v to S with the mean color of π(v) - 6
mark every pixel of π(v) for each voxel v added in this layer - 7
return S, and whether every non-background pixel is marked
Line L4, the footprint. The pixels that see are those whose rays meet . Marked pixels already show a voxel of an earlier layer, which hides from them, so they are left out. The code finds all footprints of a layer in one pass over the unmarked pixels, by grouping them by the voxel their ray meets.
Line L6, marking after the layer. The pixels are marked only after the whole layer is done. Two voxels of the same layer never hide each other along a ray, so the order inside a layer does not matter.
Line L5, the test. Seitz and Dyer use the standard deviation of the colors, or a chi-square form of it with the noise level of the camera. The code uses the range of the colors, which is monotone, so that the proof holds exactly.
Example
A floor with blocks in front. The test file uses a grid and four cameras below it with images. The true scene is the whole far layer (16 voxels), which acts as a floor, and 11 voxels in the two nearer layers, with gray values from . The images have 207 pixels that are not background.
With , voxel coloring keeps 21 voxels: 5 in the nearest layer, 13 in the middle layer and 3 in the far layer. Seven of them are empty in the true scene, and 13 true voxels are missing. Still, the result is photo-consistent, and every pixel sees a voxel at the same layer as in the true scene or at a nearer one. This is the meaning of the output: of all scenes that explain the images, it is the one nearest to the cameras. The true voxels that are missing are hidden in all four views, or are replaced by a nearer voxel that the images cannot tell apart from them.
The test file also checks the theorem by brute force. On grids of 8 and 12 voxels it lists every consistent scene, computes for each pixel the nearest voxel that any of them lets the pixel see, and compares this set with the output.
Correctness
The full proof is in proofs/correctness.md. For each pixel , let be the nearest layer at which some consistent scene gives an owner, and let be the voxel of the ray of at that layer. The set of all is the scene of Seitz and Dyer.
- is consistent. No voxel of lies in front of on the ray of , and the pixels that a voxel owns in are a subset of those it owns in a consistent scene. The monotone test then carries over.
- The invariant. Before layer , the unmarked pixels are exactly those with . A voxel of layer passes if and only if it is in . If it is in , its footprint is a subset of its pixels in a consistent scene. If it is not in but passed, adding it to would give a consistent scene in which some pixel has an owner nearer than .
So the output is whenever any consistent scene exists. With a test that is not monotone, such as a threshold on the standard deviation, the argument breaks and the method is a heuristic.
Proof: Voxel coloring returns the consistent scene that is nearest to the cameras at every pixelfull
We use the layered model and the pseudocode of the page. The voxels are split into layers in order of distance from the cameras. The ray of each pixel meets each layer in at most one voxel, . Each pixel has a value , which is a gray value or the background mark .
For a set of voxels , the owner of a pixel is for the least with , or nothing. The pixels of are . The test on a multiset of values is true if and , and true for the empty multiset. It is monotone: if holds and , then holds, because and the range of is at most the range of .
A scene is consistent if holds for every and every pixel with has an owner in . Assume that at least one consistent scene exists. For each pixel let
with if no consistent scene gives an owner. For let , and let . This is the scene of Seitz and Dyer: each pixel sees the nearest voxel that any consistent scene lets it see.
Lemma 1. Every pixel has if , and no owner in if .
Proof. Suppose some equals with . Let be a consistent scene with , so . Then has an owner in at a layer at most , which contradicts the minimum in the definition of . So no voxel of lies on the ray of before layer . If , the voxel lies at layer , so it is the owner. If , no voxel of lies on the ray at all.
Lemma 2. is consistent.
Proof. Let , with in layer , and let be consistent with . By Lemma 1, . For such a , and , so the owner of in is at a layer at most . It is also at a layer at least . So , and . The test holds on , so it holds on by monotonicity. A pixel with has an owner in the consistent scene that is assumed to exist, so and has the owner in by Lemma 1.
Let be the set of unmarked pixels at the start of layer in line L2, and let , which is the set of line L4.
Lemma 3 (invariant). For every : , and a voxel of layer is colored at line L5 if and only if .
Proof. By induction on . is the set of all pixels, as line L1 marks none.
Assume and let be in layer .
(a) Suppose , so with . Then and , so is not empty. Let be a consistent scene with . Take any . Then , so the owner of in is at a layer at least . But , so the owner is at a layer at most . Hence , and . The test holds on , so it holds on , and is colored.
(b) Suppose and, to get a contradiction, that is colored, so is not empty and passes the test. Every has : if , then . Let . For a pixel with and , Lemma 1 says that no voxel of is on the ray of before layer , so . For a pixel with and , the owner is in front of and does not change. So , which passes. Every other voxel of owns in a subset of what it owns in , so it passes by Lemma 2 and monotonicity. Every pixel with still has an owner. So is consistent, and a pixel has its owner in at layer . Then , which is a contradiction.
Line L6 marks the pixels of for the colored voxels of layer , which are the voxels of in layer . A pixel with has , so it is marked. A pixel with has by Lemma 1, so it stays unmarked. Thus .
Theorem. If a consistent scene exists, VOXEL-COLOR returns , it is consistent, and the flag of line L7 is true. Each colored voxel gets the mean of the values of the pixels it owns in . If the flag is false, no consistent scene exists.
Proof. By Lemma 3 the colored voxels of all layers form , which is consistent by Lemma 2. The pixels that a colored voxel of layer owns in are those with , which is the set whose mean line L5 stores. After the last layer, , and these pixels have by Lemma 2, so the flag is true. The last claim is the contrapositive.
Remarks.
- The scene is one of possibly many consistent scenes. It is the nearest one at every pixel: in any consistent scene , the owner of is at a layer at least , the layer of its owner in .
- The only facts used about the order of the voxels are that each ray meets each layer at most once and visits the layers in increasing order. This is what the ordinal visibility constraint of Seitz and Dyer provides when no scene point lies inside the convex hull of the camera centers.
- The proof needs the monotone test. Seitz and Dyer use the standard deviation of the colors, or a chi-square form of it, which is not monotone, so for their test the result is a heuristic, not this theorem.
Complexity
The model is the real RAM. With layers, each layer costs one pass over all pixels plus the test on the footprints, which together have at most pixels. The total is in every case.
The code stores the voxel of each layer for each pixel, , and the colored voxels, . Seitz and Dyer compute the footprints on the fly and store only the images and one bit per pixel for the marks, which is besides the output. They count the cost per voxel as the size of its footprint and state a bound linear in the number of voxels and the number of images.
Properties
- One pass. Each voxel is tested once. No voxel is changed after its layer.
- Exact visibility. Under the ordinal visibility constraint, the marks give the exact set of pixels that see each voxel.
- Nearest consistent scene. The result is consistent, and at each pixel its surface is as near to the cameras as any consistent scene allows. It is contained in the photo hull of space carving, but it is usually smaller.
- Restricted camera positions. No scene point may lie inside the convex hull of the camera centers. Cameras all around an object break this.
- No smoothness term. Each voxel is judged only by its colors.
Variants and improvements
- Space carving. Kutulakos and Seitz drop the camera condition by plane sweeps in six directions, each using only the cameras on one side of the plane, and repeat them until no voxel changes.
- Generalized voxel coloring. Culbertson, Malzbender and Slabaugh keep exact visibility for any camera positions with item buffers that record, for each pixel, which surface voxel it sees.
- Other layer shapes. The layers need not be planes. Any layers work if the distance to the convex hull of the camera centers grows from layer to layer, for example shells around a region from which the cameras look outward.
- Adaptive grids. An octree refines the grid near the surface, which saves memory at high resolution.
- Probabilistic tests. Later methods replace the hard threshold with a probability of occupancy, which makes the result less sensitive to noise.
When to use it
Use voxel coloring when the cameras are all on one side of the scene, for example a camera that moves along a path in front of a room or above a table, and you want a colored model in one fast pass with exact visibility. If the cameras surround the object, use space carving or a method based on depth maps. For high quality surfaces of real objects, modern multi-view stereo with depth map fusion is better.
Pitfalls
- Cameras around the object. If a scene point is inside the convex hull of the camera centers, no layer order respects visibility, and voxels are tested against pixels that do not see them.
- Bulges in textureless areas. Where the surface has no texture, voxels in front of it also pass the test, and the result bulges toward the cameras. This follows from the output being the nearest consistent scene.
- A tight threshold. One noisy pixel can make a true voxel fail. Its pixels stay unmarked, and a wrong voxel farther away may then take them.
- The standard deviation test. It is not monotone, so the proof does not hold for it, and adding pixels can make a failing voxel pass.
- Coarse footprints. A voxel covers several pixels in each image. Treating each pixel as one ray, as the code does, misses voxels that cover only part of a pixel.
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/voxel-coloring/. The authors are listed in prov/1NZA21.jsonl.
"""Voxel coloring (Seitz and Dyer) in a layered model.
The grid has nx * ny * nz unit voxels; voxel (i, j, k) is the cube
[i, i+1] x [j, j+1] x [k, k+1]. All camera centers lie below the plane z = 0
and every pixel ray goes up (its direction has a positive z part), so no scene
point is inside the convex hull of the camera centers and z orders the voxels
by visibility. The ray of a pixel meets layer k at the voxel that contains its
point on the plane z = k + 0.5, or at no voxel. A camera is (K, R, t) with
X_c = R X + t. Pixel values are gray numbers, or None for a background pixel.
"""
import math
def inverse_intrinsics(K):
"""K^-1 for K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
fx, s, cx = K[0]
fy, cy = K[1][1], K[1][2]
return [[1.0 / fx, -s / (fx * fy), (s * cy - cx * fy) / (fx * fy)],
[0.0, 1.0 / fy, -cy / fy],
[0.0, 0.0, 1.0]]
def layer_cells(cam, u, v, dims):
"""The voxel of each layer k that the ray of pixel (u, v) meets, or None."""
K, R, t = cam
Ki = inverse_intrinsics(K)
m = [Ki[r][0] * u + Ki[r][1] * v + Ki[r][2] for r in range(3)]
d = [sum(R[r][c] * m[r] for r in range(3)) for c in range(3)]
C = [-sum(R[r][c] * t[r] for r in range(3)) for c in range(3)]
if C[2] >= 0.0 or d[2] <= 0.0:
raise ValueError("cameras must lie below z = 0 and look up")
cells = []
for k in range(dims[2]):
s = (k + 0.5 - C[2]) / d[2]
i, j = int(math.floor(C[0] + s * d[0])), int(math.floor(C[1] + s * d[1]))
cells.append((i, j, k) if 0 <= i < dims[0] and 0 <= j < dims[1] else None)
return cells
def build_rays(cams, width, height, dims):
"""rays[c][v * width + u] is the list of layer voxels of pixel (u, v) of camera c."""
return [[layer_cells(cam, float(u), float(v), dims)
for v in range(height) for u in range(width)] for cam in cams]
def render(rays, scene):
"""Images of a voxel scene {voxel: gray value}: the value of the first voxel on each ray, else None."""
images = []
for lists in rays:
img = []
for cells in lists:
val = None
for c in cells:
if c is not None and c in scene:
val = scene[c]
break
img.append(val)
images.append(img)
return images
def consistent(values, tau):
"""The monotone test: no background pixel, and max - min <= tau."""
if any(x is None for x in values):
return False
return not values or max(values) - min(values) <= tau
def voxel_color(rays, images, nz, tau):
"""One pass over the layers, nearest first. Returns (scene, ok): scene maps
each colored voxel to the mean of its pixels, and ok tells whether every
non-background pixel was explained (if not, no consistent scene exists)."""
scene = {} # @line L1
marked = [[False] * len(img) for img in images]
for k in range(nz): # @line L2
footprint = {}
for c, lists in enumerate(rays): # @line L3
for p, cells in enumerate(lists):
if not marked[c][p] and cells[k] is not None:
footprint.setdefault(cells[k], []).append((c, p)) # @line L4
new = []
for v, pixels in footprint.items():
values = [images[c][p] for c, p in pixels]
if consistent(values, tau): # @line L5
scene[v] = sum(values) / len(values)
new.extend(pixels)
for c, p in new: # @line L6
marked[c][p] = True
ok = all(marked[c][p] or val is None
for c, img in enumerate(images) for p, val in enumerate(img))
return scene, ok # @line L7
def owners(rays, shape):
"""The owner of each pixel in a set of voxels: the first voxel of its ray in the set."""
out = []
for lists in rays:
row = []
for cells in lists:
o = None
for c in cells:
if c is not None and c in shape:
o = c
break
row.append(o)
out.append(row)
return out
def is_consistent_scene(shape, rays, images, tau):
"""Every voxel passes the test on the pixels it owns, and every non-background pixel has an owner."""
own = owners(rays, shape)
groups = {}
for c, row in enumerate(own):
for p, o in enumerate(row):
if o is None:
if images[c][p] is not None:
return False
else:
groups.setdefault(o, []).append(images[c][p])
return all(consistent(vals, tau) for vals in groups.values())
def closest_consistent_scene_brute_force(volume, rays, images, tau):
"""S-bar of Seitz and Dyer: for each pixel, the nearest voxel that owns it in some consistent scene."""
cells = sorted(volume)
best = {}
for mask in range(1 << len(cells)):
shape = {cells[i] for i in range(len(cells)) if mask >> i & 1}
if not is_consistent_scene(shape, rays, images, tau):
continue
for c, row in enumerate(owners(rays, shape)):
for p, o in enumerate(row):
if o is not None and ((c, p) not in best or o[2] < best[(c, p)][2]):
best[(c, p)] = o
return set(best.values())
test_voxel_coloring.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/voxel-coloring/. The authors are listed in prov/1NZA21.jsonl.
import random
import unittest
from voxel_coloring import (build_rays, closest_consistent_scene_brute_force, consistent,
is_consistent_scene, layer_cells, owners, render, voxel_color)
def cams_below(dims, offsets, w, f, h=4.0):
K = [[f, 0.0, (w - 1) / 2.0], [0.0, f, (w - 1) / 2.0], [0.0, 0.0, 1.0]]
R = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
cams = []
for dx, dy in offsets:
C = (dims[0] / 2.0 + dx, dims[1] / 2.0 + dy, -h)
cams.append((K, R, [-C[0], -C[1], -C[2]]))
return cams
OFFSETS = [(-1.5, 0.0), (1.5, 0.5), (0.0, -1.5), (0.3, 1.6)]
def grid(dims):
return [(i, j, k) for i in range(dims[0]) for j in range(dims[1]) for k in range(dims[2])]
class VoxelColoringTest(unittest.TestCase):
def test_layer_cells_of_central_ray(self):
cam = cams_below((2, 2, 3), [(0.0, 0.0)], 5, 8.0)[0]
self.assertEqual(layer_cells(cam, 2.0, 2.0, (2, 2, 3)), [(1, 1, 0), (1, 1, 1), (1, 1, 2)])
bad = ([[8.0, 0.0, 2.0], [0.0, 8.0, 2.0], [0.0, 0.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [0.0, 0.0, -1.0])
with self.assertRaises(ValueError):
layer_cells(bad, 2.0, 2.0, (2, 2, 3))
def test_equals_closest_consistent_scene(self):
rng = random.Random(2)
for dims, trials in (((2, 2, 2), 4), ((3, 2, 2), 2), ((2, 2, 3), 2)):
rays = build_rays(cams_below(dims, OFFSETS, 6, 8.0), 6, 6, dims)
vol = grid(dims)
for _ in range(trials):
truth = {c: rng.choice([10, 50]) for c in vol if rng.random() < 0.5}
images = render(rays, truth)
for tau in (0, 40):
scene, ok = voxel_color(rays, images, dims[2], tau)
self.assertTrue(ok)
self.assertTrue(is_consistent_scene(set(scene), rays, images, tau))
self.assertEqual(set(scene),
closest_consistent_scene_brute_force(vol, rays, images, tau))
def test_colors_are_the_true_colors(self):
rng = random.Random(9)
dims = (4, 4, 3)
rays = build_rays(cams_below(dims, OFFSETS, 10, 12.0), 10, 10, dims)
truth = {c: rng.choice([0, 100, 200]) for c in grid(dims) if c[2] == 0 or rng.random() < 0.3}
images = render(rays, truth)
scene, ok = voxel_color(rays, images, dims[2], 0)
self.assertTrue(ok)
self.assertTrue(is_consistent_scene(set(scene), rays, images, 0))
for v, color in scene.items():
self.assertEqual(color, truth[v])
def test_result_is_nearest_not_true_scene(self):
rng = random.Random(9)
dims = (4, 4, 3)
rays = build_rays(cams_below(dims, OFFSETS, 10, 12.0), 10, 10, dims)
truth = {c: rng.choice([0, 100, 200]) for c in grid(dims)
if c[2] == 2 or (c[2] < 2 and rng.random() < 0.25)}
images = render(rays, truth)
scene, ok = voxel_color(rays, images, dims[2], 0)
self.assertTrue(ok)
self.assertTrue(is_consistent_scene(set(truth), rays, images, 0))
self.assertTrue(is_consistent_scene(set(scene), rays, images, 0))
self.assertEqual((len(truth), len(scene), len(set(scene) - set(truth))), (27, 21, 7))
mine, true = owners(rays, set(scene)), owners(rays, set(truth))
for row_a, row_b in zip(mine, true):
for a, b in zip(row_a, row_b):
self.assertEqual(a is None, b is None)
if a is not None:
self.assertLessEqual(a[2], b[2])
def test_flag_tells_if_a_consistent_scene_exists(self):
rng = random.Random(4)
dims = (2, 2, 2)
rays = build_rays(cams_below(dims, OFFSETS, 6, 8.0), 6, 6, dims)
vol = grid(dims)
seen = set()
for trial in range(6):
truth = {c: rng.choice([10, 50]) for c in vol if rng.random() < 0.6}
images = render(rays, truth)
c = rng.randrange(len(images))
fg = [p for p, x in enumerate(images[c]) if x is not None]
if fg and trial % 2 == 1:
images[c][rng.choice(fg)] = 30
_, ok = voxel_color(rays, images, dims[2], 0)
exists = bool(closest_consistent_scene_brute_force(vol, rays, images, 0)) or \
all(x is None for img in images for x in img)
self.assertEqual(ok, exists)
seen.add(ok)
self.assertEqual(seen, {True, False})
def test_monotone_test(self):
self.assertTrue(consistent([], 0))
self.assertTrue(consistent([3, 5], 2))
self.assertFalse(consistent([3, 6], 2))
self.assertFalse(consistent([3, None], 9))
if __name__ == "__main__":
unittest.main()
History
Seitz and Dyer presented voxel coloring at CVPR 1997 and in a longer journal version in the International Journal of Computer Vision in 1999. They introduced the ordinal visibility constraint and showed that, under it, a single pass over the voxels in order of distance gives a consistent scene with exact visibility. Kutulakos and Seitz then generalized the idea to space carving for any camera positions, and Culbertson, Malzbender and Slabaugh gave generalized voxel coloring with item buffers.
References
- Steven M. Seitz and Charles R. Dyer, Photorealistic scene reconstruction by voxel coloring, International Journal of Computer Vision 35(2), 1999, pages 151 to 173, Section 3.1 (the ordinal visibility constraint), Section 3.2 (the consistent scene that is closest to the cameras), Section 4.1 (layers), Section 4.2 (the voxel consistency test), Section 4.3 (the single-pass algorithm) and Section 4.4 (the cost)
- Kiriakos N. Kutulakos and Steven M. Seitz, A theory of shape by space carving, International Journal of Computer Vision 38(3), 2000, pages 199 to 218, Section 2.2 (monotone consistency checks) and Section 5 (plane sweeps for cameras in general position)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 12.7.2, Volumetric and 3D surface reconstruction
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 1NZA21 Edit this page History Report an error Markdown