Algorithm Search⌘K

Algorithmadvanced

Efficient RANSAC for shape detection

Also called Schnabel RANSAC.

Detect planes, spheres, cylinders, cones and tori in a point cloud by RANSAC with local sampling in an octree and lazy scoring on random subsets.

Time
O(s^2 n + n d) worstO(s n / r + k n + n d) averageΩ(n d) best
Space
Θ(n d + s) extra
Where
d = the depth of the octree; k = the number of shapes found; n = the number of points; r = the number of random subsets; s = the number of draws
Properties
randomizednot exactneeds normalsofflinerandomizediterative
Origin
Ruwen Schnabel, Roland Wahl, Reinhard Klein, 2007

Efficient RANSAC for shape detection breaks a point cloud with normals into simple shapes: planes, spheres, cylinders, cones and tori, plus the points that fit none of them. It is a form of RANSAC built for clouds of millions of points that hold many shapes of very different sizes, such as scans of buildings and machine parts. Plain RANSAC fails there for two reasons. A random sample of three points rarely falls on one small shape, and scoring each candidate on every point is too slow. Schnabel, Wahl and Klein (2007) fix the first problem by drawing the second and third points from an octree cell around the first one, and the second by scoring candidates on a random subset first and on more subsets only when the decision is close. Normals from normal estimation make the minimal sets small and let the method reject wrong candidates at once. The method finds the largest shape first, removes its points, and searches again.

In plain words

You have a scan of an object made of flat faces, balls and pipes, and you want to know which points belong to which part.

Pick three points at random. If they lie on one face, the face through them is a guess. Count how many points of the scan lie on that guess, and keep the guess with the largest count. Take its points out, and start again for the next part.

Three tricks make this fast. Pick the second and third points close to the first, so that they are likely on the same part. Count the points of a guess on a small random sample first, and count more only when two guesses are close. Use the direction each point faces: a point that sits on a guess but faces the wrong way does not count.

The problem

The input is a set PP of nn points with unit normals, a distance tolerance ε\varepsilon, an angle tolerance α\alpha, a connection distance β\beta, a least support τ\tau and a wanted probability ptp_t. A point is compatible with a shape when it lies within ε\varepsilon of the shape and its normal makes an angle of at most α\alpha with the shape normal there, up to sign.

The output is a list of shapes, each with a set of at least τ\tau points that are compatible with it and connected by steps of at most β\beta. The sets are disjoint. The points of no set are the rest. The wanted result is the decomposition of the scanned object into its parts, which has no exact form; the method searches greedily for the shape with the largest compatible connected set, and finds it with a probability that it controls with ptp_t.

The algorithm

  1. EFFICIENT-RANSAC(P, ε, α, β, τ, p_t)
  2. 1build an octree on P and split P into random subsets S_1, …, S_r
  3. 2R ← P; C ← ∅; s ← 0; shapes ← an empty list
  4. 3while |R| ≥ τ do
  5. 4draw p from R and a level ℓ; draw two more points of R from the cell of p at level ℓ; s ← s + 1
  6. 5fit a plane, a sphere and a cylinder to the three points; keep those that all three points are compatible with
  7. 6score each new candidate on S_1, extrapolate the score to an interval, and add it to C
  8. 7m ← the candidate with the largest expected score; score m and every candidate whose interval overlaps it on the next subsets, until no overlap
  9. 8if 1 - (1 - P(ŝ(m)))^s ≥ p_t then
  10. 9A ← the largest β-connected set of points of R compatible with m
  11. 10if |A| ≥ τ then append (m, A) to shapes; R ← R \ A; C ← ∅; s ← 0
  12. 11else remove m from C
  13. 12if no shape was taken at line L10 and 1 - (1 - P(τ))^s ≥ p_t then stop
  14. 13return shapes

Here P(n)P(n) is the probability that one draw puts all three sample points on a shape with nn points of RR, and s^(m)\hat s(m) is the expected score of mm. For uniform draws P(n)=(n/∣R∣)3P(n) = (n / |R|)^3; Schnabel and his coauthors use a bound for the localized draws of line L4.

Line L4 draws the first point uniformly and the other two from one octree cell around it, at a random level. A coarse cell holds the large shapes, and a fine cell isolates a small shape among clutter. Line L5 uses the normals. A plane needs three points. A sphere needs two points with normals: its center lies on both normal lines. A cylinder needs two points with normals: the cross product of the normals gives the axis direction, and the normal lines meet the axis. The third point then only checks the candidate. Cones and tori need more sample points; they follow the same pattern and are left out of the code below. Lines L6 and L7 are the lazy score: most candidates are poor, and one small subset shows that. Line L8 decides when to take the best candidate: once a shape of its size would have been drawn with probability ptp_t, a larger shape is unlikely to be still missing. Line L9 keeps only one connected piece, so two coplanar faces far apart are two shapes. Line L12 stops when a shape of size τ\tau would have been found by now with probability ptp_t.

Example

The fits of line L5, on exact data:

