Depth without multipath: transport probing

A CW-ToF camera measures depth from the phase of its modulated light. Light that bounces between surfaces arrives along longer paths and pulls the phase: the multipath error. O’Toole et al. (2014) remove it by probing the light transport. A projector, modulated like the camera’s light, shows patterns while the camera masks its pixels in step, so that the sensor keeps only the light that leaves the projector and comes back along the same line: the direct and the retro-reflective light. This page renders their coaxial setup, a projector at the camera, with the projector of LaserLight and the transport probing of CWToFPathTracerInline, and recovers depth without the multipath error.

The measurement with and without probing, and the depth error of the conventional, probed and masked measurements

The measurement

With phaseShift set to (0, 0.25, 0) and the cos waveform, the red and green channels hold the real and imaginary parts of the complex measurement

\[ I = \sum_{\text{paths}} f\, e^{2\pi i\, \ell / \lambda}, \]

from the same paths, \(f\) the path’s contribution and \(\ell\) its length (the scene and the light are gray). Its phase gives the path length up to multiples of \(\lambda\); for the direct light, the path length is twice the depth \(d\):

\[ d = \frac{\lambda}{4\pi} \arg I . \]

The modulation is 20 MHz, \(\lambda = 15\) m of path length, longer than the round trips in this scene, so the phase does not wrap. The indirect light adds longer paths, so the conventional phase, and the depth, come out too large.

Transport probing

A path leaves the light along its projector ray \(j\), to its last vertex, and reaches the camera along its camera ray \(i\), from its first vertex. Transport probing (O’Toole et al. 2012) weights it by \(\Pi(i, j)\):

  • epipolar: \(\Pi = 1\) when the projector ray is the camera ray, within half a pixel, and 0 otherwise. The direct light, the surface on the camera ray lit by the projector, always passes, and so does retro-reflective light, which comes back along the same rays (by way of a mirror, for example). Indirect light almost never does.

  • non_epipolar: \(1 - \Pi\), the indirect light.

  • masks: what a camera does (O’Toole et al. 2014, Algorithm 2). During the exposure, \(K\) random binary masks \(m_k\) of the camera’s rows take turns, each with its complement \(1 - m_k\) shown by the projector on the same rows. A path keeps \(\frac{4}{K} \sum_k m_k(\text{row}_i) \left(1 - m_k(\text{row}_j)\right)\): zero when its projector row is its camera row, and one on average otherwise. The measurement estimates the non-epipolar light, and the conventional measurement minus it, the direct and retro-reflective light (their Algorithm 3).

In general the lines are the epipolar planes, through the camera and the projector; with the projector at the camera, they all hold the camera ray, hence the rays and the rows (see Transport probing).

The algorithms of the paper

The pass computes each of the paper’s photos in one render:

  • Algorithm 1, a PMD photo: the camera captures four images \(i_1, \dots, i_4\) with the correlation \(\frac{1}{2}\cos + \frac{1}{2}\) delayed by 0, 1/4, 1/2 and 3/4 of a period (unsignedModulation, phase), and \(I = (i_1 - i_3) + i\,(i_2 - i_4)\). The differences cancel the constant half path by path, so phaseShift (0, 0.25, 0) with the signed cos renders \(I\) directly.

  • Algorithm 2, a probed PMD photo: the \(K\) masks and patterns take turns during one exposure, \(\frac{1}{K} \sum_k m_k \odot I(p_k)\), a sum that masks evaluates path by path (times 4: a path between two rows passes a mask and its pattern a quarter of the time).

  • Algorithm 3, the direct and retro-reflective photo: the conventional photo minus the probed one.

Step 6 runs the algorithms as a camera does, exposure by exposure. With the masks of masks and the same paths in every exposure, the two give the same photos, to float rounding, apart from a few paths that land on the edge of a row.

1. Build the scene

A white concave corner, the floor and two walls, with a box in it: light bounces between the faces.

import time
from pathlib import Path

import matplotlib
matplotlib.use("Agg")  # no window
import matplotlib.pyplot as plt
import numpy as np
import falcorcomp as falcor

# A white concave corner, the floor and two walls, with a box in it: light bounces between the faces (meters).
SCENE = """
camera = Camera()
camera.position = float3(1.8, 1.4, 1.8)
camera.target = float3(-0.4, 0.5, -0.4)
camera.up = float3(0.0, 1.0, 0.0)
camera.focalLength = 30.0
sceneBuilder.addCamera(camera)
white = StandardMaterial('White')
white.baseColor = float4(0.8, 0.8, 0.8, 1.0)
white.roughness = 1.0
white.metallic = 0.0
for name, size, center in [('Floor', float3(2.0, 0.02, 2.0), float3(0.0, -0.01, 0.0)),
                           ('Back', float3(2.0, 2.0, 0.02), float3(0.0, 1.0, -1.01)),
                           ('Left', float3(0.02, 2.0, 2.0), float3(-1.01, 1.0, 0.0)),
                           ('Box', float3(0.5, 0.5, 0.5), float3(-0.45, 0.25, -0.45))]:
    transform = Transform()
    transform.translation = center
    sceneBuilder.addMeshInstance(sceneBuilder.addNode(name, transform),
                                 sceneBuilder.addTriangleMesh(TriangleMesh.createCube(size), white))
"""
Path("cwtof_probing.pyscene").write_text(SCENE)

