Algorithmintro
Voxel grid downsampling
Also called voxel grid filter.
Reduce a point cloud by replacing the points in each cell of a 3D grid with their centroid, in linear expected time with hashing.
- Time
- Θ(n) expected worst · averageΘ(n) best
- Space
- Θ(m) extra
- Where
- m = the number of occupied voxels; n = the number of input points
- Model
- Real RAM
- Properties
- deterministicexactofflineorder independentiterativenot translation invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jarek Rossignac, Paul Borrel, 1993
Voxel grid downsampling makes a point cloud smaller and more even. It cuts space into equal cubes, called voxels, and replaces all the points that fall in one cube by their average, the centroid. The output has one point per occupied cube, so its density is at most one point per cube, wherever the input was dense. A hash table keyed by the integer index of the cube does the grouping in one pass, in expected time for points. It is the usual first step before normal estimation, registration and meshing, because it bounds the number of points and evens out the sampling. It is the point cloud form of the vertex clustering used to simplify meshes.
In plain words
Put a 3D grid of equal boxes over the points, like a stack of ice cube trays. Look at each box. If it is empty, skip it. If it holds points, throw them away and put one new point at their average position.
To do this fast, compute for each point the number of its box from its coordinates: divide by the box size and round down. Keep a table from box numbers to a running total and a count. One pass over the points fills the table, and one pass over the table gives the new points. The result never has two points in one box, so a dense patch near the scanner becomes as sparse as the box size asks.
The problem
The input is a finite list of points in , a voxel size and an origin . The voxel with integer index is the half-open box . These boxes cover space without overlap. The output has one point for each voxel that holds at least one input point: the centroid of the input points in that voxel.
There is no single correct downsampled cloud. This is one well-defined rule among many, chosen because it is fast, needs no neighbor search, and moves no point by more than one voxel diagonal.
The algorithm
VOXEL-DOWNSAMPLE(P, s, o)- 1
cells ← an empty hash table from integer triples to (sum, count) - 2
for each point p in P do - 3
c ← (⌊(p_x - o_x)/s⌋, ⌊(p_y - o_y)/s⌋, ⌊(p_z - o_z)/s⌋) - 4
if c is not in cells then cells[c] ← (0, 0) - 5
add p to the sum and 1 to the count of cells[c] - 6
Q ← an empty list - 7
for each entry (c, sum, count) of cells do - 8
append sum / count to Q - 9
return Q
Line L3 is the only geometric step: the floor of each scaled coordinate gives the index of the voxel. Line L5 keeps a running sum and a count, not a list of points, so the table needs one entry per occupied voxel. Line L8 divides once per voxel. Other values that the points carry, such as colors or intensities, are averaged in the same way at line L5.
The grid is never stored. Only the occupied voxels have entries, so a cloud that spans a kilometer with a voxel size of a centimeter costs no more than one that spans a meter, as long as the number of points is the same.
Example
Take six points in the plane , voxel size and origin . All the voxels have , so the table shows only and .
| point | voxel | |
|---|---|---|
| (0.2, 0.1) | (0, 0) | |
| (0.6, 0.3) | (0, 0) | |
| (1.5, 0.2) | (1, 0) | |
| (1.8, 0.9) | (1, 0) | |
| (1.2, 0.4) | (1, 0) | |
| (0.3, 1.7) | (0, 1) |
After the loop, the table holds three entries: voxel with sum and count 2, voxel with sum and count 3, and voxel with sum and count 1. Line L8 gives the three output points , and . Six points became three. Each output point lies in its own voxel, and the single point is kept as it is.
Correctness
By the definition of the floor, line L3 gives the index exactly when the point lies in the half-open voxel , so each point goes to exactly one voxel. An induction on the loop of line L2 shows that after points the table holds, for each voxel met so far, the sum and the count of the first points in it. At the end, line L8 returns the centroid of each occupied voxel. A voxel is convex, so the centroid lies in the same voxel, and every input point is less than , the voxel diagonal, from the output point of its voxel. The full proof is below.
Proof: VOXEL-DOWNSAMPLE returns one point per occupied voxel, the centroid of the input points in that voxel, and every input point is within s√3 of its representativefull
Let be the input points, the voxel size and the origin. For an integer triple the voxel is the half-open box
Line L3 computes .
Lemma 1. if and only if . So the voxels partition , and each point lies in exactly one of them.
Proof. For a real and an integer , holds exactly when . Apply this to and multiply by , which keeps the order: exactly when . The same holds for and . The floor is a function, so each point has one key.
For a key and let , the indices of the first points that fall in .
Lemma 2 (invariant of the loop at line L2). After passes of the loop, the keys of the table are exactly the keys with , in the order of the first index in , and the entry of each such key holds and .
Proof. By induction on . For the table is empty (line L1) and every is empty. Assume the claim after passes and let . Then , and for every other key . If is empty, is not in the table, line L4 creates the entry with zero sum and zero count, and the insertion puts last, which is the order of first indices since is larger than all earlier first indices. Line L5 then adds to the sum and to the count of only. So the entry of holds the sum and the size of , and the other entries do not change.
Theorem. VOXEL-DOWNSAMPLE returns, for each voxel that holds at least one input point, the single point
and no other point. The points come in the order in which their voxels are first met in the input. Each lies in , and every input point satisfies .
Proof. After the loop, . By Lemma 1, is the set of indices of the points in , so by Lemma 2 the table has one entry for each occupied voxel, with the sum and the count of its points. Each count is at least , so the division at line L8 is defined, and lines L6 to L8 emit the quotient for each entry, in table order. This is the first claim, and the order claim follows from Lemma 2.
is a product of half-open intervals, so it is convex. The point is a convex combination of points of , with weights , so . Coordinate by coordinate: each in the voxel satisfies , and an average of numbers in lies in . Two points of one voxel differ by less than in each coordinate, so their distance is less than . Both and lie in , which gives the last claim. The loops run over points and over at most entries, so the procedure terminates.
The bound is the diameter of a voxel. It is the guarantee a user gets: replacing the cloud by the output moves no point by more than one voxel diagonal, so the one-sided Hausdorff distance from the input to the output is below . The other direction is also below , since each output point lies in a voxel with an input point.
Complexity
The model is the real RAM with the floor function and a hash table on integer keys. Let be the number of occupied voxels, with .
- Time. Line L3 costs per point, and each lookup or insertion at lines L4 and L5 costs expected with a good hash function. The total is expected. With a sort of the keys in place of the hash table, the time is in the worst case, or with a radix sort on bounded integer keys.
- Space. extra for the table and the output.
No neighbor search is needed, so this is cheaper than any filter that looks at the nearest neighbors of each point, such as statistical outlier removal.
Properties
- Order independent. The set of output points does not depend on the order of the input. Only the order of the output does.
- Not translation invariant. The output depends on where the grid starts. Moving the origin by half a voxel can split one cluster into two or join two clusters.
- Bounded error. Each input point is within one voxel diagonal, , of its representative.
- New points. The centroids are usually not input points. On a curved surface, the centroid lies slightly inside the curve, not on the surface.
- Density cap, not density target. The output has at most one point per voxel. Sparse regions stay sparse, so the result is even only where the input was denser than the grid.
Variants and improvements
- Voxel centers. Output the center of each occupied voxel in place of the centroid. This is cheaper and puts the points on a regular grid, but it moves points by up to half a diagonal even on a flat, dense surface.
- Nearest input point. Keep the input point closest to each centroid. The output is then a subset of the input, which keeps the original attributes and avoids points between surfaces.
- Sort in place of hashing. Compute all keys, sort them, and average each run of equal keys. This is deterministic, uses less memory per point and runs well on GPUs. Packing the three indices into one integer, or into a Z-order key, makes the sort cheap.
- Minimum count. Drop the voxels with fewer than a set number of points. This also removes isolated points, a crude form of outlier removal.
- Adaptive cells. An octree that splits a cell only while its points do not fit a plane keeps more points where the surface bends. Pauly, Gross and Kobbelt (2002) give hierarchical and incremental clustering of this kind.
- Unit normals. If the points carry normals, average them at line L5 and normalize at line L8, or estimate the normals again on the output.
When to use it
Use a voxel grid filter to reduce a large cloud to a size that later steps can handle, to make the density more even before a fixed radius search, and to make the input of ICP or feature descriptors independent of the distance to the sensor. Choose the voxel size from the detail you need: a feature smaller than a voxel is lost. Use an adaptive method when the surface has both large flat parts and small detailed parts. Do not use it when every original sample must be kept, for example to measure noise.
Pitfalls
- Truncation in place of the floor. Writing at line L3 rounds toward zero, so the points in and in get the same index, and the voxel at the origin is twice as wide. Use the floor, or put the origin at the minimum corner of the bounding box so that all indices are at least zero.
- Packed keys that overflow. Many programs pack the three indices of line L3 into one 32-bit or 64-bit integer. If the cloud spans more voxels along an axis than the field holds, different voxels share a key and their points are averaged together. Check the extent divided by against the field width.
- Large coordinates. In floating point, loses digits when the coordinates are large, as with georeferenced lidar. Points near a voxel face then go to the wrong side. Subtract a local origin first.
- Averaging normals as points. Summing unit normals at line L5 gives a short vector, and normals of opposite sign cancel. Normalize at line L8, or estimate normals after downsampling.
- One voxel across two surfaces. A voxel that holds points of two surfaces, for example both sides of a thin wall, gets one centroid between them, in empty space. Use a voxel smaller than the thinnest part, or keep the nearest input point.
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-grid-downsampling/. The authors are listed in prov/S76VBE.jsonl.
"""Voxel grid downsampling of a 3D point cloud.
The space is cut into cubes (voxels) of edge `size`, aligned with the axes and
with one corner at `origin`. Each occupied voxel is replaced by the centroid of
the points that fall in it. A dict (a hash table) maps the integer voxel index
to a running sum, so the cost is O(n) expected time for n points.
"""
from __future__ import annotations
import math
from typing import Dict, List, Sequence, Tuple
Point = Tuple[float, float, float]
Key = Tuple[int, int, int]
def voxel_index(p: Sequence[float], size: float, origin: Sequence[float] = (0.0, 0.0, 0.0)) -> Key:
"""The integer index (i, j, k) of the voxel that holds p.
The voxel (i, j, k) is the half-open box [o + i s, o + (i + 1) s) x ... .
floor, not int(), so that negative coordinates go to negative indices.
"""
return (math.floor((p[0] - origin[0]) / size),
math.floor((p[1] - origin[1]) / size),
math.floor((p[2] - origin[2]) / size))
def voxel_grid_downsample(points: Sequence[Sequence[float]], size: float,
origin: Sequence[float] = (0.0, 0.0, 0.0)) -> List[Point]:
"""Replace the points of each occupied voxel by their centroid.
Precondition: size > 0. The output has one point per occupied voxel, in the
order in which the voxels are first met in the input. Entries may be floats
or fractions.Fraction; with fractions and a Fraction size the result is
exact. Cost: O(n) expected time and O(m) extra space for m occupied voxels.
"""
if not size > 0:
raise ValueError("the voxel size must be positive")
cells: Dict[Key, list] = {} # @line L1
for p in points: # @line L2
key = voxel_index(p, size, origin) # @line L3
acc = cells.get(key) # @line L4
if acc is None:
acc = [0, 0, 0, 0]
cells[key] = acc
acc[0] += p[0] # @line L5
acc[1] += p[1]
acc[2] += p[2]
acc[3] += 1
out: List[Point] = [] # @line L6
for acc in cells.values(): # @line L7
c = acc[3]
out.append((acc[0] / c, acc[1] / c, acc[2] / c)) # @line L8
return out # @line L9
test_voxel_grid_downsampling.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/voxel-grid-downsampling/. The authors are listed in prov/S76VBE.jsonl.
import math
import random
from fractions import Fraction as F
import pytest
from voxel_grid_downsampling import voxel_grid_downsample, voxel_index
EXAMPLE = [(0.2, 0.1, 0.0), (0.6, 0.3, 0.0), (1.5, 0.2, 0.0), (1.8, 0.9, 0.0),
(1.2, 0.4, 0.0), (0.3, 1.7, 0.0)]
def brute_force(points, size, origin=(0, 0, 0)):
"""Group by comparing every pair of points: same voxel when the three
floors agree. Quadratic, independent of any dict."""
groups = []
for p in points:
for g in groups:
q = g[0]
if all(math.floor((p[a] - origin[a]) / size) == math.floor((q[a] - origin[a]) / size)
for a in range(3)):
g.append(p)
break
else:
groups.append([p])
return [tuple(sum(p[a] for p in g) / len(g) for a in range(3)) for g in groups]
def test_example() -> None:
pts = [tuple(F(str(v)) for v in p) for p in EXAMPLE]
out = voxel_grid_downsample(pts, F(1))
assert out == [(F("0.4"), F("0.2"), 0), (F("1.5"), F("0.5"), 0), (F("0.3"), F("1.7"), 0)]
def test_matches_brute_force_exact() -> None:
rng = random.Random(1)
for trial in range(40):
n = rng.randint(0, 60)
size = F(rng.randint(1, 8), rng.randint(1, 4))
origin = tuple(F(rng.randint(-5, 5), 3) for _ in range(3))
pts = [tuple(F(rng.randint(-40, 40), 7) for _ in range(3)) for _ in range(n)]
assert voxel_grid_downsample(pts, size, origin) == brute_force(pts, size, origin)
def test_centroid_stays_in_its_voxel_and_counts() -> None:
rng = random.Random(2)
pts = [(rng.uniform(-3, 3), rng.uniform(-3, 3), rng.uniform(-1, 1)) for _ in range(300)]
size = 0.7
out = voxel_grid_downsample(pts, size)
keys = {voxel_index(p, size) for p in pts}
assert len(out) == len(keys)
out_keys = {voxel_index(c, size) for c in out}
assert out_keys == keys
def test_order_does_not_change_the_set() -> None:
rng = random.Random(3)
pts = [tuple(F(rng.randint(-30, 30), 4) for _ in range(3)) for _ in range(80)]
a = voxel_grid_downsample(pts, F(3, 2))
shuffled = pts[:]
rng.shuffle(shuffled)
b = voxel_grid_downsample(shuffled, F(3, 2))
assert sorted(a) == sorted(b)
def test_edges() -> None:
assert voxel_grid_downsample([], 1.0) == []
assert voxel_grid_downsample([(1.0, 2.0, 3.0)], 0.5) == [(1.0, 2.0, 3.0)]
# A point on a voxel face goes to the voxel above (half-open boxes).
assert voxel_index((1.0, -1.0, 0.0), 1.0) == (1, -1, 0)
assert voxel_index((-0.5, 0.0, 0.0), 1.0) == (-1, 0, 0)
with pytest.raises(ValueError):
voxel_grid_downsample([(0.0, 0.0, 0.0)], 0.0)
History
Rossignac and Borrel (1993) simplified triangle meshes by clustering the vertices on a uniform grid and keeping one representative vertex per cell. Pauly, Gross and Kobbelt (2002) studied the simplification of point-sampled surfaces and listed this uniform grid clustering as the simplest method, with its two weak points: the cell size does not adapt to the sampling density, and points of parts that are not connected can fall into one cell. The VoxelGrid filter of the Point Cloud Library (Rusu and Cousins, 2011), which replaces the points of each voxel by their centroid, made the method the standard first step of point cloud processing in robotics.
References
- Mark Pauly, Markus Gross and Leif P. Kobbelt, Efficient simplification of point-sampled surfaces, IEEE Visualization 2002, 163-170, Section 3.1, Clustering (uniform grid clustering after Rossignac and Borrel, and its two drawbacks: a fixed cell size that does not follow the sampling density, and the joining of parts that are not connected)
- Jarek Rossignac and Paul Borrel, Multi-resolution 3D approximations for rendering complex scenes, in Modeling in Computer Graphics, Springer, 1993, The vertex clustering on a uniform grid
- Radu Bogdan Rusu and Steve Cousins, 3D is here: Point Cloud Library (PCL), IEEE International Conference on Robotics and Automation (ICRA), 2011, The library and its filtering module
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 S76VBE Edit this page History Report an error Markdown