shape points normals fit
plane (0,0,0)(0,0,0), (1,0,0)(1,0,0), (0,1,0)(0,1,0) (0,0,1)(0,0,1), (0,0,−1)(0,0,-1), (0,0,1)(0,0,1) normal (0,0,1)(0,0,1) from the cross product, d=0d = 0; the signs of the normals do not matter
sphere (1,0,0)(1,0,0), (0,1,0)(0,1,0), check (0,0,1)(0,0,1) (1,0,0)(1,0,0), (0,1,0)(0,1,0), (0,0,1)(0,0,1) the normal lines meet at (0,0,0)(0,0,0), radius 1; the third point is on it
cylinder (1,0,0)(1,0,0), (0,1,5)(0,1,5), check (−1,0,2)(-1,0,2) (1,0,0)(1,0,0), (0,1,0)(0,1,0), (−1,0,0)(-1,0,0) axis direction (1,0,0)×(0,1,0)=(0,0,1)(1,0,0) \times (0,1,0) = (0,0,1); seen along it, the normal lines meet at (0,0)(0,0), so the axis is the zz axis and the radius is 1

The search, on a scene of 840 points: a plane with 300 points, a sphere and a cylinder with 250 points each, and 40 points of clutter, with τ=100\tau = 100 and pt=0.99p_t = 0.99. The rule of line L8 with uniform draws needs this many draws:

∣R∣\lvert R \rvert best shape (n/∣R∣)3(n / \lvert R \rvert)^3 draws for 0.99
840 plane, 300 0.0456 99
540 sphere or cylinder, 250 0.0992 45
290 the last one, 250 0.641 5

After the third shape, 40 points remain, fewer than τ\tau, and the loop ends. Before that, a shape of only τ=100\tau = 100 points among 840 would need 2728 draws to reach the same probability. This is why small shapes in large clouds are slow for plain RANSAC, and why line L4 samples locally: once the first point is on the small shape, the other two come from a cell that the shape fills, so the draw hits it much more often.

Correctness

On exact data, the fits of line L5 return the true plane, sphere or cylinder whenever the sample is not degenerate: three points that are not collinear for a plane, and two normals that are not parallel for a sphere or a cylinder. After a candidate is scored on all subsets, its score is the exact count of compatible points of RR, because the subsets partition the points. The refinement of line L7 ends after at most rr steps per candidate. Every output shape has at least τ\tau compatible points that are connected by steps of at most β\beta, and the point sets of different shapes are disjoint. The loop ends for every pt<1p_t < 1, because the draw count grows between extractions and each extraction removes at least τ\tau points. That the best shape is found is a statement of probability: if each draw hits a shape with probability at least qq, the chance of ss misses is at most (1−q)s(1 - q)^s. With localized draws the value of qq is an estimate or a bound, not an exact number. The full proof is below.

Proof: The minimal fits recover exact shapes, the extracted shapes are disjoint connected sets of compatible points, and the search stopsfull

Write RR for the set of remaining points, ε\varepsilon for the distance tolerance, α\alpha for the angle tolerance, β\beta for the connectivity distance, τ≥3\tau \ge 3 for the least support and pt<1p_t < 1 for the wanted probability. A point pp with unit normal n\mathbf{n} is compatible with a shape when its distance to the shape is at most ε\varepsilon and ∣n⋅s∣≥cos⁡α|\mathbf{n} \cdot \mathbf{s}| \ge \cos \alpha, where s\mathbf{s} is the unit normal of the shape at the closest point. RANSAC methods do not find the true shapes with certainty, so the statements below are of two kinds: exact properties of every run, and the probability argument behind the stop rule.

The fits of line L5

Lemma 1 (exact minimal fits). Let three points with unit normals lie exactly on a shape, with the true normals of the shape.

  1. If the shape is a plane and the points are not collinear, the plane fit returns it.
  2. If the shape is a sphere and the first two normals are not parallel, the sphere fit returns it.
  3. If the shape is a cylinder and the first two normals are not parallel, the cylinder fit returns it.

Proof. (1) The vector (p2−p1)×(p3−p1)(p_2 - p_1) \times (p_3 - p_1) is nonzero and orthogonal to two independent directions of the plane, so it is a multiple of the plane normal n\mathbf{n}, and n⋅p1=d\mathbf{n} \cdot p_1 = d. Every point has distance 0 and normal ±n\pm \mathbf{n}, so the check passes.

(2) The normal of a sphere with center cc at pip_i is ±(pi−c)/r\pm (p_i - c)/r, so the line pi+tnip_i + t \mathbf{n}_i passes through cc. Two lines with nonparallel directions that meet have exactly one common point, which is then the closest pair of points of both lines, so both closest points equal cc and their midpoint is cc. Both distances to cc are rr, so the radius is rr, and all three points pass the check.

(3) The normal of a cylinder with axis c+tac + t \mathbf{a} at pip_i is the unit radial vector, which is orthogonal to a\mathbf{a}. Two nonparallel vectors orthogonal to a\mathbf{a} have a cross product parallel to a\mathbf{a}, so the fit finds the axis direction up to sign. Project along a\mathbf{a} onto the plane through the origin orthogonal to it. The axis becomes one point cˉ\bar c, and the projected normal line of pip_i passes through cˉ\bar c, because the radial vector runs from the axis to pip_i. As in (2), the two projected lines meet only at cˉ\bar c, so the fit gets a point on the axis, and both axis distances are rr. □\square

