Algorithm Search⌘K

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
Properties
deterministicexactofflineorder independentiterativenot translation invariant
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 Θ(n)\Theta(n) expected time for nn 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 PP of nn points in R3\mathbb{R}^3, a voxel size s>0s > 0 and an origin oo. The voxel with integer index c=(i,j,k)c = (i, j, k) is the half-open box [ox+is,ox+(i+1)s)×[oy+js,oy+(j+1)s)×[oz+ks,oz+(k+1)s)[o_x + is, o_x + (i+1)s) \times [o_y + js, o_y + (j+1)s) \times [o_z + ks, o_z + (k+1)s). 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

  1. VOXEL-DOWNSAMPLE(P, s, o)
  2. 1cells ← an empty hash table from integer triples to (sum, count)
  3. 2for each point p in P do
  4. 3c ← (⌊(p_x - o_x)/s⌋, ⌊(p_y - o_y)/s⌋, ⌊(p_z - o_z)/s⌋)
  5. 4if c is not in cells then cells[c] ← (0, 0)
  6. 5add p to the sum and 1 to the count of cells[c]
  7. 6Q ← an empty list
  8. 7for each entry (c, sum, count) of cells do
  9. 8append sum / count to Q
  10. 9return 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 z=0z = 0, voxel size s=1s = 1 and origin o=(0,0,0)o = (0, 0, 0). All the voxels have k=0k = 0, so the table shows only ii and jj.

point (x,y)(x, y) voxel (i,j)(i, j)
p1p_1 (0.2, 0.1) (0, 0)
p2p_2 (0.6, 0.3) (0, 0)
p3p_3 (1.5, 0.2) (1, 0)
p4p_4 (1.8, 0.9) (1, 0)
p5p_5 (1.2, 0.4) (1, 0)
p6p_6 (0.3, 1.7) (0, 1)

After the loop, the table holds three entries: voxel (0,0)(0, 0) with sum (0.8,0.4)(0.8, 0.4) and count 2, voxel (1,0)(1, 0) with sum (4.5,1.5)(4.5, 1.5) and count 3, and voxel (0,1)(0, 1) with sum (0.3,1.7)(0.3, 1.7) and count 1. Line L8 gives the three output points (0.4,0.2)(0.4, 0.2), (1.5,0.5)(1.5, 0.5) and (0.3,1.7)(0.3, 1.7). Six points became three. Each output point lies in its own voxel, and the single point p6p_6 is kept as it is.

Correctness

By the definition of the floor, line L3 gives the index cc exactly when the point lies in the half-open voxel V(c)V(c), so each point goes to exactly one voxel. An induction on the loop of line L2 shows that after tt points the table holds, for each voxel met so far, the sum and the count of the first tt 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 s3s\sqrt{3}, 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 P=(p1,…,pn)P = (p_1, \ldots, p_n) be the input points, s>0s > 0 the voxel size and oo the origin. For an integer triple c=(i,j,k)c = (i, j, k) the voxel is the half-open box

V(c)=[ox+is,ox+(i+1)s)×[oy+js,oy+(j+1)s)×[oz+ks,oz+(k+1)s).V(c) = [o_x + i s, o_x + (i+1) s) \times [o_y + j s, o_y + (j+1) s) \times [o_z + k s, o_z + (k+1) s).

Line L3 computes key(p)=(⌊(px−ox)/s⌋,⌊(py−oy)/s⌋,⌊(pz−oz)/s⌋)\mathrm{key}(p) = (\lfloor (p_x - o_x)/s \rfloor, \lfloor (p_y - o_y)/s \rfloor, \lfloor (p_z - o_z)/s \rfloor).

Lemma 1. p∈V(c)p \in V(c) if and only if key(p)=c\mathrm{key}(p) = c. So the voxels V(c)V(c) partition R3\mathbb{R}^3, and each point lies in exactly one of them.

Proof. For a real tt and an integer ii, ⌊t⌋=i\lfloor t \rfloor = i holds exactly when i≤t<i+1i \le t < i + 1. Apply this to t=(px−ox)/st = (p_x - o_x)/s and multiply by s>0s > 0, which keeps the order: ⌊(px−ox)/s⌋=i\lfloor (p_x - o_x)/s \rfloor = i exactly when ox+is≤px<ox+(i+1)so_x + i s \le p_x < o_x + (i+1) s. The same holds for yy and zz. The floor is a function, so each point has one key. □\square