SIZE = 256
testbed = falcor.Testbed(create_window=False)
testbed.load_scene("cwtof_probing.pyscene")
testbed.resize_frame_buffer(SIZE, SIZE)
testbed.scene.camera.aspectRatio = 1.0
testbed.clock.pause()
position = testbed.scene.camera.position
camera_position = np.array([position.x, position.y, position.z])

2. Build the render graph

The light is the point light at the camera, as a projector (projector) with the camera’s field of view, showing a constant pattern. Each measurement builds a new graph with the probing given.

WAVELENGTH = 15.0  # path length of one modulation period, m: 20 MHz. The round trips here are shorter: no wrapping.
FRAMES = 64        # 64 frames x 16 spp per measurement


def measure(probing):
    """The complex CW-ToF measurement sum f exp(2 pi i l / wavelength) over the paths, l their lengths, weighted by
    the transport probing `probing`. Every call builds a new graph, so every measurement traces the same paths."""
    graph = testbed.create_render_graph("Probing")
    graph.create_pass("VBuffer", "VBufferRT", {"samplePattern": "Center", "sampleCount": 1})
    # A projector at the camera, with the camera's field of view: it lights everything the camera sees.
    graph.create_pass("Light", "LaserLight", {
        "isLightSourceLaser": False, "laserCollocated": True, "laserPower": [10.0, 10.0, 10.0],
        "projector": {"fov": [0.0, 0.0], "pattern": "constant"},
    })
    graph.create_pass("Tracer", "CWToFPathTracerInline", {
        "samplesPerPixel": 16, "maxBounces": 6, "computeDirect": True,
        "waveform": "cos", "modulationWavelength": WAVELENGTH,
        "phaseShift": [0.0, 0.25, 0.0],  # red: sum f cos(2 pi l / wavelength), green: sum f sin(...)
        **probing,
    })
    graph.create_pass("Accumulate", "AccumulatePass", {"precisionMode": "Single"})
    graph.add_edge("VBuffer.vbuffer", "Tracer.vbuffer")
    graph.add_edge("VBuffer.viewW", "Tracer.viewW")
    graph.add_edge("Light", "Tracer")
    graph.add_edge("Tracer.color", "Accumulate.input")
    graph.mark_output("Accumulate.output")
    testbed.render_graph = graph
    for _ in range(FRAMES):
        testbed.frame()
    image = graph.get_output("Accumulate.output").to_numpy()
    return image[..., 0].astype(np.float64) + 1j * image[..., 1]


3. Measure, with and without probing

A new graph starts from the same random numbers, so all four measurements trace the same paths: the epipolar and non-epipolar measurements add up to the conventional one, to \(10^{-6}\). The non-epipolar light is 19% of the epipolar light.

start = time.perf_counter()
measurements = {
    "conventional": measure({"probing": "none"}),
    "epipolar": measure({"probing": "epipolar"}),          # direct and retro-reflective light
    "non_epipolar": measure({"probing": "non_epipolar"}),  # the rest, the indirect light
    "masks": measure({"probing": "masks", "probingMaskCount": 128}),  # 128 random mask and pattern pairs
}
print(f"4 measurements in {time.perf_counter() - start:.0f} s")
conventional = measurements["conventional"]
lit = np.abs(conventional) > 1e-3 * np.abs(conventional).max()
residual = np.abs(conventional - measurements["epipolar"] - measurements["non_epipolar"])[lit].max()
print(f"|conventional - epipolar - non_epipolar| / max |conventional|: {residual / np.abs(conventional).max():.1e}")
share = np.abs(measurements["non_epipolar"])[lit].sum() / np.abs(measurements["epipolar"])[lit].sum()
print(f"non-epipolar / epipolar light, summed magnitudes: {share:.3f}")

4. Depth from the phase

The true depth is the distance from the camera to the world positions of GBufferRT.

graph = testbed.create_render_graph("Depth")
graph.create_pass("GBuffer", "GBufferRT", {"samplePattern": "Center", "sampleCount": 1})
graph.mark_output("GBuffer.posW")
testbed.render_graph = graph
testbed.frame()
positions = graph.get_output("GBuffer.posW").to_numpy()[..., :3]
true_depth = np.linalg.norm(positions - camera_position, axis=-1)


