Algorithm Search⌘K

Algorithmcore

Statistical outlier removal

Also called statistical outlier filter.

Remove points whose mean distance to their k nearest neighbors is more than a few standard deviations above the mean of that distance over the cloud.

Time
O(n^2) worstO(n (log n + k log k)) averageΘ(n k) best
Space
Θ(n) extra
Where
k = the number of neighbors per point; n = the number of points
Properties
deterministicexactheuristicofflineiterativerigid motion invariantscale invariant
Origin
Radu Bogdan Rusu, Zoltan Csaba Marton, Nico Blodow, Mihai Dolha, Michael Beetz, 2008

Statistical outlier removal is a filter that deletes isolated points from a set of points in space. Laser scanners and depth cameras produce a few points that float in empty space, from reflections, from edges where the beam hits two surfaces, or from noise in the sensor. Such points are far from their neighbors. The filter measures, for each point, the mean distance did_i to its kk nearest neighbors. It then takes the mean μ\mu and the standard deviation σ\sigma of these values over the whole cloud, and keeps a point only if di≤μ+ασd_i \le \mu + \alpha \sigma, for a user choice of α\alpha such as 1 or 2. It is a rule of thumb, not a statistical test: it assumes that most points lie on dense surfaces, so that a large mean neighbor distance means an outlier. With a k-d tree for the neighbor search, it costs O(n(log⁡n+klog⁡k))O(n (\log n + k \log k)) time on well-spread points in 3D.

In plain words

Points on a real surface have close neighbors. A stray point in the air does not. So, for each point, find its few nearest neighbors and take the average distance to them. This gives one number per point, a measure of how lonely the point is.

Look at all these numbers together. Most of them are about the same, because most points sit on surfaces sampled at about the same spacing. Compute their average and their spread. A point whose number is much larger than the average, by more than a chosen number of spreads, is thrown away. The rest are kept.

The problem

The input is a finite list PP of nn points in R3\mathbb{R}^3, a number of neighbors kk with 1≤k≤n−11 \le k \le n - 1, and a multiplier α≥0\alpha \ge 0. The output is the sub-list of the points whose mean distance to their kk nearest neighbors is at most μ+ασ\mu + \alpha \sigma, where μ\mu and σ\sigma are the mean and the standard deviation of these mean distances over all nn points.

The real aim, to remove the points that are not samples of a surface, has no exact definition. The rule above is one practical stand-in for it.

The algorithm

  1. SOR(P, k, α)
  2. 1for i ← 1 to n do
  3. 2N ← the k nearest neighbors of p_i in P, without p_i
  4. 3d_i ← (1/k) Σ_{q ∈ N} ‖p_i - q‖
  5. 4μ ← (1/n) Σ_i d_i
  6. 5σ ← sqrt( (1/(n - 1)) Σ_i (d_i - μ)² )
  7. 6T ← μ + α σ
  8. 7return the points p_i with d_i ≤ T, in input order

Line L2 is the expensive step. Build a k-d tree on PP once and query it with k+1k + 1 neighbors, since the nearest point to pip_i in PP is pip_i itself. Line L3 averages the distances, not the squared distances. Line L5 uses the sample variance with the divisor n−1n - 1; with many points, the divisor nn gives the same result in practice. Lines L4 and L5 can run in one pass with Welford's method.

The rule has two parameters. A larger kk makes did_i smoother, but it also raises did_i for points at the border of a surface, which have neighbors on one side only. A smaller α\alpha removes more points.

Example

Take the nine points of a 3×33 \times 3 grid with spacing 1 in the plane z=0z = 0, at (x,y,0)(x, y, 0) for x,y∈{0,1,2}x, y \in \{0, 1, 2\}, and one outlier at (4,4,0)(4, 4, 0). Use k=2k = 2.

point two nearest distances did_i
each grid point 1 and 1 1
(4,4,0)(4, 4, 0) 8=2.828\sqrt{8} = 2.828 and 13=3.606\sqrt{13} = 3.606 3.217

Every grid point has two neighbors at distance 1. The outlier is nearest to (2,2,0)(2, 2, 0), then to (2,1,0)(2, 1, 0) and (1,2,0)(1, 2, 0), which tie. The mean is μ=(9⋅1+3.217)/10=1.2217\mu = (9 \cdot 1 + 3.217)/10 = 1.2217, and the sample standard deviation is σ=0.7011\sigma = 0.7011.

  • With α=1\alpha = 1, the threshold is T=1.9228T = 1.9228. The outlier has d=3.217>Td = 3.217 > T, so it is removed, and the nine grid points stay.
  • With α=3\alpha = 3, the threshold is T=3.3249T = 3.3249, and the outlier stays. The outlier itself raised σ\sigma from 0 to 0.70, enough to hide it at this setting. This is the masking effect of the mean and the standard deviation, which the variant with the median below avoids.