For a key cc and 0≤t≤n0 \le t \le n let Gt(c)={m≤t:key(pm)=c}G_t(c) = \{ m \le t : \mathrm{key}(p_m) = c \}, the indices of the first tt points that fall in V(c)V(c).

Lemma 2 (invariant of the loop at line L2). After tt passes of the loop, the keys of the table cells\mathrm{cells} are exactly the keys cc with Gt(c)≠∅G_t(c) \ne \emptyset, in the order of the first index in Gt(c)G_t(c), and the entry of each such key holds ∑m∈Gt(c)pm\sum_{m \in G_t(c)} p_m and ∣Gt(c)∣|G_t(c)|.

Proof. By induction on tt. For t=0t = 0 the table is empty (line L1) and every G0(c)G_0(c) is empty. Assume the claim after tt passes and let c=key(pt+1)c = \mathrm{key}(p_{t+1}). Then Gt+1(c)=Gt(c)∪{t+1}G_{t+1}(c) = G_t(c) \cup \{t+1\}, and Gt+1(c′)=Gt(c′)G_{t+1}(c') = G_t(c') for every other key c′c'. If Gt(c)G_t(c) is empty, cc is not in the table, line L4 creates the entry with zero sum and zero count, and the insertion puts cc last, which is the order of first indices since t+1t + 1 is larger than all earlier first indices. Line L5 then adds pt+1p_{t+1} to the sum and 11 to the count of cc only. So the entry of cc holds the sum and the size of Gt+1(c)G_{t+1}(c), and the other entries do not change. □\square

Theorem. VOXEL-DOWNSAMPLE returns, for each voxel V(c)V(c) that holds at least one input point, the single point

q(c)=1∣P∩V(c)∣∑p∈P∩V(c)p,q(c) = \frac{1}{|P \cap V(c)|} \sum_{p \in P \cap V(c)} p,

and no other point. The points come in the order in which their voxels are first met in the input. Each q(c)q(c) lies in V(c)V(c), and every input point pp satisfies ∥p−q(key(p))∥<s3\| p - q(\mathrm{key}(p)) \| < s \sqrt{3}.

Proof. After the loop, t=nt = n. By Lemma 1, Gn(c)G_n(c) is the set of indices of the points in V(c)V(c), 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 11, 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.

V(c)V(c) is a product of half-open intervals, so it is convex. The point q(c)q(c) is a convex combination of points of V(c)V(c), with weights 1/∣Gn(c)∣1/|G_n(c)|, so q(c)∈V(c)q(c) \in V(c). Coordinate by coordinate: each pxp_x in the voxel satisfies ox+is≤px<ox+(i+1)so_x + i s \le p_x < o_x + (i+1) s, and an average of numbers in [a,b)[a, b) lies in [a,b)[a, b). Two points of one voxel differ by less than ss in each coordinate, so their distance is less than 3s2=s3\sqrt{3 s^2} = s \sqrt{3}. Both pp and q(key(p))q(\mathrm{key}(p)) lie in V(key(p))V(\mathrm{key}(p)), which gives the last claim. The loops run over nn points and over at most nn entries, so the procedure terminates. ■\blacksquare

The bound s3s\sqrt{3} 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 s3s\sqrt{3}. The other direction is also below s3s \sqrt{3}, 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 mm be the number of occupied voxels, with m≤nm \le n.

  • Time. Line L3 costs O(1)O(1) per point, and each lookup or insertion at lines L4 and L5 costs O(1)O(1) expected with a good hash function. The total is Θ(n)\Theta(n) expected. With a sort of the keys in place of the hash table, the time is O(nlog⁡n)O(n \log n) in the worst case, or O(n)O(n) with a radix sort on bounded integer keys.
  • Space. Θ(m)\Theta(m) extra for the table and the output.

No neighbor search is needed, so this is cheaper than any filter that looks at the kk 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, s3s\sqrt{3}, 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 int((px−ox)/s)\mathrm{int}((p_x - o_x)/s) at line L3 rounds toward zero, so the points in (−s,0)(-s, 0) and in [0,s)[0, s) 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 ss against the field width.
  • Large coordinates. In floating point, px−oxp_x - o_x 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.

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

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

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