def depth(measurement):
    """The phase is 2 pi l / wavelength, and the path length l of the direct light is twice the depth."""
    phase = np.angle(measurement) % (2.0 * np.pi)
    return phase / (2.0 * np.pi) * WAVELENGTH / 2.0


# The masks give the indirect light as a camera would measure it; the conventional measurement minus it is the
# direct and retro-reflective light (O'Toole et al. 2014, Algorithm 3).
depths = {
    "conventional": depth(conventional),
    "epipolar": depth(measurements["epipolar"]),
    "conventional - masks": depth(conventional - measurements["masks"]),
}
for name, estimate in depths.items():
    error = (estimate - true_depth)[lit]
    print(f"{name}: median |depth error| {np.median(np.abs(error)) * 1e3:.2f} mm, "
          f"95th percentile {np.percentile(np.abs(error), 95) * 1e3:.2f} mm")
# The masks leave less indirect light the more of them take turns in the exposure.
for count in [8, 32, 128]:
    masked = measurements["masks"] if count == 128 else measure({"probing": "masks", "probingMaskCount": count})
    error = (depth(conventional - masked) - true_depth)[lit]
    print(f"conventional - masks, K = {count}: median |depth error| {np.median(np.abs(error)) * 1e3:.2f} mm")

5. Show the measurements and the depth errors

Depth from

Median error

95th percentile

The conventional measurement

101 mm

162 mm

The epipolar measurement

0.00 mm

0.03 mm

The conventional measurement minus the masks (\(K = 128\))

7.7 mm

25 mm

The indirect light biases the conventional depth by about 10 cm, the most on the floor near the corner, where the light bounces between the faces. The epipolar measurement keeps the direct light alone, and the indirect light that happens to return within half a pixel of the camera ray: its depth error is a few hundredths of a millimeter. The masks remove most of the indirect light but not all of it: with 128 fixed random masks, each indirect path is weighted by a random factor around one (about 15% off), and all the pixels of a row share the row’s masks, so the error comes in rows of a few millimeters. It falls about as \(1/\sqrt{K}\): a median of 29 mm with 8 masks, 14 mm with 32 and 7.7 mm with 128.

fig, axes = plt.subplots(2, 4, figsize=(16, 8.4), layout="constrained")
top = np.percentile(np.abs(conventional[lit]), 99)
titles = {"conventional": "conventional", "epipolar": "epipolar: direct + retro-reflective",
          "non_epipolar": "non-epipolar: indirect", "masks": "masks (K = 128)"}
for axis, (name, measurement) in zip(axes[0], measurements.items()):
    axis.imshow((np.abs(measurement) / top).clip(0, 1) ** (1 / 2.2), cmap="gray", vmin=0, vmax=1)
    axis.set_title(f"|I|, {titles[name]}")
shown = axes[1, 0].imshow(np.where(lit, true_depth, np.nan), cmap="viridis")
axes[1, 0].set_title("true depth (m)")
fig.colorbar(shown, ax=axes[1, 0], shrink=0.8)
for axis, (name, estimate) in zip(axes[1, 1:], depths.items()):
    error = np.where(lit, estimate - true_depth, np.nan) * 1e3
    shown = axis.imshow(error, cmap="RdBu_r", vmin=-150, vmax=150)
    axis.set_title(f"depth error (mm), {name}\nmedian |error| {np.nanmedian(np.abs(error)):.1f} mm")
fig.colorbar(shown, ax=axes[1, 1:], shrink=0.8)
for axis in axes.ravel():
    axis.set_xticks([])
    axis.set_yticks([])
fig.savefig("cwtof_probing.png", dpi=70)
np.savez("cwtof_probing.npz", true_depth=true_depth, lit=lit, **measurements)

6. The algorithms, one exposure at a time

A camera captures these photos in exposures. Algorithm 1 takes four raw images, each in an exposure of its own, with the correlation \(\frac{1}{2}\cos + \frac{1}{2}\) delayed by a quarter period from one to the next (unsignedModulation and phase). Algorithm 2 runs within each of them: the \(K\) random masks of the camera’s rows take turns, here for 4 frames each, while the projector shows their complements on its rows (set_pattern_data sets the row pattern; the masks multiply the rows of each frame). One graph renders the exposures frame by frame, without accumulation, so that each has its own noise, as on a camera.