Correctness

The mean of the kk smallest distances is the same for every way to break ties among equal distances, so line L3 is well defined. Lines L4 to L7 then compute μ\mu, σ\sigma and the threshold by their definitions and keep exactly the points with di≤μ+ασd_i \le \mu + \alpha\sigma. The values did_i depend only on the distances between points, so the kept set does not change under a rigid motion, a uniform scaling or a reordering of the cloud.

The one guarantee on the result is a bound on the number of removed points. For α>0\alpha > 0, the one-sided Chebyshev inequality of Cantelli shows that at most n/(1+α2)n / (1 + \alpha^2) points are removed, whatever the cloud: at most half for α=1\alpha = 1. There is no guarantee that the removed points are outliers, or that all outliers are removed. The full proof is below.

Proof: SOR keeps exactly the points whose mean k-neighbor distance is at most mu + alpha sigma, and removes at most n/(1 + alpha^2) pointsfull

Let P=(p1,…,pn)P = (p_1, \ldots, p_n) with n≥2n \ge 2, let 1≤k≤n−11 \le k \le n - 1 and α≥0\alpha \ge 0. For each ii let DiD_i be the multiset of the n−1n - 1 distances ∥pi−pj∥\|p_i - p_j\|, j≠ij \ne i.

Lemma 1 (line L2 and L3 are well defined). The value did_i of line L3 equals the mean of the kk smallest elements of DiD_i, whatever neighbors line L2 picks among equal distances.

Proof. Sort DiD_i as δ1≤δ2≤⋯≤δn−1\delta_1 \le \delta_2 \le \cdots \le \delta_{n-1}. A valid choice at line L2 is a set NN of kk points other than pip_i such that no point outside NN is strictly closer to pip_i than some point of NN. First, every point of NN is at distance at most δk\delta_k: at least kk points are at distance at most δk\delta_k, so if NN held a point farther than δk\delta_k, one of those kk points would be outside NN and strictly closer. Next, let a<ka < k be the number of points at distance strictly less than δk\delta_k. All of them are in NN: if one were missing, NN would hold at most a−1a - 1 points at distance below δk\delta_k, so at least one point of NN would be at distance δk\delta_k, and the missing point would be strictly closer than it. So NN is the aa points below δk\delta_k plus k−ak - a points at distance exactly δk\delta_k, and its distances are δ1,…,δk\delta_1, \ldots, \delta_k as a multiset. The sum at line L3 is δ1+⋯+δk\delta_1 + \cdots + \delta_k for every valid choice. □\square

Theorem 1 (output). Lines L4 to L7 return exactly the indices ii with di≤μ+ασd_i \le \mu + \alpha \sigma, in input order, where μ=1n∑idi\mu = \frac{1}{n} \sum_i d_i and σ2=1n−1∑i(di−μ)2\sigma^2 = \frac{1}{n-1} \sum_i (d_i - \mu)^2.

Proof. By Lemma 1 the loop of line L1 computes each did_i. Lines L4, L5 and L6 compute μ\mu, σ\sigma and the threshold T=μ+ασT = \mu + \alpha \sigma by their definitions, with n−1≥1n - 1 \ge 1. Line L7 scans i=1,…,ni = 1, \ldots, n in order and keeps ii exactly when di≤Td_i \le T. □\square

The values did_i depend only on the distances between points. A rigid motion keeps all distances, and a permutation of the input permutes the did_i without changing μ\mu and σ\sigma. So the set of kept points does not change under a rigid motion of the cloud or a new order of the input. A uniform scaling by c>0c > 0 multiplies every did_i, μ\mu and σ\sigma by cc, so it does not change the kept set either.

Theorem 2 (at most a fixed fraction is removed). If α>0\alpha > 0, the number of removed points is at most n/(1+α2)n / (1 + \alpha^2).

Proof. Let s2=1n∑i(di−μ)2s^2 = \frac{1}{n} \sum_i (d_i - \mu)^2 be the variance of the did_i with the divisor nn. Then σ2=nn−1s2≥s2\sigma^2 = \frac{n}{n-1} s^2 \ge s^2, so T≥μ+αsT \ge \mu + \alpha s, and every removed index has di−μ>αsd_i - \mu > \alpha s.