With noise the fits are not exact, and the check of all three sample points against ε\varepsilon and α\alpha rejects samples that do not fit one shape. The third point of a sphere or cylinder sample does not take part in the fit and serves only for this check.

The lazy score of lines L6 and L7

The subsets S1,…,SrS_1, \ldots, S_r of line L1 are a partition of the points.

Lemma 2 (the score becomes exact). After a candidate is scored on all rr subsets, its score is the number of points of RR compatible with it.

Proof. Each refinement counts the points of one subset that are in RR and compatible. The subsets are disjoint and cover all points, and RR does not change while candidates are kept (the candidates are cleared at every extraction), so after all rr subsets the count is the exact count over RR, and the code then sets the expected value and both ends of the interval to it. □\square

Lemma 3 (the refinement of line L7 stops). The loop of line L7 ends, and it returns a candidate mm of largest expected score such that every other candidate either has an interval entirely below the lower end of the interval of mm, or has been scored on all subsets, as has mm.

Proof. Each round that does not return refines at least one candidate by one subset. A candidate can be refined at most rr times, and no candidate is added during the loop, so there are at most r∣C∣r |C| rounds. The loop returns exactly when there is no rival with an upper end at or above the lower end of mm, or when mm and every such rival are exact; this is the stated condition. □\square

When the intervals are valid confidence intervals, a returned mm that has no rival is the candidate with the largest score with the probability of those intervals. When all the overlapping candidates are exact, mm has the largest score among them for certain.

The extraction of lines L8 to L11

Theorem 1 (the output). Every shape in the output has at least τ\tau points; each of its points was in RR when it was extracted and is compatible with it; its points are connected by steps of length at most β\beta between its own points; and the point sets of different shapes are disjoint.

Proof. Line L9 takes the set II of points of RR compatible with mm and returns the largest connected component of the graph on II with an edge for every pair at distance at most β\beta. The search by grid cells of side β\beta finds every such pair, since two points at distance at most β\beta have cell coordinates that differ by at most 1 on each axis. Line L10 accepts the component only when it has at least τ\tau points, and then removes it from RR. Later shapes take their points from the smaller RR, so they cannot take these points again. □\square

The stop rule of line L12

Lemma 4 (missing a shape). Let a shape have nn compatible points in RR, and suppose each draw puts all three sample points among them with probability at least q>0q > 0, independently of the other draws. Then the probability that none of ss draws does so is at most (1−q)s(1 - q)^s.

Proof. The draws are independent, so the probability that all ss fail is the product of the ss failure probabilities, each at most 1−q1 - q. □\square

For three points drawn uniformly and independently from RR, with replacement, q=(n/∣R∣)3q = (n / |R|)^3, and the function of lines L8 and L12 is 1−(1−q)s1 - (1 - q)^s. Line L8 extracts the best candidate once a shape of its estimated size would have been hit with probability at least ptp_t: then it is unlikely that a larger shape was never drawn. Line L12 stops once a shape of τ\tau points would have been hit with probability at least ptp_t and no shape was extracted. The localized draws of line L4 are not uniform: they raise the chance for a compact shape that fills the cells it meets, and lower it for a shape spread thinly over many cells. So for this implementation the two tests are estimates, not bounds. Schnabel and his coauthors give a bound for localized sampling in an octree, which can replace qq.

Theorem 2 (termination). If pt<1p_t < 1, the main loop ends.

Proof. Each extraction removes at least τ≥3\tau \ge 3 points, so there are at most n/3n / 3 extractions. Between two extractions, each pass of the loop adds 1 to the draw count ss. While the loop runs, ∣R∣≥τ|R| \ge \tau, so qτ=(τ/∣R∣)3>0q_\tau = (\tau / |R|)^3 > 0, and 1−(1−qτ)s1 - (1 - q_\tau)^s grows to 1 as ss grows. Once it reaches ptp_t, the next pass without an extraction stops the loop at line L12. The refinements inside a pass end by Lemma 3, and the sampling at line L4 always succeeds, because level 0 of the octree holds all of RR, which has at least τ≥3\tau \ge 3 points. ■\blacksquare

Complexity

The model is the real RAM, with nn points, ss draws in total, rr subsets, kk shapes found and an octree of depth dd.

  • Build. The octree costs O(nd)O(n d) time and space. The random split costs O(n)O(n).
  • One draw. Lines L4 and L5 cost the size of the cell for the sample, and O(1)O(1) for the fits. Line L6 costs O(n/r)O(n / r) per candidate.
  • Refinement. In the worst case every candidate is refined to the full set at every draw, O(sn)O(s n) per draw and O(s2n)O(s^2 n) in total. In practice most candidates are poor, their intervals end far below the best one after one subset, and the cost is O(sn/r)O(s n / r) in total.
  • Extraction. Lines L9 to L11 cost O(n)O(n) for the compatible points, and the connected set costs O(n)O(n) more on clouds of bounded density with a grid of side β\beta. With kk shapes and a bounded number of failed extractions, this is O(kn)O(k n).
  • Space. Θ(nd)\Theta(n d) for the octree and Θ(s)\Theta(s) for the candidates.

