Algorithm Search⌘K

Algorithmcore

Point cloud normal estimation

Also called PCA normal estimation, local plane fitting.

Estimate the normal at a point as the eigenvector of least eigenvalue of the covariance of its nearest neighbors.

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
deterministicnot exactofflineiterativerigid motion invariantsign ambiguous
Origin
Hugues Hoppe, Tony DeRose, Tom Duchamp, John McDonald, Werner Stuetzle, 1992

Point cloud normal estimation finds, for each point of a set of 3D points sampled from a surface, the direction perpendicular to the surface at that point. The points come without the surface, so the method fits a plane to the kk nearest neighbors of each point and takes the normal of that plane. The best plane in the least squares sense passes through the centroid of the neighbors, and its normal is the eigenvector of the smallest eigenvalue of their 3×33 \times 3 covariance matrix. This is local principal component analysis: the two large components span the tangent plane, and the smallest one is the normal. The method gives a line, not a direction: the sign of each normal is arbitrary, and making the signs agree is a separate problem, consistent normal orientation. The normals feed point-to-plane ICP, shape detection, descriptors and surface reconstruction.

In plain words

Look at one point and its closest neighbors, say 10 or 20 of them. On a smooth surface they lie almost on a flat sheet. Find the flat sheet that passes closest to all of them. The normal is the direction straight out of that sheet.

To find the sheet, measure how the neighbors spread out around their middle point. They spread a lot along the two directions of the sheet, and very little across it. The direction with the least spread is the normal. The amount of spread across the sheet, compared with the total, also tells you how flat the patch is: zero on a plane, larger at edges, corners and noise.

The method cannot tell the outside of the sheet from the inside. It gives the normal up to its sign.

The problem

The input is a finite list PP of nn points in R3\mathbb{R}^3, sampled from a smooth surface with some noise, and a neighborhood size kk with 3≤k≤n3 \le k \le n. For each point pip_i the output is a unit vector ni\mathbf{n}_i that approximates the surface normal at pip_i, up to sign, and a number σi\sigma_i that measures how far the neighborhood is from a plane.

The surface is unknown, so the true normal is not available, and "approximates" has no exact meaning without a model of the sampling and the noise. The algorithm solves an exact problem in its place: for each neighborhood, the plane that minimizes the sum of the squared orthogonal distances to the neighbors.

The algorithm

  1. ESTIMATE-NORMALS(P, k, o) ▷ o is an optional viewpoint
  2. 1for each point p_i in P do
  3. 2Q ← the k points of P nearest to p_i, with p_i itself
  4. 3c ← (1/k) Σ_{q ∈ Q} q
  5. 4C ← (1/k) Σ_{q ∈ Q} (q - c)(q - c)ᵀ
  6. 5(λ₀ ≤ λ₁ ≤ λ₂, v₀, v₁, v₂) ← the eigenvalues and unit eigenvectors of C
  7. 6n_i ← v₀
  8. 7σ_i ← λ₀ / (λ₀ + λ₁ + λ₂)
  9. 8if o is given and n_i · (o - p_i) < 0 then n_i ← -n_i
  10. 9return the pairs (n_i, σ_i)

Line L2 is a kk-nearest neighbor query, usually on a k-d tree built once, or a fixed radius query. On a range image the neighbors are the cells of a small window. Lines L3 and L4 build the covariance around the centroid, not around pip_i. Line L5 solves a symmetric 3×33 \times 3 eigenproblem, for example by the Jacobi eigenvalue algorithm or by the closed form for the roots of a cubic. Line L7 is the surface variation of Pauly, Gross and Kobbelt (2002). Line L8 is the usual quick fix for the sign when the cloud comes from one sensor at oo: a surface seen by the sensor faces it.

The same normal is the right singular vector of the smallest singular value of the k×3k \times 3 matrix of centered neighbors. The SVD is a little more accurate in floating point, and the covariance is cheaper.

Example

Take a neighborhood of five points: the corners (±1,±1,0)(\pm 1, \pm 1, 0) of a square, and a bump (0,0,0.5)(0, 0, 0.5) at its center.

step value
centroid cc (0,0,0.1)(0, 0, 0.1)
CxxC_{xx}, CyyC_{yy} 4/5=0.84/5 = 0.8 each
CzzC_{zz} (4⋅0.12+0.42)/5=0.04(4 \cdot 0.1^2 + 0.4^2)/5 = 0.04
CxyC_{xy}, CxzC_{xz}, CyzC_{yz} 0, by symmetry
eigenvalues 0.04,0.8,0.80.04, 0.8, 0.8
normal v0v_0 (0,0,±1)(0, 0, \pm 1)
surface variation 0.04/1.64=0.02440.04 / 1.64 = 0.0244