If s=0s = 0, all did_i equal μ=T\mu = T, and nothing is removed. Otherwise put t=αs>0t = \alpha s > 0, and let R={i:di−μ≥t}R = \{ i : d_i - \mu \ge t \}, which contains every removed index. For any u≥0u \ge 0 and i∈Ri \in R we have di−μ+u≥t+u>0d_i - \mu + u \ge t + u > 0, so (di−μ+u)2≥(t+u)2(d_i - \mu + u)^2 \ge (t + u)^2. Summing over RR and then over all ii, since the terms are squares,

∣R∣(t+u)2≤∑i=1n(di−μ+u)2=ns2+2u∑i=1n(di−μ)+nu2=n(s2+u2),|R| (t + u)^2 \le \sum_{i=1}^{n} (d_i - \mu + u)^2 = n s^2 + 2u \sum_{i=1}^n (d_i - \mu) + n u^2 = n (s^2 + u^2),

because ∑i(di−μ)=0\sum_i (d_i - \mu) = 0. Take u=s2/tu = s^2 / t. Then

∣R∣n≤s2+s4/t2(t+s2/t)2=s2(t2+s2)/t2(t2+s2)2/t2=s2s2+t2=11+α2.\frac{|R|}{n} \le \frac{s^2 + s^4/t^2}{(t + s^2/t)^2} = \frac{s^2 (t^2 + s^2)/t^2}{(t^2 + s^2)^2 / t^2} = \frac{s^2}{s^2 + t^2} = \frac{1}{1 + \alpha^2}.

This is the one-sided Chebyshev inequality of Cantelli, applied to the uniform distribution on the values did_i. □\square

With α=1\alpha = 1 at most half of the points go, and with α=2\alpha = 2 at most a fifth. The bound needs no assumption on how the points are distributed. It also shows the weak side of the method: it is a bound on how much the filter removes, not a promise that it removes the outliers. ■\blacksquare

Complexity

The model is the real RAM, with nn points and kk neighbors per point.

  • Brute force. Line L2 scans all other points, Θ(n)\Theta(n) per point with a selection of the kk smallest. The total is Θ(n2)\Theta(n^2) for a fixed kk.
  • With a k-d tree. Building the tree costs O(nlog⁡n)O(n \log n). In 3D, on points that are spread out without large clusters of equal coordinates, a query for kk neighbors visits O(log⁡n+k)O(\log n + k) nodes on average, and keeping the kk best in a heap costs O(log⁡k)O(\log k) per update. The total is then O(n(log⁡n+klog⁡k))O(n (\log n + k \log k)). This is an average case bound for well-spread data in low dimension, not a worst case bound.
  • Lines L4 to L7. Θ(n)\Theta(n).
  • Space. Θ(n)\Theta(n) for the tree and the values did_i.

Properties

  • A heuristic. The rule assumes that the did_i of the surface points form one tight group. It has no model of the sensor and no false alarm rate.
  • Global threshold. One threshold serves the whole cloud. Where the density falls with the distance to the sensor, far surfaces have large did_i and can be removed as a whole, while dense clusters of outliers near the sensor are kept.
  • Not robust. The mean and the standard deviation have a breakdown point of zero, so a few far outliers raise μ\mu and σ\sigma and hide themselves, as in the example.
  • Invariant. The result does not depend on the order of the points, on a rigid motion or on a uniform scaling of the cloud.
  • Bounded removal. At most n/(1+α2)n / (1 + \alpha^2) points are removed for α>0\alpha > 0.

Variants and improvements

  • Median and MAD. Replace μ\mu by the median of the did_i and σ\sigma by a scaled median absolute deviation. These have a breakdown point of one half, so a group of outliers cannot hide itself.
  • Radius outlier removal. Count the neighbors within a fixed radius rr of each point, and remove the points with fewer than a set count. This needs one radius search per point and no global statistics, but the radius depends on the density.
  • Repeat. Run the filter again on the output. Each pass removes outliers that the previous σ\sigma hid, but it also eats into the borders of surfaces.
  • Local density ratios. Compare did_i with the djd_j of the neighbors of pip_i, not with the global mean. This adapts to the fall of density with range. The local outlier factor of Breunig, Kriegel, Ng and Sander (2000) is a method of this kind.
  • Clusters. Group the points with DBSCAN or by connected components of a radius graph, and remove the small clusters. This also removes small groups of outliers that are dense inside.
  • Downsample first. A voxel grid before the filter makes the density more even, so the global threshold fits better.