The number of draws is set by the rule of lines L8 and L12, not by nn. It grows when the shapes are small compared with ∣R∣|R|, which localized sampling is meant to offset.

Properties

  • Randomized. Two runs with different seeds can return different shapes in a different order. With a fixed seed the result is fixed.
  • Greedy. The largest shape goes first and keeps its points. A wrong early shape, such as a plane that cuts across two faces within ε\varepsilon, takes points from the shapes that follow.
  • Needs normals. The fits and the compatibility test use them. Without normals the minimal sets are larger and many more candidates are wrong.
  • Sign free. The normals need no consistent orientation; the test uses the absolute value of the dot product.
  • Robust to clutter. Points of no shape do not affect a candidate's score, unless they happen to be compatible with it.

Variants and improvements

  • Refit. After line L9, fit the shape again to all its points by least squares, as in geometric primitive fitting, and collect the compatible points again. This lowers the error of a shape fitted from three noisy points.
  • Bitmap connectivity. The original method finds the connected set in a 2D bitmap over the parameter domain of the shape, with a cell size set by β\beta, which is faster than a 3D search and follows the shape itself.
  • Adaptive levels. The original method uses the scores of past candidates to learn which octree levels give good candidates, and draws the levels with these rates in place of uniformly.
  • Keep the candidates. After an extraction, only candidates that used removed points need to go; the others can be scored again on the smaller RR. This saves draws.
  • More shapes. Cones, tori and other surfaces that can be fitted from a few oriented points fit the same frame.
  • MSAC scores. Score by a truncated sum of distances, as in MSAC, in place of a count.
  • Region growing and Hough methods. Region growing from seed points with similar normals, and the Hough transform for planes, are the main other ways to find shapes in clouds. Multi-model methods such as J-linkage group all hypotheses at once.

When to use it

Use efficient RANSAC to turn a scan of a building, a machine part or an indoor room into simple shapes, for primitive segmentation, reverse engineering, compression or detection of walls and floors. It needs normals and a good choice of ε\varepsilon, α\alpha and β\beta for the noise and the sampling density. For a cloud of only planes, region growing or a plane Hough transform is often simpler. For free-form surfaces with no simple shapes, use a surface reconstruction method.

Pitfalls

  • ε below the noise. If ε\varepsilon at line L5 or line L9 is smaller than the noise of the scan, the fits fail their check and each shape breaks into many small pieces. Measure the noise on a known flat part first.
  • Too loose an angle. A large α\alpha lets line L9 accept points from a neighboring face near an edge, and lets a sphere of large radius pass as a plane. A small α\alpha fails on noisy normals.
  • β and the density. At line L9, a β\beta smaller than the sampling spacing breaks one face into pieces; one larger than the gap between parts joins them.
  • Huge spheres and cylinders. Near-flat samples give spheres and cylinders of very large radius at line L5, which compete with the true plane. Bound the radius by the size of the scene.
  • Trusting the probability. The rule of lines L8 and L12 assumes that a draw hits a shape with a known probability. With localized draws or a poor model of the clutter this is only an estimate, so a small shape can still be missed.
  • Normals across edges. Normals estimated near edges are blends of the two faces, so points near edges fail the check of line L9 and stay unassigned. This is expected; assign them afterwards to the nearest shape if needed.

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.

efficient_ransac_shape_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/efficient-ransac-shape-detection/. The authors are listed in prov/NAW12G.jsonl.
"""Efficient RANSAC for shape detection in a point cloud with normals, after
Schnabel, Wahl and Klein (2007), for planes, spheres and cylinders.

The three ideas of the method are here:

1. Localized sampling. The first point of a minimal set is drawn uniformly;
   the other two are drawn from the octree cell of the first point at a
   random level, so they are likely to lie on the same shape.
2. Lazy scoring. The points are split once into random subsets. A candidate
   is scored on the first subset, its score is extrapolated to an interval,
   and it is scored on more subsets only while its interval overlaps the
   interval of the best candidate.
3. Probabilistic extraction. The best candidate is extracted when the
   probability that a shape of its size was missed by every draw so far is
   below 1 - p_t. The extracted shape keeps only the largest connected set of
   its compatible points, and those points are removed.

A point is compatible with a shape when it is within eps of the shape and
its normal is within alpha of the shape normal there, up to sign.

Simplifications, compared with the paper: the octree level is drawn
uniformly, the subsets have equal sizes, the interval uses a normal
approximation, the candidates are cleared after each extraction, the
connectivity uses a 3D distance beta in place of a bitmap in the parameter
domain of the shape, and the shape is not refitted to its points. Cones and
tori are left out. The draw probability uses the bound for uniform
sampling, (n / |R|)^3.
"""

from __future__ import annotations

import math
import random
from typing import Dict, List, Optional, Sequence, Set, Tuple

Vec = Tuple[float, float, float]
Shape = Tuple[str, tuple]


def _sub(a, b) -> Vec:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def _add(a, b) -> Vec:
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