The covariance is diagonal, so its eigenvectors are the axes. The least spread is along zz, and the normal is ±z\pm z, as the shape of the square says. The bump pulls the centroid up to z=0.1z = 0.1 but does not tilt the plane, because it sits at the center. The surface variation is small but not zero: the five points are not coplanar. Moving the bump to a corner, (1,1,0.5)(1, 1, 0.5), would tilt the fitted plane toward it.

Correctness

For a fixed unit normal nn, the sum of squared distances to the plane n⋅x=dn \cdot x = d is least when the plane passes through the centroid, and it then equals k n⊤Cnk\, n^\top C n. By the spectral theorem, n⊤Cnn^\top C n over unit vectors is least at the eigenvector of the least eigenvalue, so line L6 gives the normal of the total least squares plane of the neighborhood. The surface variation lies in [0,1/3][0, 1/3]. It is 0 exactly when the neighbors are coplanar, and 1/31/3 exactly when the three eigenvalues are equal. A rigid motion of the cloud rotates every normal with it and keeps every σi\sigma_i. The full proof is below.

This is a statement about the fit, not about the true surface. How close v0v_0 is to the true normal depends on the noise, the curvature, the sampling density and kk, as analyzed by Mitra and Nguyen (2003): a larger kk averages out more noise but sees more curvature, so there is a best neighborhood size that depends on the data.

Proof: The least eigenvector of the neighbor covariance is the normal of the least squares plane, and the surface variation lies in [0, 1/3] and is 0 exactly for coplanar pointsfull

Fix one point and its neighborhood Q={q1,…,qk}Q = \{q_1, \ldots, q_k\} from line L2, with k≥3k \ge 3. Line L3 computes the centroid c=1k∑jqjc = \frac1k \sum_j q_j, and line L4 the covariance

C=1k∑j=1k(qj−c)(qj−c)⊤.C = \frac1k \sum_{j=1}^{k} (q_j - c)(q_j - c)^\top.

CC is symmetric, and x⊤Cx=1k∑j(x⋅(qj−c))2≥0x^\top C x = \frac1k \sum_j (x \cdot (q_j - c))^2 \ge 0 for every xx, so CC is positive semidefinite. By the spectral theorem it has real eigenvalues 0≤λ0≤λ1≤λ20 \le \lambda_0 \le \lambda_1 \le \lambda_2 with orthonormal eigenvectors v0,v1,v2v_0, v_1, v_2, which line L5 returns.

For a unit vector nn and a number dd, the plane {x:n⋅x=d}\{x : n \cdot x = d\} has the squared distance sum

E(n,d)=∑j=1k(n⋅qj−d)2.E(n, d) = \sum_{j=1}^{k} (n \cdot q_j - d)^2.

Lemma 1 (the plane passes through the centroid). For a fixed unit nn, E(n,d)E(n, d) is least at d=n⋅cd = n \cdot c, and E(n,n⋅c)=k n⊤CnE(n, n \cdot c) = k\, n^\top C n.

Proof. Write n⋅qj−d=n⋅(qj−c)+(n⋅c−d)n \cdot q_j - d = n \cdot (q_j - c) + (n \cdot c - d). Expanding the square and using ∑j(qj−c)=0\sum_j (q_j - c) = 0, the cross term vanishes, so

E(n,d)=∑j(n⋅(qj−c))2+k(n⋅c−d)2.E(n, d) = \sum_j (n \cdot (q_j - c))^2 + k (n \cdot c - d)^2.

The second term is zero exactly at d=n⋅cd = n \cdot c, and the first term is k n⊤Cnk\, n^\top C n. □\square

Theorem 1 (line L6 gives the least squares plane). The unit vector v0v_0 minimizes E(n,n⋅c)E(n, n \cdot c) over all unit nn, and the least value is kλ0k \lambda_0. If λ0<λ1\lambda_0 < \lambda_1, the minimizers are exactly ±v0\pm v_0.