# A camera captures each raw image of Algorithm 1 in an exposure of its own, and runs Algorithm 2 within it: K masks
# and patterns take turns during the exposure. One graph renders them frame by frame, without accumulation, so that
# each exposure has its own noise, as on a camera.
graph = testbed.create_render_graph("Exposures")
graph.create_pass("VBuffer", "VBufferRT", {"samplePattern": "Center", "sampleCount": 1})
light = graph.create_pass("Light", "LaserLight", {
    "isLightSourceLaser": False, "laserCollocated": True, "laserPower": [10.0, 10.0, 10.0],
    "projector": {"fov": [0.0, 0.0], "pattern": "constant"},
})
tracer = graph.create_pass("Tracer", "CWToFPathTracerInline", {
    "samplesPerPixel": 16, "maxBounces": 6, "computeDirect": True,
    "waveform": "cos", "modulationWavelength": WAVELENGTH,
    "unsignedModulation": True,  # the correlation of a sensor, 0.5 cos + 0.5: never negative
})
graph.add_edge("VBuffer.vbuffer", "Tracer.vbuffer")
graph.add_edge("VBuffer.viewW", "Tracer.viewW")
graph.add_edge("Light", "Tracer")
graph.mark_output("Tracer.color")
testbed.render_graph = graph
DELAYS = [0.0, 0.25, 0.5, 0.75]  # of the correlation, in periods


def exposure(frames):
    """The raw image of one exposure: the mean of the tracer's next `frames` frames."""
    image = np.zeros((SIZE, SIZE))
    for _ in range(frames):
        testbed.frame()
        image += graph.get_output("Tracer.color").to_numpy()[..., 0]
    return image / frames


def pmd_photo(raw):
    """Algorithm 1: the complex photo from the raw images at the four delays."""
    i1, i2, i3, i4 = raw
    return (i1 - i3) + 1j * (i2 - i4)


# Algorithm 1 with the all-white pattern: the conventional photo.
raw = []
for delay in DELAYS:
    tracer.set_properties({"phase": delay})
    raw.append(exposure(FRAMES))
conventional_alg1 = pmd_photo(raw)

# Algorithm 2 within each exposure of Algorithm 1: K random masks m_k of the camera's rows take turns, each for
# FRAMES_PER_MASK frames, with their complements p_k = 1 - m_k shown by the projector on its rows (its v runs up the
# image: its column c is image row SIZE - 1 - c).
K, FRAMES_PER_MASK = 128, 4
masks = np.random.default_rng(1).integers(0, 2, (K, SIZE))
light.set_properties({"projector": {"pattern": "arbitrary", "patternAxis": "v"}})
raw = []
for delay in DELAYS:
    tracer.set_properties({"phase": delay})
    image = np.zeros((SIZE, SIZE))
    for k in range(K):
        light.set_pattern_data((1 - masks[k, ::-1]).tolist())
        image += masks[k][:, None] * exposure(FRAMES_PER_MASK) / K
    raw.append(image)
probed_alg2 = pmd_photo(raw)

# Algorithm 3: the conventional photo minus the probed one, times 4, as a path between two rows passes a mask and its
# pattern a quarter of the time.
direct_alg3 = conventional_alg1 - 4.0 * probed_alg2
for name, photo in [("Algorithm 1 (conventional)", conventional_alg1), ("Algorithm 3 (direct)", direct_alg3)]:
    error = (depth(photo) - true_depth)[lit]
    print(f"{name}: median |depth error| {np.median(np.abs(error)) * 1e3:.2f} mm, "
          f"95th percentile {np.percentile(np.abs(error), 95) * 1e3:.2f} mm")

Depth from

Median error

95th percentile

Algorithm 1, the conventional photo

101 mm

163 mm

Algorithm 3, the direct photo (\(K = 128\))

11 mm

38 mm

The conventional photo has the multipath error of step 5. Algorithm 3 removes most of it, and leaves a little more than the photos of step 5 (7.7 mm): its 128 masks are other random masks, with their own errors along the rows, and its 4 × 128 short exposures add their own noise.

The full script: cwtof_probing.py. It builds its scene and takes under a minute.

Limitations

  • The projector reaches a surface by a connection from it (next-event estimation), so light that reflects off a mirror on its way from the projector to a diffuse surface (a caustic) is not rendered. The paper separates such caustic light further, with high-frequency patterns.

  • With the projector beside the camera (laserCollocated off), the lines are the epipolar planes: the probing works the same way, and the indirect light within one line, a band through the image, stays with the direct light.

References

  • M. O’Toole, R. Raskar and K. N. Kutulakos. Primal-dual coding to probe light transport. ACM Transactions on Graphics (SIGGRAPH) 31(4), 2012.

  • M. O’Toole, F. Heide, L. Xiao, M. B. Hullin, W. Heidrich and K. N. Kutulakos. Temporal frequency probing for 5D transient analysis of global light transport. ACM Transactions on Graphics (SIGGRAPH) 33(4), 2014.