def _mul(s: float, a) -> Vec:
    return (s * a[0], s * a[1], s * a[2])


def _dot(a, b) -> float:
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def _cross(a, b) -> Vec:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def _norm(a) -> float:
    return math.sqrt(_dot(a, a))


def _unit(a) -> Optional[Vec]:
    length = _norm(a)
    if length < 1e-12:
        return None
    return _mul(1.0 / length, a)


def shape_distance_and_normal(shape: Shape, p) -> Tuple[float, Optional[Vec]]:
    """Distance from p to the shape, and the unit shape normal at the
    closest point (None where it is not defined)."""
    kind, par = shape
    if kind == "plane":
        n, d = par
        return abs(_dot(n, p) - d), n
    if kind == "sphere":
        c, r = par
        v = _sub(p, c)
        return abs(_norm(v) - r), _unit(v)
    c, a, r = par  # cylinder: a point c on the axis, the unit direction a
    v = _sub(p, c)
    radial = _sub(v, _mul(_dot(v, a), a))
    return abs(_norm(radial) - r), _unit(radial)


def compatible(shape: Shape, p, n, eps: float, cos_alpha: float) -> bool:
    dist, sn = shape_distance_and_normal(shape, p)
    return dist <= eps and sn is not None and abs(_dot(sn, n)) >= cos_alpha


def _closest_points_of_lines(p1, d1, p2, d2) -> Optional[Tuple[Vec, Vec]]:
    """Closest points of the lines p1 + t d1 and p2 + u d2, unit d1 and d2."""
    b = _dot(d1, d2)
    denom = 1.0 - b * b
    if denom < 1e-6:
        return None
    w = _sub(p1, p2)
    d, e = _dot(d1, w), _dot(d2, w)
    t = (b * e - d) / denom
    u = (e - b * d) / denom
    return _add(p1, _mul(t, d1)), _add(p2, _mul(u, d2))


def fit_plane(ps, ns, eps: float, cos_alpha: float) -> Optional[Shape]:
    n = _unit(_cross(_sub(ps[1], ps[0]), _sub(ps[2], ps[0])))
    if n is None:
        return None
    shape = ("plane", (n, _dot(n, ps[0])))
    return shape if all(compatible(shape, p, m, eps, cos_alpha) for p, m in zip(ps, ns)) else None


def fit_sphere(ps, ns, eps: float, cos_alpha: float, max_radius: float) -> Optional[Shape]:
    """The center is the midpoint of the closest points of the two normal
    lines; the third point only verifies."""
    cp = _closest_points_of_lines(ps[0], ns[0], ps[1], ns[1])
    if cp is None:
        return None
    c = _mul(0.5, _add(cp[0], cp[1]))
    r = 0.5 * (_norm(_sub(ps[0], c)) + _norm(_sub(ps[1], c)))
    if r > max_radius:
        return None
    shape = ("sphere", (c, r))
    return shape if all(compatible(shape, p, m, eps, cos_alpha) for p, m in zip(ps, ns)) else None


def fit_cylinder(ps, ns, eps: float, cos_alpha: float, max_radius: float) -> Optional[Shape]:
    """The axis direction is n1 x n2; the axis passes through the meeting
    point of the two normal lines projected along it."""
    a = _unit(_cross(ns[0], ns[1]))
    if a is None:
        return None
    q1 = _sub(ps[0], _mul(_dot(ps[0], a), a))
    q2 = _sub(ps[1], _mul(_dot(ps[1], a), a))
    m1 = _unit(_sub(ns[0], _mul(_dot(ns[0], a), a)))
    m2 = _unit(_sub(ns[1], _mul(_dot(ns[1], a), a)))
    if m1 is None or m2 is None:
        return None
    cp = _closest_points_of_lines(q1, m1, q2, m2)
    if cp is None:
        return None
    c = _mul(0.5, _add(cp[0], cp[1]))

    def axis_distance(p) -> float:
        v = _sub(p, c)
        return _norm(_sub(v, _mul(_dot(v, a), a)))

    r = 0.5 * (axis_distance(ps[0]) + axis_distance(ps[1]))
    if r > max_radius:
        return None
    shape = ("cylinder", (c, a, r))
    return shape if all(compatible(shape, p, m, eps, cos_alpha) for p, m in zip(ps, ns)) else None


class Octree:
    """An implicit octree: the cell of a point at level l is its integer
    key in a grid of 2^l cells per side over the bounding cube."""

    def __init__(self, points: Sequence[Sequence[float]], depth: int) -> None:
        self.depth = depth
        self.origin = tuple(min(p[i] for p in points) for i in range(3))
        self.size = max(max(p[i] for p in points) - self.origin[i] for i in range(3)) or 1.0
        self.cells: List[Dict[tuple, List[int]]] = []
        for level in range(depth + 1):
            table: Dict[tuple, List[int]] = {}
            for i, p in enumerate(points):
                table.setdefault(self.key(p, level), []).append(i)
            self.cells.append(table)

    def key(self, p, level: int) -> tuple:
        side = 1 << level
        return tuple(min(side - 1, int((p[i] - self.origin[i]) / self.size * side)) for i in range(3))

    def cell(self, p, level: int) -> List[int]:
        return self.cells[level][self.key(p, level)]


