Algorithm Search⌘K

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.

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
Properties
deterministicexactofflineiterative
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.

  • NN images of size W×HW \times H. Each pixel has a gray value or the mark ⊥\bot for background.
  • The cameras, as KK, RR, tt with Xc=RX+tX_c = R X + t (see pinhole camera model).
  • A grid of voxels that contains the scene, with nn voxels along each side, and a threshold τ≥0\tau \ge 0.

The ordinal visibility constraint. There must be a function DD on the points of the scene such that D(P)<D(Q)D(P) < D(Q) whenever PP can hide QQ 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 z=0z = 0, the grid lies above it, and D=zD = z. The voxels with the same zz 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 τ\tau. 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

  1. VOXEL-COLOR(rays, images, L, τ)
  2. 1S ← ∅; mark no pixel
  3. 2for k ← 0 to L - 1 do ▷ layers, nearest first
  4. 3for each voxel v of layer k do
  5. 4π(v) ← the unmarked pixels whose ray meets layer k at v
  6. 5if π(v) is not empty and passes the test then add v to S with the mean color of π(v)
  7. 6mark every pixel of π(v) for each voxel v added in this layer
  8. 7return S, and whether every non-background pixel is marked

Line L4, the footprint. The pixels that see vv are those whose rays meet vv. Marked pixels already show a voxel of an earlier layer, which hides vv 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 4×4×34 \times 4 \times 3 grid and four cameras below it with 10×1010 \times 10 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 {0,100,200}\{0, 100, 200\}. The images have 207 pixels that are not background.

With τ=0\tau = 0, 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 pp, let ℓ(p)\ell(p) be the nearest layer at which some consistent scene gives pp an owner, and let VpV_p be the voxel of the ray of pp at that layer. The set Sˉ\bar S of all VpV_p is the scene of Seitz and Dyer.

  1. Sˉ\bar S is consistent. No voxel of Sˉ\bar S lies in front of VpV_p on the ray of pp, and the pixels that a voxel owns in Sˉ\bar S are a subset of those it owns in a consistent scene. The monotone test then carries over.
  2. The invariant. Before layer kk, the unmarked pixels are exactly those with ℓ(p)≥k\ell(p) \ge k. A voxel of layer kk passes if and only if it is in Sˉ\bar S. If it is in Sˉ\bar S, its footprint is a subset of its pixels in a consistent scene. If it is not in Sˉ\bar S but passed, adding it to Sˉ\bar S would give a consistent scene in which some pixel has an owner nearer than ℓ(p)\ell(p).

So the output is Sˉ\bar S 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 0,1,…,L−10, 1, \dots, L - 1 in order of distance from the cameras. The ray of each pixel pp meets each layer kk in at most one voxel, rk(p)r_k(p). Each pixel has a value I(p)I(p), which is a gray value or the background mark ⊥\bot.

For a set of voxels SS, the owner oS(p)o_S(p) of a pixel is rj(p)r_j(p) for the least jj with rj(p)∈Sr_j(p) \in S, or nothing. The pixels of vv are PS(v)={p:oS(p)=v}P_S(v) = \{p : o_S(p) = v\}. The test c(A)c(A) on a multiset of values is true if ⊥∉A\bot \notin A and max⁡A−min⁡A≤τ\max A - \min A \le \tau, and true for the empty multiset. It is monotone: if c(A)c(A) holds and B⊆AB \subseteq A, then c(B)c(B) holds, because ⊥∉B\bot \notin B and the range of BB is at most the range of AA.

A scene SS is consistent if c(I(PS(v)))c(I(P_S(v))) holds for every v∈Sv \in S and every pixel with I(p)≠⊥I(p) \ne \bot has an owner in SS. Assume that at least one consistent scene exists. For each pixel let

ℓ(p)=min⁡{j:oS(p)=rj(p) for some consistent scene S},\ell(p) = \min \{ j : o_S(p) = r_j(p) \text{ for some consistent scene } S \},

with ℓ(p)=∞\ell(p) = \infty if no consistent scene gives pp an owner. For ℓ(p)<∞\ell(p) < \infty let Vp=rℓ(p)(p)V_p = r_{\ell(p)}(p), and let Sˉ={Vp:ℓ(p)<∞}\bar S = \{V_p : \ell(p) < \infty\}. 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 qq has oSˉ(q)=Vqo_{\bar S}(q) = V_q if ℓ(q)<∞\ell(q) < \infty, and no owner in Sˉ\bar S if ℓ(q)=∞\ell(q) = \infty.

Proof. Suppose some Vr∈SˉV_r \in \bar S equals rj(q)r_j(q) with j<ℓ(q)j < \ell(q). Let SrS_r be a consistent scene with oSr(r)=Vro_{S_r}(r) = V_r, so Vr∈SrV_r \in S_r. Then qq has an owner in SrS_r at a layer at most jj, which contradicts the minimum in the definition of ℓ(q)\ell(q). So no voxel of Sˉ\bar S lies on the ray of qq before layer ℓ(q)\ell(q). If ℓ(q)<∞\ell(q) < \infty, the voxel Vq∈SˉV_q \in \bar S lies at layer ℓ(q)\ell(q), so it is the owner. If ℓ(q)=∞\ell(q) = \infty, no voxel of Sˉ\bar S lies on the ray at all. □\square

Lemma 2. Sˉ\bar S is consistent.