When to use it

Use statistical outlier removal on raw scans before normal estimation, registration and surface reconstruction, where isolated points spoil the local fits. It works best on clouds of roughly even density with sparse, scattered outliers. On clouds whose density changes a lot with the distance to the sensor, downsample first or use a local variant. Do not use it to remove dense groups of false points, such as the ghost points of a mirror or the mixed points along a depth edge: those have close neighbors.

Pitfalls

  • The point is its own neighbor. A k-d tree query for the kk nearest points of pip_i in PP returns pip_i first, at distance zero. Using these kk points at line L2 makes did_i too small for every point. Query k+1k + 1 points and drop the first, or exclude the point by its index.
  • Duplicates. Several identical points have neighbors at distance zero, so their did_i is small and they are always kept. Remove exact duplicates first if they come from the sensor.
  • The wrong side of the threshold. The rule at line L7 keeps points with small did_i. The two-sided form ∣di−μ∣≤ασ|d_i - \mu| \le \alpha\sigma also removes the points with very close neighbors, which are the densest and best samples.
  • Large kk at borders. With a large kk, line L3 reaches far past the border of a small surface, so a thin object or the edge of a table can be removed as outliers. Keep kk small compared with the number of points on the smallest object you need, often 10 to 50.
  • Units of α\alpha. The threshold at line L6 is in standard deviations of did_i, not in meters. The same α\alpha removes more or fewer points on another cloud. If you need a distance in meters, use a radius filter.

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.

statistical_outlier_removal.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/statistical-outlier-removal/. The authors are listed in prov/RBGT7A.jsonl.
"""Statistical outlier removal for a 3D point cloud.

For each point, take the mean distance to its k nearest neighbors (the point
itself excluded). Over the whole cloud, take the mean mu and the sample
standard deviation sigma of these mean distances. Keep the points whose mean
distance is at most mu + alpha sigma.

The neighbor search here is a brute force scan, O(n^2 log k) in total, which
is enough for the small clouds of the tests. A k-d tree gives the same
neighbor distances faster in low dimension.
"""

from __future__ import annotations

import heapq
import math
from typing import List, Sequence, Tuple


def knn_distances(points: Sequence[Sequence[float]], i: int, k: int) -> List[float]:
    """The k smallest distances from point i to the other points, ascending.

    The multiset of the k smallest distances does not depend on how ties
    between equal distances are broken."""
    p = points[i]
    return heapq.nsmallest(k, (math.dist(p, q) for j, q in enumerate(points) if j != i))


def mean_knn_distances(points: Sequence[Sequence[float]], k: int) -> List[float]:
    """d_i, the mean distance of each point to its k nearest neighbors."""
    n = len(points)
    if not 1 <= k <= n - 1:
        raise ValueError("need 1 <= k <= n - 1")
    d: List[float] = []
    for i in range(n):  # @line L1
        nbr = knn_distances(points, i, k)  # @line L2
        d.append(sum(nbr) / k)  # @line L3
    return d


def statistical_outlier_removal(points: Sequence[Sequence[float]], k: int,
                                alpha: float) -> Tuple[List[int], float]:
    """Return (the indices of the kept points in input order, the threshold).

    Preconditions: n >= 2 points and 1 <= k <= n - 1."""
    n = len(points)
    if n < 2:
        raise ValueError("need at least 2 points")
    d = mean_knn_distances(points, k)
    mu = sum(d) / n  # @line L4
    sigma = math.sqrt(sum((x - mu) ** 2 for x in d) / (n - 1))  # @line L5
    threshold = mu + alpha * sigma  # @line L6
    kept = [i for i in range(n) if d[i] <= threshold]  # @line L7
    return kept, threshold
test_statistical_outlier_removal.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/statistical-outlier-removal/. The authors are listed in prov/RBGT7A.jsonl.

import math
import random
import statistics

import pytest

from statistical_outlier_removal import mean_knn_distances, statistical_outlier_removal

GRID = [(x, y, 0) for y in range(3) for x in range(3)] + [(4, 4, 0)]


def oracle(points, k, alpha):
    """Sort all distances of each point, then use the statistics module."""
    d = []
    for i, p in enumerate(points):
        ds = sorted(math.dist(p, q) for j, q in enumerate(points) if j != i)
        d.append(sum(ds[:k]) / k)
    t = statistics.mean(d) + alpha * statistics.stdev(d)
    return [i for i in range(len(points)) if d[i] <= t + 1e-12], d