class Candidate:
    """A shape with a lazily computed score over the random subsets."""

    def __init__(self, shape: Shape, ident: int) -> None:
        self.shape, self.ident = shape, ident
        self.j = 0  # the number of subsets scored
        self.hits = 0  # compatible points among the tested points
        self.tested = 0  # remaining points of the scored subsets
        self.est = self.lo = self.hi = 0.0

    def refine(self, subsets, remaining: Set[int], points, normals, eps, cos_alpha) -> None:
        for i in subsets[self.j]:
            if i in remaining:
                self.tested += 1
                if compatible(self.shape, points[i], normals[i], eps, cos_alpha):
                    self.hits += 1
        self.j += 1
        size = len(remaining)
        if self.j == len(subsets):
            self.est = self.lo = self.hi = float(self.hits)
        elif self.tested == 0:
            self.est, self.lo, self.hi = 0.0, 0.0, float(size)
        else:
            f = self.hits / self.tested
            self.est = f * size
            half = 2.0 * size * math.sqrt(f * (1.0 - f) / self.tested) + size / self.tested
            self.lo, self.hi = max(0.0, self.est - half), min(float(size), self.est + half)


def _separate(cands: List[Candidate], subsets, remaining, points, normals, eps, cos_alpha) -> Candidate:
    """Refine until the best candidate's interval overlaps no other one."""
    while True:
        best = max(cands, key=lambda c: (c.est, -c.ident))
        rivals = [c for c in cands if c is not best and c.hi >= best.lo]
        todo = [c for c in rivals + [best] if c.j < len(subsets)]
        if not rivals or not todo:
            return best
        for c in todo:
            c.refine(subsets, remaining, points, normals, eps, cos_alpha)


def largest_component(points, idxs: Sequence[int], beta: float) -> List[int]:
    """The largest set of the given points connected by steps of length at
    most beta. Ties go to the set with the smallest index."""
    grid: Dict[tuple, List[int]] = {}
    for i in idxs:
        grid.setdefault(tuple(math.floor(x / beta) for x in points[i]), []).append(i)
    seen: Set[int] = set()
    best: List[int] = []
    for start in sorted(idxs):
        if start in seen:
            continue
        seen.add(start)
        comp, stack = [start], [start]
        while stack:
            i = stack.pop()
            kx, ky, kz = (math.floor(x / beta) for x in points[i])
            for dx in (-1, 0, 1):
                for dy in (-1, 0, 1):
                    for dz in (-1, 0, 1):
                        for j in grid.get((kx + dx, ky + dy, kz + dz), ()):
                            if j not in seen and math.dist(points[i], points[j]) <= beta:
                                seen.add(j)
                                comp.append(j)
                                stack.append(j)
        if len(comp) > len(best):
            best = comp
    return sorted(best)


def hit_probability(n: float, remaining: int, draws: int) -> float:
    """The probability that at least one of the draws hits a shape of n
    points, for uniform draws of three points: 1 - (1 - (n/|R|)^3)^draws."""
    if remaining == 0 or n <= 0:
        return 0.0
    p = min(1.0, n / remaining) ** 3
    return 1.0 - (1.0 - p) ** draws


def detect_shapes(points: Sequence[Sequence[float]], normals: Sequence[Sequence[float]],
                  eps: float, alpha_degrees: float, beta: float, min_support: int,
                  p_t: float = 0.99, depth: int = 4, num_subsets: int = 8,
                  seed: int = 0) -> List[Tuple[Shape, List[int]]]:
    """Return the detected shapes in the order of extraction, each with the
    sorted indices of its points."""
    if min_support < 3:
        raise ValueError("min_support must be at least 3")
    if len(points) != len(normals):
        raise ValueError("one normal per point")
    n = len(points)
    if n < min_support:
        return []
    rng = random.Random(seed)
    cos_alpha = math.cos(math.radians(alpha_degrees))
    tree = Octree(points, depth)  # @line L1
    order = list(range(n))
    rng.shuffle(order)
    subsets = [order[i::num_subsets] for i in range(num_subsets)]
    max_radius = tree.size
    remaining: Set[int] = set(range(n))  # @line L2
    cands: List[Candidate] = []
    draws, made = 0, 0
    shapes: List[Tuple[Shape, List[int]]] = []
    pool = sorted(remaining)  # R as a list, rebuilt after each extraction
    while len(remaining) >= min_support:  # @line L3
        first = rng.choice(pool)  # @line L4
        level = rng.randint(0, depth)
        while True:
            others = [i for i in tree.cell(points[first], level) if i in remaining and i != first]
            if len(others) >= 2 or level == 0:
                break
            level -= 1
        sample = [first] + rng.sample(others, 2)
        draws += 1
        ps = [points[i] for i in sample]
        ns = [normals[i] for i in sample]
        fits = (fit_plane(ps, ns, eps, cos_alpha),  # @line L5
                fit_sphere(ps, ns, eps, cos_alpha, max_radius),
                fit_cylinder(ps, ns, eps, cos_alpha, max_radius))
        for shape in fits:
            if shape is not None:
                made += 1
                cand = Candidate(shape, made)
                cand.refine(subsets, remaining, points, normals, eps, cos_alpha)  # @line L6
                cands.append(cand)
        extracted = False
        if cands:
            best = _separate(cands, subsets, remaining, points, normals, eps, cos_alpha)  # @line L7
            if hit_probability(best.est, len(remaining), draws) >= p_t:  # @line L8
                inliers = [i for i in remaining
                           if compatible(best.shape, points[i], normals[i], eps, cos_alpha)]
                comp = largest_component(points, inliers, beta)  # @line L9
                if len(comp) >= min_support:  # @line L10
                    shapes.append((best.shape, comp))
                    remaining.difference_update(comp)
                    pool = sorted(remaining)
                    cands, draws, extracted = [], 0, True
                else:
                    cands.remove(best)  # @line L11
        if not extracted and hit_probability(min_support, len(remaining), draws) >= p_t:  # @line L12
            break
    return shapes  # @line L13