Proof. Let w∈Sˉw \in \bar S, with w=Vrw = V_r in layer j=ℓ(r)j = \ell(r), and let SrS_r be consistent with oSr(r)=wo_{S_r}(r) = w. By Lemma 1, PSˉ(w)={q:Vq=w}P_{\bar S}(w) = \{q : V_q = w\}. For such a qq, ℓ(q)=j\ell(q) = j and rj(q)=w∈Srr_j(q) = w \in S_r, so the owner of qq in SrS_r is at a layer at most jj. It is also at a layer at least ℓ(q)=j\ell(q) = j. So oSr(q)=wo_{S_r}(q) = w, and PSˉ(w)⊆PSr(w)P_{\bar S}(w) \subseteq P_{S_r}(w). The test holds on PSr(w)P_{S_r}(w), so it holds on PSˉ(w)P_{\bar S}(w) by monotonicity. A pixel with I(q)≠⊥I(q) \ne \bot has an owner in the consistent scene that is assumed to exist, so ℓ(q)<∞\ell(q) < \infty and qq has the owner VqV_q in Sˉ\bar S by Lemma 1. □\square

Let UkU_k be the set of unmarked pixels at the start of layer kk in line L2, and let πk(v)={p∈Uk:rk(p)=v}\pi_k(v) = \{p \in U_k : r_k(p) = v\}, which is the set of line L4.

Lemma 3 (invariant). For every kk: Uk={p:ℓ(p)≥k}U_k = \{p : \ell(p) \ge k\}, and a voxel vv of layer kk is colored at line L5 if and only if v∈Sˉv \in \bar S.

Proof. By induction on kk. U0U_0 is the set of all pixels, as line L1 marks none.

Assume Uk={p:ℓ(p)≥k}U_k = \{p : \ell(p) \ge k\} and let vv be in layer kk.

(a) Suppose v∈Sˉv \in \bar S, so v=Vp0v = V_{p_0} with ℓ(p0)=k\ell(p_0) = k. Then p0∈Ukp_0 \in U_k and p0∈πk(v)p_0 \in \pi_k(v), so πk(v)\pi_k(v) is not empty. Let SS be a consistent scene with oS(p0)=vo_S(p_0) = v. Take any p∈πk(v)p \in \pi_k(v). Then ℓ(p)≥k\ell(p) \ge k, so the owner of pp in SS is at a layer at least kk. But rk(p)=v∈Sr_k(p) = v \in S, so the owner is at a layer at most kk. Hence oS(p)=vo_S(p) = v, and πk(v)⊆PS(v)\pi_k(v) \subseteq P_S(v). The test holds on PS(v)P_S(v), so it holds on πk(v)\pi_k(v), and vv is colored.

(b) Suppose v∉Sˉv \notin \bar S and, to get a contradiction, that vv is colored, so πk(v)\pi_k(v) is not empty and passes the test. Every p∈πk(v)p \in \pi_k(v) has ℓ(p)>k\ell(p) > k: if ℓ(p)=k\ell(p) = k, then v=rk(p)=Vp∈Sˉv = r_k(p) = V_p \in \bar S. Let T=Sˉ∪{v}T = \bar S \cup \{v\}. For a pixel pp with rk(p)=vr_k(p) = v and ℓ(p)>k\ell(p) > k, Lemma 1 says that no voxel of Sˉ\bar S is on the ray of pp before layer ℓ(p)\ell(p), so oT(p)=vo_T(p) = v. For a pixel with rk(p)=vr_k(p) = v and ℓ(p)<k\ell(p) < k, the owner VpV_p is in front of vv and does not change. So PT(v)=πk(v)P_T(v) = \pi_k(v), which passes. Every other voxel of TT owns in TT a subset of what it owns in Sˉ\bar S, so it passes by Lemma 2 and monotonicity. Every pixel with I(p)≠⊥I(p) \ne \bot still has an owner. So TT is consistent, and a pixel p∈πk(v)p \in \pi_k(v) has its owner in TT at layer kk. Then ℓ(p)≤k\ell(p) \le k, which is a contradiction.

Line L6 marks the pixels of πk(v)\pi_k(v) for the colored voxels vv of layer kk, which are the voxels of Sˉ\bar S in layer kk. A pixel p∈Ukp \in U_k with ℓ(p)=k\ell(p) = k has rk(p)=Vp∈Sˉr_k(p) = V_p \in \bar S, so it is marked. A pixel p∈Ukp \in U_k with ℓ(p)>k\ell(p) > k has rk(p)∉Sˉr_k(p) \notin \bar S by Lemma 1, so it stays unmarked. Thus Uk+1={p:ℓ(p)≥k+1}U_{k+1} = \{p : \ell(p) \ge k + 1\}. □\square

Theorem. If a consistent scene exists, VOXEL-COLOR returns Sˉ\bar S, 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 Sˉ\bar S. If the flag is false, no consistent scene exists.

Proof. By Lemma 3 the colored voxels of all layers form Sˉ\bar S, which is consistent by Lemma 2. The pixels that a colored voxel vv of layer kk owns in Sˉ\bar S are those with Vp=vV_p = v, which is the set πk(v)\pi_k(v) whose mean line L5 stores. After the last layer, UL={p:ℓ(p)=∞}U_L = \{p : \ell(p) = \infty\}, and these pixels have I(p)=⊥I(p) = \bot by Lemma 2, so the flag is true. The last claim is the contrapositive. ■\blacksquare

Remarks.

  • The scene Sˉ\bar S is one of possibly many consistent scenes. It is the nearest one at every pixel: in any consistent scene SS, the owner of pp is at a layer at least ℓ(p)\ell(p), the layer of its owner in Sˉ\bar S.
  • 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 nn layers, each layer costs one pass over all NWHN W H pixels plus the test on the footprints, which together have at most NWHN W H pixels. The total is Θ(NWHn)\Theta(N W H n) in every case.

The code stores the voxel of each layer for each pixel, O(NWHn)O(N W H n), and the colored voxels, O(n3)O(n^3). Seitz and Dyer compute the footprints on the fly and store only the images and one bit per pixel for the marks, which is O(NWH)O(N W H) 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.

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

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

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