def test_example() -> None:
    d = mean_knn_distances(GRID, 2)
    assert all(abs(x - 1.0) < 1e-12 for x in d[:9])
    assert abs(d[9] - (math.sqrt(8) + math.sqrt(13)) / 2) < 1e-12
    kept, t = statistical_outlier_removal(GRID, 2, 1.0)
    assert kept == list(range(9))
    assert abs(t - 1.92277246) < 1e-7
    kept3, t3 = statistical_outlier_removal(GRID, 2, 3.0)
    assert kept3 == list(range(10))  # one outlier inflates sigma and hides itself


def test_matches_oracle() -> None:
    rng = random.Random(5)
    for _ in range(30):
        n = rng.randint(3, 40)
        pts = [tuple(rng.uniform(-2, 2) for _ in range(3)) for _ in range(n)]
        k = rng.randint(1, n - 1)
        alpha = rng.choice([0.0, 0.5, 1.0, 2.0])
        kept, _ = statistical_outlier_removal(pts, k, alpha)
        want, _ = oracle(pts, k, alpha)
        assert kept == want


def test_planted_outliers_are_removed() -> None:
    rng = random.Random(6)
    surface = [(0.1 * i + rng.gauss(0, 0.005), 0.1 * j + rng.gauss(0, 0.005), rng.gauss(0, 0.005))
               for i in range(10) for j in range(8)]
    outliers = [(rng.uniform(-2, 3), rng.uniform(-2, 3), rng.uniform(0.6, 2.0)) for _ in range(6)]
    pts = surface + outliers
    kept, _ = statistical_outlier_removal(pts, 6, 1.0)
    assert kept == list(range(len(surface)))


def test_cantelli_bound_on_removed_fraction() -> None:
    rng = random.Random(7)
    for _ in range(20):
        n = rng.randint(5, 50)
        pts = [tuple(rng.expovariate(1.0) ** 3 for _ in range(3)) for _ in range(n)]
        for alpha in (0.5, 1.0, 2.0):
            kept, _ = statistical_outlier_removal(pts, 3, alpha)
            removed = n - len(kept)
            assert removed <= n / (1 + alpha * alpha)


def test_invariance_under_order_and_rigid_motion() -> None:
    rng = random.Random(8)
    pts = [tuple(rng.gauss(0, 1) for _ in range(3)) for _ in range(30)] + [(9.0, 9.0, 9.0)]
    kept, _ = statistical_outlier_removal(pts, 4, 1.0)
    perm = list(range(len(pts)))
    rng.shuffle(perm)
    kept_p, _ = statistical_outlier_removal([pts[i] for i in perm], 4, 1.0)
    assert sorted(perm[i] for i in kept_p) == kept
    c, s = math.cos(0.7), math.sin(0.7)
    moved = [(c * x - s * y + 5.0, s * x + c * y - 2.0, z + 1.0) for x, y, z in pts]
    kept_m, _ = statistical_outlier_removal(moved, 4, 1.0)
    assert kept_m == kept
    assert len(pts) - 1 not in kept


def test_edges() -> None:
    same = [(1.0, 1.0, 1.0)] * 5
    kept, t = statistical_outlier_removal(same, 2, 1.0)
    assert kept == [0, 1, 2, 3, 4] and t == 0.0
    with pytest.raises(ValueError):
        statistical_outlier_removal([(0.0, 0.0, 0.0)], 1, 1.0)
    with pytest.raises(ValueError):
        statistical_outlier_removal(GRID, 10, 1.0)

History

Rusu, Marton, Blodow, Dolha and Beetz (2008) built maps of kitchens from laser scans for a household robot. To remove the sparse outliers of the scans, they computed the mean distance of each point to its kk nearest neighbors, modeled these distances by their mean and standard deviation, and trimmed the points that fell outside an interval set by these two values. The method became the StatisticalOutlierRemoval filter of the Point Cloud Library (Rusu and Cousins, 2011), which keeps the points below the threshold μ+ασ\mu + \alpha\sigma and is the form most programs use.

References

  1. Radu Bogdan Rusu, Zoltan Csaba Marton, Nico Blodow, Mihai Dolha and Michael Beetz, Towards 3D point cloud based object maps for household environments, Robotics and Autonomous Systems 56(11), 2008, 927-941, The removal of sparse outliers by the mean and the standard deviation of the mean distances to the k nearest neighbors
  2. 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
  • at least three sources
  • a scene preset for the example