test_efficient_ransac_shape_detection.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/efficient-ransac-shape-detection/. The authors are listed in prov/NAW12G.jsonl.

import math
import random

import pytest

from efficient_ransac_shape_detection import (
    Candidate,
    Octree,
    compatible,
    detect_shapes,
    fit_cylinder,
    fit_plane,
    fit_sphere,
    hit_probability,
    largest_component,
)

COS10 = math.cos(math.radians(10))


def close(a, b, tol=1e-9):
    return all(abs(x - y) <= tol for x, y in zip(a, b))


def unit(v):
    length = math.sqrt(sum(x * x for x in v))
    return tuple(x / length for x in v)


def test_example_fits() -> None:
    plane = fit_plane([(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 0, 1), (0, 0, -1), (0, 0, 1)], 0.01, COS10)
    assert plane[0] == "plane" and close(plane[1][0], (0, 0, 1)) and abs(plane[1][1]) < 1e-12
    sphere = fit_sphere([(1, 0, 0), (0, 1, 0), (0, 0, 1)], [(1, 0, 0), (0, 1, 0), (0, 0, 1)], 0.01, COS10, 10)
    assert sphere[0] == "sphere" and close(sphere[1][0], (0, 0, 0)) and abs(sphere[1][1] - 1) < 1e-12
    cyl = fit_cylinder([(1, 0, 0), (0, 1, 5), (-1, 0, 2)], [(1, 0, 0), (0, 1, 0), (-1, 0, 0)], 0.01, COS10, 10)
    assert cyl[0] == "cylinder" and close(cyl[1][0], (0, 0, 0)) and abs(abs(cyl[1][1][2]) - 1) < 1e-12
    assert abs(cyl[1][2] - 1) < 1e-12


def test_fits_reject_bad_normals_and_bad_third_points() -> None:
    tilted = unit((1, 0, 1))
    assert fit_plane([(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 0, 1), tilted, (0, 0, 1)], 0.01, COS10) is None
    # The third point is off the sphere through the first two.
    assert fit_sphere([(1, 0, 0), (0, 1, 0), (0, 0, 2)], [(1, 0, 0), (0, 1, 0), (0, 0, 1)], 0.01, COS10, 10) is None
    # Parallel normals give no sphere and no cylinder.
    ps, ns = [(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 0, 1)] * 3
    assert fit_sphere(ps, ns, 0.01, COS10, 10) is None and fit_cylinder(ps, ns, 0.01, COS10, 10) is None


def scene(rng):
    pts, nrm, label = [], [], []

    def add(p, n, lab):
        pts.append(tuple(x + rng.gauss(0, 0.002) for x in p))
        s = rng.choice([-1.0, 1.0])
        nrm.append(tuple(s * x for x in n))
        label.append(lab)

    for _ in range(300):
        add((rng.uniform(0, 3), rng.uniform(0, 3), 0.0), (0.0, 0.0, 1.0), "plane")
    for _ in range(250):
        u = unit([rng.gauss(0, 1) for _ in range(3)])
        add(tuple(c + 0.8 * x for c, x in zip((1.5, 1.5, 2.5), u)), u, "sphere")
    for _ in range(250):
        t = rng.uniform(0, 2 * math.pi)
        add((5 + 0.6 * math.cos(t), rng.uniform(0, 3), 1 + 0.6 * math.sin(t)), (math.cos(t), 0.0, math.sin(t)), "cylinder")
    for _ in range(40):
        add((rng.uniform(0, 6), rng.uniform(0, 3), rng.uniform(0, 3.5)), unit([rng.gauss(0, 1) for _ in range(3)]), "noise")
    return pts, nrm, label


