Algorithmadvanced
TSDF fusion
Also called Curless-Levoy volumetric fusion, truncated signed distance fusion, KinectFusion volumetric integration.
Fuse many depth images into a voxel grid by a weighted running average of truncated signed distances to the surface, then extract the zero level set as the fused surface.
- Solves
- Surface reconstruction
- Time
- Θ(N n^3) worst · average · best
- Space
- Θ(n^3) extra
- Where
- N = the number of depth images; n = the number of voxels along each side of the grid
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brian Curless, Marc Levoy, 1996
TSDF fusion builds one surface from many depth images, for example scans from a laser scanner or frames from a depth camera. It cuts space into a grid of small cubes, called voxels. For each depth image and each voxel, it computes how far the voxel is in front of or behind the measured surface along the line of sight, cuts this signed distance off at a small band (the truncation), and adds it to a weighted running average stored in the voxel. The surface is where the averaged distance is zero, and marching cubes turns it into a mesh. Averaging removes much of the noise of single scans, and the grid can grow one image at a time. Depth map fusion is the general technique of merging depth maps; TSDF fusion is its volumetric algorithm, by Curless and Levoy (1996), which KinectFusion made real time.
In plain words
Imagine a room filled with a grid of tiny boxes. Each time a depth camera takes a picture, every box near the measured surface writes down a number: positive if it is in front of the surface, negative if it is behind, and larger the farther it is, up to a small limit. Each box keeps the average of all the numbers it got, giving more weight to readings it trusts more. Boxes far in front of every surface say plus one, and boxes far behind it say nothing, because no camera saw them. The surface lies where the averages change from positive to negative. One noisy picture gives a rough surface, but many pictures average out to a smooth one.
The problem
Input.
- Depth images . is the depth of the surface at pixel in camera , or empty where the sensor gave no reading.
- The cameras with (see pinhole camera model), all in one world frame.
- A grid of voxels of size , a truncation distance of a few voxels, and a weight per image or per pixel.
Output. For each voxel, a value and a weight . is the weighted mean of the truncated distances divided by , and marks a voxel that no image has seen. The surface is the zero level set of over the seen voxels. In the sense of a signed distance function, is positive outside the object, toward the cameras.
The algorithm
TSDF-INTEGRATE(D, W, Z, (K, R, t), μ, w)- 1
for each voxel x with center X do - 2
X_c ← R X + t; if Z_c ≤ 0 then skip x - 3
(u, v) ← the pixel nearest to the projection of X_c; if it is outside the image or Z[v][u] is empty then skip x - 4
η ← Z[v][u] - Z_c ▷ signed distance along the line of sight - 5
if η < -μ then skip x ▷ far behind the surface: not seen - 6
f ← min(1, η / μ) - 7
D[x] ← (W[x] D[x] + w f) / (W[x] + w); W[x] ← W[x] + w
Call TSDF-INTEGRATE once per depth image. To extract the surface, find the pairs of neighboring seen voxels where changes sign and place a point between them by linear interpolation. The code does this along one axis; marching cubes does it on all edges of each cube and links the points into triangles.
Line L4, the distance. is the difference of depths along the line of sight, as in KinectFusion. It is zero exactly on the measured surface, but on a slanted surface it is larger than the true distance to the surface by the factor , where is the angle between the line of sight and the normal.
Lines L5 and L6, the truncation. In front of the surface, the distance is cut off at 1, which marks free space. Behind the surface, the camera saw nothing, so voxels more than behind it get no reading. This keeps a thin object from being wiped out by readings from the other side.
Line L7, the update. This is the running form of the weighted mean, so the images can come one at a time and in any order. Curless and Levoy set the weight from the angle between the line of sight and the surface normal and lower it near the edges of a scan, where range data are less reliable.
Example
One line of sight. A camera at the origin looks along the axis, and four voxels on the axis have centers at . Three depth images read the depth on the axis as , and , with weights 1, 2 and 1. The truncation is .
| voxel | |||||
|---|---|---|---|---|---|
| 1.975 | 0.5 | 1 (cut off from 1.1) | 0.1 | 0.65 | 4 |
| 2.000 | 0 | 0.6 | -0.4 | 0.2 | 4 |
| 2.025 | -0.5 | 0.1 | -0.9 | -0.3 | 4 |
| 2.050 | -1 | -0.4 | none () | -0.6 | 3 |
The sign changes between and . Linear interpolation gives , which is the weighted mean of the readings.
A noisy sphere. The test file renders a sphere of radius 1 at a distance of 3 from eight cameras near the origin, with depth images and Gaussian noise of standard deviation on every depth. On a grid of voxels of size with , the surface points near the center of the view from one image are on average from the true sphere. After fusing all eight images, the mean error is .
Correctness
The full proof is in proofs/correctness.md.
- Running mean. By induction over the images, line L7 keeps and over the images that gave the voxel a reading. So the result does not depend on the order of the images.
- Least squares. Along a line of sight on which every reading lies within of two neighboring voxels, is linear in the depth: with . Linear interpolation therefore puts the surface at , which is the minimizer of .
This is a theorem only inside the truncation band and along a common line of sight. Curless and Levoy show in an appendix that the zero set still minimizes a weighted sum of squared distances when the lines of sight are nearly parallel and the weights change slowly. Outside these conditions, the method is a well-tested heuristic.
Proof: TSDF fusion computes the weighted mean of the truncated distances, and its zero crossing is the weighted least squares surface along a line of sightfull
We use the pseudocode of the page and exact real arithmetic. A voxel keeps a value and a weight , both 0 at the start. Frame gives the voxel a reading with weight if lines L2 to L5 do not skip it, and no reading otherwise. Let be the set of frames that give a reading.
Lemma 1 (running weighted mean). After any sequence of frames, , and if then . In particular the result does not depend on the order of the frames.
Proof. By induction on the number of frames. At the start both sums are empty and . A frame that gives no reading changes nothing. Suppose a frame with reading and weight arrives, and before it and over the earlier frames in . This also holds when , since then both sides are 0. Line L7 sets and , which is the claim for the longer sequence. The two sums do not depend on the order of their terms.
Lemma 2 (the three states of a voxel). Let be the value of line L4 for frame . If , the reading is . If , the reading is . If , there is no reading. So , a voxel far in front of every observed surface has , and a voxel that is more than behind the surface in every frame keeps , which marks it as unseen.
Proof. Lines L5 and L6. A weighted mean of numbers in lies in .
Theorem (zero crossing on a line of sight). Let voxels and be neighbors on a line with centers at positions along the line. Suppose that in every frame both voxels project to pixels with readings, and that the signed distance in frame is at both centers, for a surface position along the line with and . Let and assume . Then the point that linear interpolation of places between and is , and is the unique minimizer of .
Proof. By the assumptions and Lemma 2, every frame gives both voxels the reading , without truncation. By Lemma 1, for ,
So , and the sign changes between the two voxels. The interpolated point is with
which is . Finally is zero only at , and .
The assumption that at both centers holds in the setting of the test file: every frame is taken by a camera on the line, which looks along it, and is the depth. With cameras in other positions, each frame measures the distance along its own line of sight. Curless and Levoy show in their appendix that the zero set is still the weighted least squares surface when the lines of sight are nearly parallel and the weights vary slowly, and they give the full argument in Curless's thesis. We do not prove that general case here.
What is not proved. The theorem holds only inside the truncation band. Where a reading is truncated to 1 or skipped, is no longer linear in , and the crossing moves. The value $\eta = $ depth is the distance along the line of sight, not the Euclidean distance to the surface; for a plane whose normal makes an angle with the line of sight, the true distance is . The zero set is right in both cases, but the band is wider than on slanted surfaces, and readings from different directions are scaled differently.
Complexity
The model is the real RAM. Each image visits every voxel once, with constant work per voxel, so integration takes per image and for all images, in every case. Extraction takes . The grid stores and for each voxel, , and the images can be dropped after integration. An implementation that updates only the voxels in the band near each measured surface, as sparse grids do, spends time in proportion to the area of the surface times instead of the volume.
Properties
- Online. Each image is used once and can be dropped. The cost of one update does not depend on how many images came before.
- Order independent. The fused grid is the same for any order of the images, up to rounding.
- Least squares surface. Under the conditions above, the zero set is the weighted mean of the readings.
- Any topology. The zero set can have any number of parts and holes, and needs no initial shape.
- Fixed resolution. The grid limits the detail to about the voxel size and needs memory, even though the surface fills only a thin layer.
Variants and improvements
- Hole filling. Curless and Levoy also mark voxels as unseen, empty or near the surface. They then put a surface between unseen and empty voxels, which closes the holes of the model in a way that is consistent with the scans.
- Real-time fusion. KinectFusion runs line L7 for every voxel on a GPU at camera frame rate. It finds the pose of each new frame by point-to-plane ICP against a surface that it predicts by ray casting the grid, and caps the weight so that the model can follow slow changes in the scene.
- Sparse grids. Voxel hashing and octrees store only the blocks of voxels near the surface, which makes large scenes fit in memory.
- Occupancy instead of distance. An occupancy grid stores a probability of being occupied per cell. It is the robotics counterpart and has no subvoxel surface.
- Other surfaces from depth. Poisson surface reconstruction fits an indicator function to oriented points instead of averaging distances on a grid.
When to use it
Use TSDF fusion when you have many depth images with known poses, from a range scanner, a depth camera, or multi-view stereo, and you want a closed, smooth mesh at a resolution that fits in memory. It is simple, runs well on a GPU, and handles new images as they come. For a few depth maps with many outliers, use a voting form of depth map fusion first, since one far outlier with a high weight moves the averaged surface. For thin structures thinner than the band , and for very large scenes, use a sparse grid or a point-based method.
Pitfalls
- Thin objects. Readings from the back of a thin object reach the front voxels through the band behind the surface and pull the surface back. Keep smaller than the thickness of the thinnest part you want to keep.
- Too small a band. If is less than the noise or than about two voxels, neighboring voxels do not both get readings, and the surface breaks into holes.
- Projective distance. On slanted surfaces is larger than the true distance, so the band is wider than and readings from different directions are scaled differently. Weighting by the angle to the normal reduces the effect.
- Pose errors. The fusion assumes exact poses. A small error in one pose blurs or doubles the surface. KinectFusion tracks each frame against the model to keep poses consistent.
- Sign convention. Here in front of the surface. Some code uses the opposite sign. Mixing the two puts the mesh normals inside out.
- Nearest pixel. Rounding the projection to the nearest pixel, as the code does, gives staircase artifacts at depth edges. Bilinear interpolation of the depth helps on smooth surfaces but blurs edges.
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/tsdf-fusion/. The authors are listed in prov/AYN2F8.jsonl.
"""Fusion of depth maps into a truncated signed distance field (TSDF).
The volume is a grid of nx * ny * nz voxels of size h. The center of voxel
(i, j, k) is origin + h (i + 1/2, j + 1/2, k + 1/2). Each voxel keeps a fused
value D in [-1, 1] and a weight W; W = 0 means that no camera has seen it.
A camera is (K, R, t) with X_c = R X + t, and a depth map gives the depth Z of
the surface for each pixel (u, v) as depth[v][u], or None where it has no
reading. The signed distance of a voxel is the projective distance
depth - Z_c along the line of sight: positive in front of the surface,
negative behind it.
"""
class Volume:
def __init__(self, dims, origin, h):
self.dims, self.origin, self.h = tuple(dims), tuple(origin), float(h)
n = dims[0] * dims[1] * dims[2]
self.D = [0.0] * n
self.W = [0.0] * n
def index(self, i, j, k):
return i + self.dims[0] * (j + self.dims[1] * k)
def center(self, i, j, k):
return [self.origin[0] + self.h * (i + 0.5),
self.origin[1] + self.h * (j + 0.5),
self.origin[2] + self.h * (k + 0.5)]
def integrate(vol, depth, cam, mu, weight=1.0):
"""Fuse one depth map into the volume with the running weighted average."""
K, R, t = cam
height, width = len(depth), len(depth[0])
nx, ny, nz = vol.dims
for k in range(nz): # @line L1
for j in range(ny):
for i in range(nx):
X = vol.center(i, j, k)
Xc = [R[r][0] * X[0] + R[r][1] * X[1] + R[r][2] * X[2] + t[r] for r in range(3)] # @line L2
if Xc[2] <= 0.0:
continue
x, y = Xc[0] / Xc[2], Xc[1] / Xc[2]
u = int(round(K[0][0] * x + K[0][1] * y + K[0][2])) # @line L3
v = int(round(K[1][1] * y + K[1][2]))
if not (0 <= u < width and 0 <= v < height) or depth[v][u] is None:
continue
eta = depth[v][u] - Xc[2] # @line L4
if eta < -mu: # @line L5
continue
f = min(1.0, eta / mu) # @line L6
n = vol.index(i, j, k)
vol.D[n] = (vol.W[n] * vol.D[n] + weight * f) / (vol.W[n] + weight) # @line L7
vol.W[n] += weight
def zero_crossings(vol, axis=2):
"""Surface points where D changes sign between two seen neighbors along one axis,
placed by linear interpolation. Marching cubes builds a mesh from the same data."""
nx, ny, nz = vol.dims
step = [0, 0, 0]
step[axis] = 1
points = []
for k in range(nz - step[2]):
for j in range(ny - step[1]):
for i in range(nx - step[0]):
a = vol.index(i, j, k)
b = vol.index(i + step[0], j + step[1], k + step[2])
if vol.W[a] == 0.0 or vol.W[b] == 0.0:
continue
da, db = vol.D[a], vol.D[b]
if (da > 0.0) == (db > 0.0) or da == db:
continue
s = da / (da - db)
pa = vol.center(i, j, k)
pb = vol.center(i + step[0], j + step[1], k + step[2])
points.append([pa[c] + s * (pb[c] - pa[c]) for c in range(3)])
return points
def batch_average(values_and_weights):
"""The weighted mean that the running average must equal."""
sw = sum(w for _, w in values_and_weights)
return sum(f * w for f, w in values_and_weights) / sw, sw
test_tsdf_fusion.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tsdf-fusion/. The authors are listed in prov/AYN2F8.jsonl.
import math
import random
import unittest
from tsdf_fusion import Volume, batch_average, integrate, zero_crossings
I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
def column(nz, z0, h):
"""A single column of voxels on the optical axis of a camera at the origin."""
return Volume((1, 1, nz), (-h / 2.0, -h / 2.0, z0), h)
ONE_PIXEL = ([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], I3, [0.0, 0.0, 0.0])
def sphere_depth(cam, width, height, c, r, rng, sigma):
K, _, t = cam
C = [-t[0], -t[1], -t[2]]
out = []
for v in range(height):
row = []
for u in range(width):
d = [(u - K[0][2]) / K[0][0], (v - K[1][2]) / K[1][1], 1.0]
oc = [C[a] - c[a] for a in range(3)]
A = sum(x * x for x in d)
B = 2.0 * sum(d[a] * oc[a] for a in range(3))
disc = B * B - 4.0 * A * (sum(x * x for x in oc) - r * r)
if disc < 0.0:
row.append(None)
else:
row.append((-B - math.sqrt(disc)) / (2.0 * A) + rng.gauss(0.0, sigma))
out.append(row)
return out
class TsdfFusionTest(unittest.TestCase):
def test_worked_example(self):
vol = column(4, 1.9625, 0.025)
for z, w in ((2.00, 1.0), (2.03, 2.0), (1.98, 1.0)):
integrate(vol, [[z]], ONE_PIXEL, 0.05, w)
for got, want in zip(vol.D, (0.65, 0.2, -0.3, -0.6)):
self.assertAlmostEqual(got, want, places=12)
self.assertEqual(vol.W, [4.0, 4.0, 4.0, 3.0])
(p,) = zero_crossings(vol)
self.assertAlmostEqual(p[2], 2.01, places=12)
def test_crossing_is_weighted_mean_of_readings(self):
rng = random.Random(3)
for _ in range(20):
readings = [(2.0 + rng.uniform(-0.01, 0.01), rng.uniform(0.5, 2.0)) for _ in range(6)]
vol = column(16, 1.8, 0.025)
for z, w in readings:
integrate(vol, [[z]], ONE_PIXEL, 0.1, w)
mean, _ = batch_average(readings)
crossings = zero_crossings(vol)
self.assertEqual(len(crossings), 1)
self.assertAlmostEqual(crossings[0][2], mean, places=10)
def test_running_average_ignores_order(self):
rng = random.Random(5)
readings = [(2.0 + rng.uniform(-0.03, 0.03), rng.uniform(0.5, 2.0)) for _ in range(5)]
a, b = column(12, 1.85, 0.025), column(12, 1.85, 0.025)
for z, w in readings:
integrate(a, [[z]], ONE_PIXEL, 0.05, w)
for z, w in reversed(readings):
integrate(b, [[z]], ONE_PIXEL, 0.05, w)
for x, y in zip(a.D, b.D):
self.assertAlmostEqual(x, y, places=12)
for x, y in zip(a.W, b.W):
self.assertAlmostEqual(x, y, places=12)
def test_free_space_and_unseen(self):
vol = column(20, 1.5, 0.05)
integrate(vol, [[2.0]], ONE_PIXEL, 0.1)
for k in range(20):
z = 1.5 + 0.05 * (k + 0.5)
if z < 1.9:
self.assertEqual((vol.D[k], vol.W[k]), (1.0, 1.0))
elif z > 2.1:
self.assertEqual(vol.W[k], 0.0)
integrate(vol, [[None]], ONE_PIXEL, 0.1)
self.assertEqual(vol.W[0], 1.0)
def test_fusion_reduces_noise_on_a_sphere(self):
rng = random.Random(1)
K = [[30.0, 0.0, 15.5], [0.0, 30.0, 15.5], [0.0, 0.0, 1.0]]
offsets = [(0, 0), (0.4, 0), (-0.4, 0), (0, 0.4), (0, -0.4), (0.3, 0.3), (-0.3, 0.3), (0.3, -0.3)]
cams = [(K, I3, [-ox, -oy, 0.0]) for ox, oy in offsets]
c, r = (0.0, 0.0, 3.0), 1.0
def mean_error(vol):
e = [abs(math.dist(p, c) - r) for p in zero_crossings(vol)
if abs(p[0]) < 0.6 and abs(p[1]) < 0.6]
self.assertGreater(len(e), 100)
return sum(e) / len(e)
single = Volume((24, 24, 14), (-1.2, -1.2, 1.6), 0.1)
integrate(single, sphere_depth(cams[0], 32, 32, c, r, rng, 0.02), cams[0], 0.15)
fused = Volume((24, 24, 14), (-1.2, -1.2, 1.6), 0.1)
for cam in cams:
integrate(fused, sphere_depth(cam, 32, 32, c, r, rng, 0.02), cam, 0.15)
e1, e8 = mean_error(single), mean_error(fused)
self.assertLess(e8, 0.6 * e1)
self.assertLess(e8, 0.01)
if __name__ == "__main__":
unittest.main()
History
Curless and Levoy (1996) introduced the weighted average of signed distances on a grid to merge range scans from a laser scanner into one model. They showed that the zero set is a least squares surface, added hole filling with the unseen and empty states, and used marching cubes for the mesh. Newcombe, Izadi and co-authors (2011) used the same update in KinectFusion, which tracked a moving depth camera and fused its frames on a GPU in real time. Later systems made the grid sparse, with voxel hashing or octrees, to scale to rooms and buildings.
References
- Brian Curless and Marc Levoy, A volumetric method for building complex models from range images, SIGGRAPH 1996, pages 303 to 312, the cumulative signed distance and weight functions and their incremental update, the ramp that limits the distance near the surface, hole filling with the unseen, empty and near-surface states, and Appendix A (the isosurface as a least squares minimizer)
- Richard A. Newcombe, Shahram Izadi, Otmar Hilliges, David Molyneaux, David Kim, Andrew J. Davison, Pushmeet Kohli, Jamie Shotton, Steve Hodges and Andrew Fitzgibbon, KinectFusion: Real-time dense surface mapping and tracking, IEEE International Symposium on Mixed and Augmented Reality 2011, pages 127 to 136, the surface reconstruction update (the projective truncated signed distance and the weighted running average), surface prediction by ray casting, and tracking by ICP against the predicted surface
- Yasutaka Furukawa and Carlos Hernández, Multi-view stereo: a tutorial, Foundations and Trends in Computer Graphics and Vision 9(1-2), pages 1 to 148, 2015, the discussion of volumetric fusion of depth maps
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 13.2.1, Range data merging, and Section 13.5, Volumetric representations
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 AYN2F8 Edit this page History Report an error Markdown