Proof. Write a unit nn as n=∑iαivin = \sum_i \alpha_i v_i with ∑iαi2=1\sum_i \alpha_i^2 = 1. Then n⊤Cn=∑iλiαi2≥λ0∑iαi2=λ0n^\top C n = \sum_i \lambda_i \alpha_i^2 \ge \lambda_0 \sum_i \alpha_i^2 = \lambda_0, with equality at n=v0n = v_0. If λ0<λ1\lambda_0 < \lambda_1, equality forces α1=α2=0\alpha_1 = \alpha_2 = 0, so n=±v0n = \pm v_0. With Lemma 1, the plane through cc with normal v0v_0 minimizes E(n,d)E(n, d) over all planes. □\square

So the normal of line L6 is the normal of the total least squares plane of the neighborhood, the plane that minimizes the sum of squared orthogonal distances. When λ0=λ1\lambda_0 = \lambda_1, for example on a line of points or a symmetric blob, every unit vector of the span of v0v_0 and v1v_1 is equally good, and the normal is not defined by the data.

Theorem 2 (surface variation). Let σ=λ0/(λ0+λ1+λ2)\sigma = \lambda_0 / (\lambda_0 + \lambda_1 + \lambda_2) as at line L7, defined when the points are not all equal. Then 0≤σ≤1/30 \le \sigma \le 1/3, σ=0\sigma = 0 exactly when the kk points lie in one plane, and σ=1/3\sigma = 1/3 exactly when λ0=λ1=λ2\lambda_0 = \lambda_1 = \lambda_2.

Proof. The sum λ0+λ1+λ2=trace(C)=1k∑j∥qj−c∥2\lambda_0 + \lambda_1 + \lambda_2 = \mathrm{trace}(C) = \frac1k \sum_j \|q_j - c\|^2 is positive when the points are not all equal. Since λ0≥0\lambda_0 \ge 0, σ≥0\sigma \ge 0. Since λ0\lambda_0 is the least of three numbers, 3λ0≤λ0+λ1+λ23\lambda_0 \le \lambda_0 + \lambda_1 + \lambda_2, so σ≤1/3\sigma \le 1/3, with equality exactly when the three are equal. Finally λ0=0\lambda_0 = 0 holds exactly when v0⊤Cv0=1k∑j(v0⋅(qj−c))2=0v_0^\top C v_0 = \frac1k \sum_j (v_0 \cdot (q_j - c))^2 = 0, that is, when every qjq_j lies on the plane through cc with normal v0v_0; and if the points lie on any plane, Lemma 1 and Theorem 1 give kλ0≤E=0k \lambda_0 \le E = 0. □\square

Theorem 3 (rigid motions and the viewpoint). If every point is moved by x↦Rx+tx \mapsto R x + t with RR a rotation, the neighborhoods do not change, the normal becomes ±Rv0\pm R v_0, and σ\sigma does not change. With a viewpoint oo, line L8 returns the one of ±v0\pm v_0 with n⋅(o−p)≥0n \cdot (o - p) \ge 0.

Proof. Distances do not change, so line L2 picks the same indices (ties are broken by index). The centroid becomes Rc+tR c + t, and the covariance becomes RCR⊤R C R^\top, which has the same eigenvalues and the eigenvectors RviR v_i. Line L8 flips nn exactly when n⋅(o−p)<0n \cdot (o - p) < 0, and the flipped vector has −n⋅(o−p)>0-n \cdot (o - p) > 0. □\square

Each neighborhood is processed in a fixed number of steps once the eigenvectors are found, and the Jacobi method of the helper stops after at most 100 sweeps, so the procedure terminates. The eigenvectors are computed in floating point, so in practice the results hold up to rounding. ■\blacksquare

Complexity

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

  • Per point, after the search. Lines L3 and L4 cost Θ(k)\Theta(k). Line L5 is a 3×33 \times 3 problem and costs O(1)O(1). Lines L6 to L8 cost O(1)O(1).
  • Neighbor search. Brute force costs Θ(n)\Theta(n) per point, so Θ(n2)\Theta(n^2) in total. With a k-d tree on well-spread points in 3D, the build costs O(nlog⁡n)O(n \log n) and a query costs O(log⁡n+klog⁡k)O(\log n + k \log k) on average, for O(n(log⁡n+klog⁡k))O(n (\log n + k \log k)) in total. On a range image the search is free.
  • Space. Θ(n)\Theta(n) for the tree and the output.

The search dominates. The fit itself is Θ(nk)\Theta(n k) in total.

