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
- Model
- Real RAM
- Properties
- deterministicexactheuristicofflineiterativerigid motion invariantscale invariant
- Evidence
- Proof sketchCode in 1 languages
- 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 to its nearest neighbors. It then takes the mean and the standard deviation of these values over the whole cloud, and keeps a point only if , for a user choice of 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 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 of points in , a number of neighbors with , and a multiplier . The output is the sub-list of the points whose mean distance to their nearest neighbors is at most , where and are the mean and the standard deviation of these mean distances over all 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
SOR(P, k, α)- 1
for i ← 1 to n do - 2
N ← the k nearest neighbors of p_i in P, without p_i - 3
d_i ← (1/k) Σ_{q ∈ N} ‖p_i - q‖ - 4
μ ← (1/n) Σ_i d_i - 5
σ ← sqrt( (1/(n - 1)) Σ_i (d_i - μ)² ) - 6
T ← μ + α σ - 7
return the points p_i with d_i ≤ T, in input order
Line L2 is the expensive step. Build a k-d tree on once and query it with neighbors, since the nearest point to in is itself. Line L3 averages the distances, not the squared distances. Line L5 uses the sample variance with the divisor ; with many points, the divisor 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 makes smoother, but it also raises for points at the border of a surface, which have neighbors on one side only. A smaller removes more points.
Example
Take the nine points of a grid with spacing 1 in the plane , at for , and one outlier at . Use .
| point | two nearest distances | |
|---|---|---|
| each grid point | 1 and 1 | 1 |
| and | 3.217 |
Every grid point has two neighbors at distance 1. The outlier is nearest to , then to and , which tie. The mean is , and the sample standard deviation is .
- With , the threshold is . The outlier has , so it is removed, and the nine grid points stay.
- With , the threshold is , and the outlier stays. The outlier itself raised 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 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 , and the threshold by their definitions and keep exactly the points with . The values 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 , the one-sided Chebyshev inequality of Cantelli shows that at most points are removed, whatever the cloud: at most half for . 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 with , let and . For each let be the multiset of the distances , .
Lemma 1 (line L2 and L3 are well defined). The value of line L3 equals the mean of the smallest elements of , whatever neighbors line L2 picks among equal distances.
Proof. Sort as . A valid choice at line L2 is a set of points other than such that no point outside is strictly closer to than some point of . First, every point of is at distance at most : at least points are at distance at most , so if held a point farther than , one of those points would be outside and strictly closer. Next, let be the number of points at distance strictly less than . All of them are in : if one were missing, would hold at most points at distance below , so at least one point of would be at distance , and the missing point would be strictly closer than it. So is the points below plus points at distance exactly , and its distances are as a multiset. The sum at line L3 is for every valid choice.
Theorem 1 (output). Lines L4 to L7 return exactly the indices with , in input order, where and .
Proof. By Lemma 1 the loop of line L1 computes each . Lines L4, L5 and L6 compute , and the threshold by their definitions, with . Line L7 scans in order and keeps exactly when .
The values depend only on the distances between points. A rigid motion keeps all distances, and a permutation of the input permutes the without changing and . 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 multiplies every , and by , so it does not change the kept set either.
Theorem 2 (at most a fixed fraction is removed). If , the number of removed points is at most .
Proof. Let be the variance of the with the divisor . Then , so , and every removed index has .
If , all equal , and nothing is removed. Otherwise put , and let , which contains every removed index. For any and we have , so . Summing over and then over all , since the terms are squares,
because . Take . Then
This is the one-sided Chebyshev inequality of Cantelli, applied to the uniform distribution on the values .
With at most half of the points go, and with 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.
Complexity
The model is the real RAM, with points and neighbors per point.
- Brute force. Line L2 scans all other points, per point with a selection of the smallest. The total is for a fixed .
- With a k-d tree. Building the tree costs . In 3D, on points that are spread out without large clusters of equal coordinates, a query for neighbors visits nodes on average, and keeping the best in a heap costs per update. The total is then . This is an average case bound for well-spread data in low dimension, not a worst case bound.
- Lines L4 to L7. .
- Space. for the tree and the values .
Properties
- A heuristic. The rule assumes that the 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 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 and 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 points are removed for .
Variants and improvements
- Median and MAD. Replace by the median of the and 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 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 hid, but it also eats into the borders of surfaces.
- Local density ratios. Compare with the of the neighbors of , 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 nearest points of in returns first, at distance zero. Using these points at line L2 makes too small for every point. Query points and drop the first, or exclude the point by its index.
- Duplicates. Several identical points have neighbors at distance zero, so their 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 . The two-sided form also removes the points with very close neighbors, which are the densest and best samples.
- Large at borders. With a large , 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 small compared with the number of points on the smallest object you need, often 10 to 50.
- Units of . The threshold at line L6 is in standard deviations of , not in meters. The same 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.
# 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 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 and is the form most programs use.
References
- 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
- 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 RBGT7A Edit this page History Report an error Markdown