def test_scene_with_three_shapes() -> None:
    pts, nrm, label = scene(random.Random(41))
    shapes = detect_shapes(pts, nrm, eps=0.02, alpha_degrees=15, beta=0.45, min_support=100, seed=7)
    assert sorted(s[0] for s, _ in shapes) == ["cylinder", "plane", "sphere"]
    for (kind, par), idx in shapes:
        own = sum(1 for i in idx if label[i] == kind)
        assert own >= 0.95 * label.count(kind) and len(idx) - own <= 5
        if kind == "plane":
            assert abs(abs(par[0][2]) - 1) < 1e-3 and abs(par[1]) < 0.01
        elif kind == "sphere":
            assert math.dist(par[0], (1.5, 1.5, 2.5)) < 0.02 and abs(par[1] - 0.8) < 0.02
        else:
            c, a, r = par
            assert abs(abs(a[1]) - 1) < 1e-2 and abs(r - 0.6) < 0.02
            assert math.hypot(c[0] - 5, c[2] - 1) < 0.03


def test_connectivity_splits_coplanar_patches() -> None:
    rng = random.Random(42)
    big = [(rng.uniform(0, 2), rng.uniform(0, 2), 0.0) for _ in range(120)]
    small = [(rng.uniform(5, 6.5), rng.uniform(0, 1.5), 0.0) for _ in range(80)]
    pts = big + small
    nrm = [(0.0, 0.0, 1.0)] * len(pts)
    shapes = detect_shapes(pts, nrm, eps=0.01, alpha_degrees=10, beta=0.5, min_support=50, seed=3)
    assert [len(idx) for _, idx in shapes] == [120, 80]
    assert shapes[0][1] == list(range(120))


def test_pure_noise_gives_nothing() -> None:
    rng = random.Random(43)
    pts = [tuple(rng.uniform(0, 1) for _ in range(3)) for _ in range(120)]
    nrm = [unit([rng.gauss(0, 1) for _ in range(3)]) for _ in range(120)]
    assert detect_shapes(pts, nrm, eps=0.005, alpha_degrees=10, beta=0.2, min_support=30, seed=1) == []


def test_lazy_score_becomes_exact() -> None:
    pts, nrm, _ = scene(random.Random(44))
    shape = ("plane", ((0.0, 0.0, 1.0), 0.0))
    remaining = set(range(len(pts)))
    subsets = [list(range(len(pts)))[i::5] for i in range(5)]
    cand = Candidate(shape, 1)
    exact = sum(1 for i in remaining if compatible(shape, pts[i], nrm[i], 0.02, COS10))
    for _ in range(5):
        cand.refine(subsets, remaining, pts, nrm, 0.02, COS10)
        assert cand.lo <= exact <= cand.hi
    assert cand.est == cand.lo == cand.hi == exact


def test_hit_probability() -> None:
    assert hit_probability(50, 100, 1) == pytest.approx(0.125)
    assert hit_probability(50, 100, 2) == pytest.approx(1 - 0.875 ** 2)
    assert hit_probability(0, 100, 10) == 0.0
    assert hit_probability(100, 100, 1) == 1.0


def test_octree_cells_nest() -> None:
    rng = random.Random(45)
    pts = [tuple(rng.uniform(-1, 3) for _ in range(3)) for _ in range(200)]
    tree = Octree(pts, 4)
    for i, p in enumerate(pts):
        for level in range(5):
            assert i in tree.cell(p, level)
            if level:
                assert set(tree.cell(p, level)) <= set(tree.cell(p, level - 1))
    assert len(tree.cell(pts[0], 0)) == 200


def test_largest_component() -> None:
    pts = [(0, 0, 0), (0.5, 0, 0), (1.0, 0, 0), (5, 0, 0), (5.4, 0, 0), (9, 9, 9)]
    assert largest_component(pts, range(6), 0.6) == [0, 1, 2]
    assert largest_component(pts, [3, 4, 5], 0.6) == [3, 4]


def test_edges() -> None:
    with pytest.raises(ValueError):
        detect_shapes([(0, 0, 0)] * 3, [(0, 0, 1)] * 3, 0.1, 10, 0.5, 2)
    assert detect_shapes([], [], 0.1, 10, 0.5, 3) == []

History

Fischler and Bolles (1981) introduced RANSAC: fit a model to a random minimal sample and keep the model that most data points agree with. For point clouds, RANSAC was used early on to find planes and other shapes, but on large clouds with many shapes it needed far too many samples and far too many evaluations. Schnabel, Wahl and Klein (2007) addressed both costs. They sampled minimal sets locally in an octree, so that small shapes were found as fast as large ones, scored candidates on random subsets with confidence intervals, and used the normals to fit planes, spheres, cylinders, cones and tori from very small samples. They defined the score as the largest connected set of compatible points, and gave the probability of having missed a shape as the rule for when to extract a candidate and when to stop. Their method became a standard tool for shape detection in point clouds, with implementations in libraries for geometry processing.

References

  1. Ruwen Schnabel, Roland Wahl and Reinhard Klein, Efficient RANSAC for point-cloud shape detection, Computer Graphics Forum 26(2), 2007, 214-226, The shapes and their minimal sets with normals, the score of compatible points in the largest connected component, the localized sampling in an octree, the score evaluation on random subsets, and the probability of having missed a shape
  2. Martin A. Fischler and Robert C. Bolles, Random sample consensus: a paradigm for model fitting with applications to image analysis and automated cartography, Communications of the ACM 24(6), 1981, 381-395, The RANSAC paradigm of fitting models to minimal random samples and keeping the model with the largest consensus set

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