Properties

  • Sign ambiguous. v0v_0 and −v0-v_0 are both eigenvectors. Without a viewpoint, the sign of each normal is arbitrary.
  • Rigid motion invariant. Rotating and moving the cloud rotates the normals with it and keeps the surface variation.
  • Smoothing. The fitted plane averages over the neighborhood, so it rounds off sharp edges: a point on an edge gets a normal between the normals of the two faces.
  • Not robust. One outlier in the neighborhood can tilt the plane as much as it likes. Remove outliers first, for example with statistical outlier removal.
  • Degenerate neighborhoods. If the neighbors lie on a line, λ0=λ1=0\lambda_0 = \lambda_1 = 0 and every direction perpendicular to the line fits equally well.

Variants and improvements

  • Weighted covariance. Weight each neighbor by a function of its distance to pip_i, such as a Gaussian. This makes the result depend less on the exact choice of kk.
  • Radius neighborhoods. Use the points within a radius rr in place of the kk nearest. This fixes the scale of the fit in meters, which helps on clouds of even density.
  • Adaptive kk. Choose kk per point from estimates of the noise and the curvature, as Mitra and Nguyen propose, or take the kk that minimizes the surface variation.
  • Robust fits. Fit the plane with RANSAC or an M-estimator, which keeps sharp edges and ignores outliers. Methods that use a randomized Hough transform or that fit several planes near edges follow the same idea.
  • Quadric fits and jets. Fit a quadratic or cubic height function in the frame of the PCA plane. This gives better normals on curved surfaces and also the curvatures.
  • Normals from a grid. On a range image, the cross product of the differences to the grid neighbors gives a normal in O(1)O(1) time with no search.
  • Learned estimators. Networks trained on synthetic shapes predict normals from neighborhoods. They are outside this page.

When to use it

Use PCA normals as the default for any point cloud that lacks normals: they are cheap, stable on smooth surfaces and need only kk. Remove outliers and downsample to an even density first, and choose kk to cover a patch that is flat at the scale of the noise, often 10 to 30 points. Use a robust or a jet fit when the shapes have sharp edges or high curvature. If the normals must point outward, follow with a viewpoint test or with consistent normal orientation.

Pitfalls

  • The wrong eigenvector. Libraries return eigenvalues in different orders. Line L6 needs the eigenvector of the least eigenvalue. With an SVD, which sorts singular values from large to small, it is the last right singular vector, not the first.
  • No centering. Using ∑(q−pi)(q−pi)⊤\sum (q - p_i)(q - p_i)^\top at line L4, around the point and not the centroid, mixes the offset of the point into the matrix and tilts the normal. Subtract the centroid of line L3.
  • One-pass covariance at large coordinates. Computing CC as 1k∑qq⊤−cc⊤\frac1k \sum q q^\top - c c^\top cancels most of its digits when the coordinates are large compared with the size of the neighborhood, as in georeferenced lidar. Subtract the centroid first, or a local origin.
  • Neighbors from one scan line. A lidar samples densely along each scan line and sparsely across lines. The kk nearest neighbors can all come from one line, so λ0≈λ1\lambda_0 \approx \lambda_1 and the normal is noise. Use a radius large enough to reach the next line, or a grid of the scan.
  • Trusting the sign. Line L6 gives no sign. Code that uses the normals as if they pointed outward, for shading, for ICP rejection rules or for reconstruction, fails at random. Orient them at line L8 or with a propagation method.
  • Too large a neighborhood across thin parts. For a thin plate, the kk nearest neighbors can include points of the other side. The fit then sees two parallel sheets and still finds a good plane, but the curvature and the orientation step later go wrong.

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.

cvla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

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

Matrix = List[List[float]]
Vector = List[float]

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-vectors."""
    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 skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
point_cloud_normal_estimation.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/point-cloud-normal-estimation/. The authors are listed in prov/J9D82K.jsonl.
"""Normal estimation for a point cloud by local principal component analysis.

For each point p, take its k nearest points (p itself included, as a k-d
tree query returns it), their centroid c and their covariance matrix
C = (1/k) sum (q - c)(q - c)^T. The normal is the unit eigenvector of the
least eigenvalue of C: the normal of the plane through c that minimizes the
sum of squared distances to the k points. The surface variation
lambda0 / (lambda0 + lambda1 + lambda2) measures how far the points are from
a plane.

The neighbor search here is a brute force scan; a k-d tree gives the same
neighbors faster in low dimension. The eigenvectors come from the shared
helper cvla (cyclic Jacobi).
"""

from __future__ import annotations

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

from cvla import sym_eig

Vec3 = Tuple[float, float, float]


def k_nearest(points: Sequence[Sequence[float]], i: int, k: int) -> List[int]:
    """The indices of the k points nearest to point i, point i included."""
    p = points[i]
    return heapq.nsmallest(k, range(len(points)), key=lambda j: (math.dist(p, points[j]), j != i))


def covariance(pts: Sequence[Sequence[float]]) -> Tuple[Vec3, List[List[float]]]:
    """The centroid and the 3 x 3 covariance matrix (divisor len(pts))."""
    m = len(pts)
    c = tuple(sum(q[a] for q in pts) / m for a in range(3))  # @line L3
    cov = [[0.0] * 3 for _ in range(3)]
    for q in pts:  # @line L4
        d = (q[0] - c[0], q[1] - c[1], q[2] - c[2])
        for a in range(3):
            for b in range(3):
                cov[a][b] += d[a] * d[b] / m
    return c, cov


def plane_normal(pts: Sequence[Sequence[float]]) -> Tuple[Vec3, float, Vec3]:
    """Fit a plane to the points: (unit normal, surface variation, centroid)."""
    c, cov = covariance(pts)
    w, v = sym_eig(cov)  # @line L5
    n = (v[0][0], v[1][0], v[2][0])  # @line L6
    total = w[0] + w[1] + w[2]
    variation = max(w[0], 0.0) / total if total > 0 else 0.0  # @line L7
    return n, variation, c


def estimate_normals(points: Sequence[Sequence[float]], k: int,
                     viewpoint: Optional[Sequence[float]] = None) -> List[Tuple[Vec3, float]]:
    """For each point, (unit normal, surface variation).

    Preconditions: 3 <= k <= n. If a viewpoint is given, each normal is turned
    so that it points toward the viewpoint; otherwise its sign is arbitrary.
    """
    n = len(points)
    if not 3 <= k <= n:
        raise ValueError("need 3 <= k <= n")
    out: List[Tuple[Vec3, float]] = []
    for i in range(n):  # @line L1
        nbr = [points[j] for j in k_nearest(points, i, k)]  # @line L2
        normal, variation, _ = plane_normal(nbr)
        if viewpoint is not None:
            p = points[i]
            to_view = (viewpoint[0] - p[0], viewpoint[1] - p[1], viewpoint[2] - p[2])
            if normal[0] * to_view[0] + normal[1] * to_view[1] + normal[2] * to_view[2] < 0:  # @line L8
                normal = (-normal[0], -normal[1], -normal[2])
        out.append((normal, variation))
    return out  # @line L9
test_point_cloud_normal_estimation.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/point-cloud-normal-estimation/. The authors are listed in prov/J9D82K.jsonl.

import math
import random

import pytest

from cvla import svd
from point_cloud_normal_estimation import estimate_normals, k_nearest, plane_normal

EXAMPLE = [(-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (-1.0, 1.0, 0.0), (1.0, 1.0, 0.0), (0.0, 0.0, 0.5)]


def rotation(rng):
    """A rotation from a random unit quaternion (test only)."""
    w, x, y, z = (rng.gauss(0, 1) for _ in range(4))
    s = math.sqrt(w * w + x * x + y * y + z * z)
    w, x, y, z = w / s, x / s, y / s, z / s
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def apply(r, p):
    return tuple(sum(r[i][j] * p[j] for j in range(3)) for i in range(3))


def parallel(a, b, tol):
    """|a . b| close to 1 for unit vectors."""
    return abs(abs(sum(x * y for x, y in zip(a, b))) - 1.0) <= tol


def test_example() -> None:
    n, var, c = plane_normal(EXAMPLE)
    assert parallel(n, (0.0, 0.0, 1.0), 1e-12)
    assert abs(var - 0.04 / 1.64) < 1e-12
    assert all(abs(a - b) < 1e-15 for a, b in zip(c, (0.0, 0.0, 0.1)))


def test_plane_is_exact() -> None:
    rng = random.Random(21)
    for _ in range(10):
        r = rotation(rng)
        normal = apply(r, (0.0, 0.0, 1.0))
        pts = [apply(r, (rng.uniform(-1, 1), rng.uniform(-1, 1), 0.0)) for _ in range(30)]
        for m, var in estimate_normals(pts, 8):
            assert parallel(m, normal, 1e-9)
            assert var < 1e-12


def test_matches_svd_of_centered_points() -> None:
    rng = random.Random(22)
    for _ in range(20):
        pts = [tuple(rng.gauss(0, s) for s in (1.0, 0.7, 0.2)) for _ in range(rng.randint(3, 15))]
        n, var, c = plane_normal(pts)
        rows = [[q[a] - c[a] for a in range(3)] for q in pts]
        _, s, v = svd(rows)
        assert parallel(n, (v[0][2], v[1][2], v[2][2]), 1e-8)
        # the fitted plane minimizes the sum of squared distances
        cost = sum(sum(n[a] * row[a] for a in range(3)) ** 2 for row in rows)
        assert abs(cost - s[2] ** 2) < 1e-9
        for _ in range(20):
            u = [rng.gauss(0, 1) for _ in range(3)]
            lu = math.sqrt(sum(x * x for x in u))
            other = sum(sum(u[a] / lu * row[a] for a in range(3)) ** 2 for row in rows)
            assert cost <= other + 1e-12
        assert 0.0 <= var <= 1.0 / 3.0 + 1e-12


def test_sphere_normals_are_radial() -> None:
    rng = random.Random(23)
    pts = []
    for _ in range(400):
        u = [rng.gauss(0, 1) for _ in range(3)]
        lu = math.sqrt(sum(x * x for x in u))
        pts.append(tuple(2.0 * x / lu for x in u))
    for p, (m, var) in zip(pts, estimate_normals(pts, 10, viewpoint=(0.0, 0.0, 0.0))):
        radial = tuple(-x / 2.0 for x in p)  # toward the center, the viewpoint
        assert sum(a * b for a, b in zip(m, radial)) > 0.97
        assert var < 0.05


def test_rigid_motion_moves_normals() -> None:
    rng = random.Random(24)
    pts = [(x, y, 0.3 * x * x - 0.2 * y * y + rng.gauss(0, 0.01))
           for x in (-0.4, -0.2, 0.0, 0.2, 0.4) for y in (-0.4, -0.2, 0.0, 0.2, 0.4)]
    r = rotation(rng)
    moved = [tuple(a + b for a, b in zip(apply(r, p), (1.0, -2.0, 0.5))) for p in pts]
    before = estimate_normals(pts, 7)
    after = estimate_normals(moved, 7)
    for (m0, v0), (m1, v1) in zip(before, after):
        assert parallel(apply(r, m0), m1, 1e-8)
        assert abs(v0 - v1) < 1e-9


def test_neighbors_and_errors() -> None:
    pts = [(float(i), 0.0, 0.0) for i in range(6)]
    assert sorted(k_nearest(pts, 0, 3)) == [0, 1, 2]
    assert k_nearest(pts, 3, 1) == [3]
    with pytest.raises(ValueError):
        estimate_normals(pts, 2)
    with pytest.raises(ValueError):
        estimate_normals(pts[:3], 4)

History

Hoppe, DeRose, Duchamp, McDonald and Stuetzle (1992) needed an oriented tangent plane at each point to reconstruct a surface from unorganized points. They fitted the plane to the kk nearest neighbors through their centroid and took its normal as the eigenvector of the least eigenvalue of the covariance matrix; they then oriented the normals by propagation along a spanning tree. Pauly, Gross and Kobbelt (2002) used the same covariance analysis for the simplification of point-sampled surfaces and defined the surface variation as a measure of curvature. Mitra and Nguyen (2003) analyzed the error of the least squares normal under noise and derived a neighborhood size from the noise, the curvature and the density. The method is the normal estimator of the Point Cloud Library and of most point cloud software.

References

  1. Hugues Hoppe, Tony DeRose, Tom Duchamp, John McDonald and Werner Stuetzle, Surface reconstruction from unorganized points, Computer Graphics (Proceedings of SIGGRAPH 92) 26(2), 1992, 71-78, The tangent plane of each point from its k nearest neighbors: the centroid, the covariance matrix and the eigenvector of the least eigenvalue
  2. Mark Pauly, Markus Gross and Leif P. Kobbelt, Efficient simplification of point-sampled surfaces, IEEE Visualization 2002, 163-170, Section 2.1, Covariance Analysis (the covariance of the neighborhood, the normal as the eigenvector of the least eigenvalue, and the surface variation lambda0 / (lambda0 + lambda1 + lambda2))
  3. Niloy J. Mitra and An Nguyen, Estimating surface normals in noisy point cloud data, Symposium on Computational Geometry 2003, 322-328, The analysis of the error of the least squares normal as a function of the neighborhood size, the curvature, the sampling density and the noise

Where this leads

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