Algorithm Search⌘K

Algorithmadvanced

Variable-order surface fitting segmentation

Also called Besl-Jain segmentation.

Besl and Jain's region growing that seeds regions by curvature sign and grows them while fitting surfaces of rising polynomial order, until the fit error is too large.

Time
Θ(N w² + s N r + s (g + 4) N q²) worst
Space
Θ(N + w² + N q) extra
Where
N = the number of pixels; g = the largest number of growth passes for one seed; q = the number of polynomial coefficients, at most 15; r = the largest depth of a seed inside its block of one surface type; s = the number of seeds; w = the width of the curvature window
Properties
deterministicnot exactiterative
Origin
Paul J. Besl, Ramesh C. Jain, 1988

Variable-order surface fitting is an algorithm that segments a range image into regions, each fitted by a polynomial surface of the lowest order that matches the data within the noise. Besl and Jain (1988) introduced it. It has three stages. First, the mean curvature HH and the Gaussian curvature KK are estimated at every pixel, and the signs of HH and KK give each pixel one of eight surface types: peak, pit, ridge, valley, saddle ridge, saddle valley, flat and minimal. Second, a seed region is taken from the interior of a large block of pixels with one type. Third, the seed grows: a polynomial z=f(x,y)z = f(x, y) is fitted to the region by least squares, starting with a plane; while the fit error is too large, the order rises through the four orders that Besl and Jain use, planar, biquadratic, bicubic and biquartic; when the fit is good, the region takes in the neighboring pixels that lie close to the surface, and the fit is repeated, until the region stops growing. It solves the segmentation into primitives for range images, with polynomial surfaces as the primitives.

In plain words

A range image is a picture where each pixel holds a distance instead of a color. To cut it into faces, the method first looks at how the surface bends at each pixel: up in all directions, down in all directions, like a saddle, like a gutter, or not at all. Where many neighboring pixels bend the same way, it plants a small seed.

Then it tries to cover the seed with the simplest smooth sheet: a flat one first, then gently curved ones of more and more complex shape, up to a limit. As soon as one fits within the noise, the seed spreads to every connected pixel that lies on that sheet, and the sheet is refitted. It stops when nothing more fits. Then it plants the next seed in what is left.

The problem

Input. A range image: heights zijz_{ij} on a rectangular grid of pixels at (x,y)=(jh,ih)(x, y) = (j h, i h); an error bound τ\tau for the RMS error of a region; a band β≥τ\beta \ge \tau for the residual of a pixel that joins a region; thresholds εH\varepsilon_H and εK\varepsilon_K below which a curvature counts as zero.

Output. Disjoint regions of pixels, each 4-connected, with a polynomial ff of total degree d∈{1,2,3,4}d \in \{1, 2, 3, 4\} for each region, whose RMS error on the region is at most τ\tau. Pixels may stay unlabeled. Besl and Jain call the four orders planar, biquadratic, bicubic and biquartic, although the polynomials are of total degree 11 to 44, with 33, 66, 1010 and 1515 coefficients.

The algorithm

  1. VARIABLE-ORDER-SEGMENTATION(z, h, τ, β)
  2. 1type(p) ← (sign H(p), sign K(p)) at each pixel p, from a local quadratic fit
  3. 2while some 5 by 5 block of unblocked pixels has one type: S ← the deepest such block; block S
  4. 3R ← S; d ← 1
  5. 4f ← the least-squares polynomial of total degree d on R; e ← its RMS error on R
  6. 5if e > τ: if d = 4 reject S, else d ← d + 1 and go to L4
  7. 6R' ← R and the unused pixels connected to R through pixels q with |z(q) − f(q)| ≤ β
  8. 7if R' = R: accept (R, f, d), mark R used and blocked; else R ← R' and go to L4
  9. 8return the accepted regions

Line L1. On a window of 5×55 \times 5 pixels the code fits z≈c0+c1u+c2v+c3u2+c4uv+c5v2z \approx c_0 + c_1 u + c_2 v + c_3 u^2 + c_4 u v + c_5 v^2; since the window has the same shape everywhere, each coefficient is one fixed linear filter. With fx=c1f_x = c_1, fy=c2f_y = c_2, fxx=2c3f_{xx} = 2 c_3, fxy=c4f_{xy} = c_4, fyy=2c5f_{yy} = 2 c_5 and g=1+fx2+fy2g = 1 + f_x^2 + f_y^2, the curvatures of the graph with the upward normal are

H=(1+fy2)fxx−2fxfyfxy+(1+fx2)fyy2g3/2,K=fxxfyy−fxy2g2,H = \frac{(1 + f_y^2) f_{xx} - 2 f_x f_y f_{xy} + (1 + f_x^2) f_{yy}}{2 g^{3/2}}, \qquad K = \frac{f_{xx} f_{yy} - f_{xy}^2}{g^2} ,

from the fundamental forms of the graph. A cup z=x2+y2z = x^2 + y^2 has H>0H > 0 and K>0K > 0, a pit. Each sign is 00 when the value is within its threshold. The pair (sign HH = 0, sign KK > 0) cannot occur for exact curvatures, since H2≥KH^2 \ge K.

Line L2. The depth of a pixel is the largest kk such that the block of side 2k−12k - 1 around it has one type and no blocked pixel; the code computes it by repeated erosion and takes the 5×55 \times 5 block around the deepest pixel. Besl and Jain also erode the largest regions of one type to get seeds. A seed needs 2525 pixels because Lemma 1 of the proof shows that a 5×55 \times 5 grid determines a polynomial of total degree 44, and a 4×44 \times 4 grid does not.

Lines L4 and L5. The fit uses the monomials uavbu^a v^b with a+b≤da + b \le d in the variables shifted to the centroid of the region and scaled to [−1,1][-1, 1], and modified Gram-Schmidt done twice, which is stable for the 1515 columns of the quartic. The order rises only when the current order cannot fit the region within τ\tau.

Lines L6 and L7. The growth is a breadth-first search from the region through unused pixels within the band. The new region contains the old one, so the loop either grows or stops. The code keeps the pixels of a region even when a later fit moves away from them; their residuals then count in the RMS error, and a larger error raises the order.

Example

A 24×2424 \times 24 image with h=1/23h = 1/23 has four quadrants of 144144 pixels, with steps of about 33 in height between them and four polynomials:

0.3x−0.2y+0.1,x2+y2+0.5xy+3,x2+y2+0.4x3−0.2xy2+6,0.3 x - 0.2 y + 0.1, \quad x^2 + y^2 + 0.5 x y + 3, \quad x^2 + y^2 + 0.4 x^3 - 0.2 x y^2 + 6,
x2+y2+0.3x4+0.2x2y2−0.1y3+9.x^2 + y^2 + 0.3 x^4 + 0.2 x^2 y^2 - 0.1 y^3 + 9 .

The sign map is flat in the plane and pit in the other three quadrants, with other types along the steps, where the window crosses two quadrants. The four seeds, one per quadrant, give these RMS errors on their 2525 pixels, with τ=10−9\tau = 10^{-9} and β=10−7\beta = 10^{-7}:

quadrant order 1 order 2 order 3 order 4 result
plane 2×10−172 \times 10^{-17} 144 pixels, order 1
quadratic 0.01940.0194 5×10−165 \times 10^{-16} 144 pixels, order 2
cubic 0.02420.0242 0.0005440.000544 9×10−169 \times 10^{-16} 144 pixels, order 3
quartic 0.07420.0742 0.002370.00237 3.9×10−53.9 \times 10^{-5} 3.4×10−153.4 \times 10^{-15} 144 pixels, order 4

Each seed reaches its true order on its 2525 pixels, grows in one pass to the whole quadrant, and stops; the largest residual of a final fit is 3.6×10−153.6 \times 10^{-15}.

With noise. On the same quadrants over [0,2]2[0, 2]^2 with Gaussian noise σ=10−3\sigma = 10^{-3}, τ=2σ\tau = 2 \sigma, β=6σ\beta = 6 \sigma and curvature thresholds 0.10.1, the code found four regions, each inside one quadrant, with 144144, 144144, 144144 and 139139 pixels and orders 11, 22, 33 and 33: the quartic quadrant was fitted within the noise by a cubic. At σ=10−2\sigma = 10^{-2} the plane got no seed, because the noise made its curvature signs vary from pixel to pixel. These are measurements with the code of this page.

Correctness

The correctness file proves:

  • Unisolvence. A polynomial of degree at most kk in each variable that vanishes on a (k+1)×(k+1)(k + 1) \times (k + 1) grid is zero. So every region that contains a 5×55 \times 5 seed determines a unique least-squares polynomial of each order, and the fits of lines L4 never fail.
  • Termination. Each pass of lines L4 to L7 raises the order, rejects, accepts, or adds a pixel, and each seed blocks at least 2525 new pixels, so the algorithm stops after at most N/25N/25 seeds and N+4N + 4 passes per seed.
  • Exact recovery of one patch. Let a seed lie in a 4-connected set AA of unused pixels where z=gz = g for a polynomial gg of total degree exactly d∗∈{1,…,4}d^\ast \in \{1, \dots, 4\}, let τ\tau be smaller than the RMS errors of the lower orders on the seed, which are all positive, and let every unused pixel next to AA but outside it differ from gg by more than β\beta. Then the growth returns exactly AA, the polynomial gg and the order d∗d^\ast, in exact arithmetic.

The tests check the last statement on 2020 random polynomial patches, five of each order from 11 to 44, and on the four quadrants; all 2020 patches and all four quadrants are recovered with the true order and the whole region. Not proved: that the curvature signs give a seed in every patch, and anything about noisy data, where τ\tau and β\beta trade missed pixels against wrong ones.

Proof: A 5 by 5 seed determines every fit, the segmentation stops, and the growth from a seed recovers a noise-free polynomial patch with its true orderfull

Setup. Pixels p=(i,j)p = (i, j) sit at (x,y)=(jh,ih)(x, y) = (j h, i h) with height z(p)z(p). PdP_d is the space of real polynomials in x,yx, y of total degree at most dd. For a set RR of pixels and d≤4d \le 4, a least-squares polynomial of order dd on RR is an f∈Pdf \in P_d that minimizes ∑p∈R(z(p)−f(p))2\sum_{p \in R} (z(p) - f(p))^2, and ed(R)e_d(R) is the RMS error of such an ff. A seed is a 5×55 \times 5 block of pixels. Lines L3 to L7 of the algorithm are the growth from one seed SS; the set UU of used pixels does not change during it. All statements are in exact arithmetic.

Lemma 1 (unisolvence on a grid). Let XX and YY be sets of k+1k + 1 distinct numbers each. A polynomial qq of degree at most kk in xx and at most kk in yy that vanishes on X×YX \times Y is zero.

Proof. Write q(x,y)=∑a=0kca(y)xaq(x, y) = \sum_{a=0}^{k} c_a(y) x^a with polynomials cac_a of degree at most kk. For each y0∈Yy_0 \in Y, q(⋅,y0)q(\cdot, y_0) has degree at most kk and k+1k + 1 distinct roots XX, so all its coefficients ca(y0)c_a(y_0) vanish. So each cac_a has the k+1k + 1 distinct roots YY, and ca=0c_a = 0. □\square

Corollary 1 (the fits exist and are unique). If RR contains a seed, then for every d≤4d \le 4 the least-squares polynomial of order dd on RR is unique.

Proof. The pixels of a seed have 55 distinct values of xx and 55 distinct values of yy. A polynomial of total degree at most 44 has degree at most 44 in each variable, so by Lemma 1 the only f∈Pdf \in P_d that vanishes on the seed, and hence on RR, is 00. So the map from the coefficients to the values on RR is injective, the design matrix has full column rank, and the least-squares solution is unique. □\square

Lemma 1 is sharp for the seed size: on a 4×44 \times 4 grid with xx values x0,…,x3x_0, \dots, x_3, the quartic (x−x0)(x−x1)(x−x2)(x−x3)(x - x_0)(x - x_1)(x - x_2)(x - x_3) vanishes, so the quartic fit is not unique.

Theorem 1 (termination). The growth from a seed stops after at most ∣Rfinal∣−25+4|R_{\text{final}}| - 25 + 4 passes of lines L4 to L7, and the whole algorithm stops after at most N/25N / 25 seeds, where NN is the number of pixels.

Proof. Every region during the growth contains its seed, so by Corollary 1 line L4 is always defined. Each pass does one of four things: line L5 raises dd, which happens at most 33 times since d≤4d \le 4; line L5 rejects; line L7 accepts; or line L7 replaces RR by R′⊇RR' \supseteq R with R′≠RR' \ne R, so RR gains at least one pixel. A region has at most NN pixels, so the number of growth passes is bounded, and the growth ends with a rejection or an acceptance. Line L2 picks a seed of 2525 pixels that are not blocked and then blocks them, so the blocked set grows by 2525 pixels per seed, and there are at most N/25N / 25 seeds. □\square

Lemma 2 (lower orders leave an error). Let gg have total degree exactly d∗≤4d^\ast \le 4, and let z=gz = g on a seed SS. Then ed(S)>0e_d(S) > 0 for every d<d∗d < d^\ast.

Proof. Suppose ed(S)=0e_d(S) = 0 for some d<d∗d < d^\ast. Then some f∈Pdf \in P_d agrees with gg on SS, so g−fg - f vanishes on the 5×55 \times 5 grid SS. It has degree at most 44 in each variable, so g−f=0g - f = 0 by Lemma 1. But g−fg - f contains the nonzero terms of degree d∗>dd^\ast > d of gg, a contradiction. □\square

Theorem 2 (exact recovery of a polynomial patch). Let AA be a 4-connected set of pixels with A∩U=∅A \cap U = \emptyset, let gg be a polynomial of total degree exactly d∗∈{1,2,3,4}d^\ast \in \{1, 2, 3, 4\} with z=gz = g on AA, and let the seed SS lie in AA. Assume

  1. 0≤τ<ed(S)0 \le \tau < e_d(S) for every d<d∗d < d^\ast (these numbers are positive by Lemma 2), and β≥0\beta \ge 0;
  2. every pixel q∉A∪Uq \notin A \cup U that is a 4-neighbor of a pixel of AA has ∣z(q)−g(q)∣>β\lvert z(q) - g(q) \rvert > \beta.

Then the growth from SS accepts the region AA with the polynomial gg and the order d∗d^\ast.

Proof. Line L3 sets R=SR = S and d=1d = 1. For d<d∗d < d^\ast, line L4 gives the error ed(S)>τe_d(S) > \tau by assumption 1, and since d<d∗≤4d < d^\ast \le 4 line L5 raises the order. So the order reaches d∗d^\ast with R=SR = S.

Now take any RR with S⊆R⊆AS \subseteq R \subseteq A and d=d∗d = d^\ast. Since g∈Pd∗g \in P_{d^\ast} fits RR with zero error, it is a least-squares polynomial, and by Corollary 1 it is the only one; so line L4 gives f=gf = g and e=0≤τe = 0 \le \tau, and line L5 passes to line L6. The search of line L6 starts from RR and moves through unused pixels qq with ∣z(q)−g(q)∣≤β\lvert z(q) - g(q) \rvert \le \beta.

It reaches every pixel of AA: these are unused, have residual 0≤β0 \le \beta, and AA is 4-connected and contains RR.

It reaches no pixel outside AA: suppose it does, and let qq be the first such pixel reached. The pixel from which qq was reached is in RR or was reached earlier, so it is in AA, and qq is a 4-neighbor of AA, unused and outside AA. Assumption 2 gives ∣z(q)−g(q)∣>β\lvert z(q) - g(q) \rvert > \beta, so the search does not enter qq, a contradiction.

So R′=AR' = A. If R=AR = A, line L7 accepts (A,g,d∗)(A, g, d^\ast). Otherwise line L7 sets R=AR = A, and the next pass, by the same argument with R=AR = A, gives f=gf = g, e=0e = 0 and R′=A=RR' = A = R, and accepts (A,g,d∗)(A, g, d^\ast). □\square

What is not proved. Theorem 2 starts from a seed inside the patch. Whether line L2 finds such a seed depends on the sign map, which is computed from a local quadratic fit and is exact only where the surface is quadratic on the whole window; this is not proved here. Nothing is proved for noisy data: then the errors of all orders are positive, and the result depends on τ\tau, β\beta and the curvature thresholds. With floating point the fits have rounding errors of about 10−1510^{-15} times the size of the data, so the code uses a small positive τ\tau in place of 00. ■\blacksquare

Complexity

The sign map costs Θ(w2)\Theta(w^2) per pixel, Θ(Nw2)\Theta(N w^2) in all. One seed search erodes the type map up to rr times, Θ(Nr)\Theta(N r). A fit on a region of nn pixels with qq coefficients costs Θ(nq2)\Theta(n q^2), and a growth pass Θ(nq)\Theta(n q) for the residuals; each seed has at most 33 order raises and gg growth passes. With ss seeds and n≤Nn \le N this gives the bound in the front matter on the real RAM. In practice the regions are disjoint, and the total fitting work is closer to Θ((g+4)Nq2)\Theta((g + 4) N q^2).

Properties

  • Lowest order first. A region gets the simplest of the four surfaces that fits within τ\tau, which avoids fitting noise with a quartic where a plane will do.
  • Data driven. No list of shapes is given; the orders and the regions come from the data.
  • Viewpoint dependent. The polynomials are graphs z=f(x,y)z = f(x, y) over the image plane, so a surface that is vertical in the view, or that folds over, cannot be one region. The curvature signs themselves do not depend on the viewpoint.
  • Not invariant fits. A plane or a cylinder that is rotated in space gives a different polynomial, and a cylinder or a sphere is not a polynomial graph at all; it is fitted only approximately by a quartic, or broken into several regions.
  • Greedy. The seeds are processed one at a time, and the first region takes the disputed pixels.

Variants and improvements

  • Region merging and boundary refinement. Besl and Jain merge adjacent regions whose surfaces agree along the shared boundary, and refine the boundaries between regions; the code here does neither.
  • Smoothing first. Besl and Jain smooth the image before they estimate HH and KK, since second derivatives amplify noise; this would help the noisy example.
  • Other surface families. Later face-based methods for reverse engineering grow regions with the primitives of CAD, planes, spheres, cylinders, cones and tori, fitted by geometric fitting, or with B-spline patches.
  • Point clouds and meshes. On unordered points, the grid neighbors are replaced by a neighbor graph, the curvature comes from curvature tensor estimation, and the fit must use the orthogonal distance instead of the height.
  • Other seeds. Seeds can come from RANSAC candidates or from slippage analysis instead of curvature signs.

When to use it

Use variable-order fitting to segment range images or height fields of smooth objects into pieces described by low-order polynomials, for example for recognition or for a first model of the surface. For CAD parts with planes, cylinders and cones in arbitrary directions, methods that fit the primitives themselves, such as efficient RANSAC, give regions that match the design better. In reverse engineering it is a classic face-based method, and its seed and grow scheme is the base of many later ones.

Pitfalls

  • Thresholds. τ\tau and β\beta must match the noise. Too small, and the regions stop early or the seeds are rejected; too large, and a region crosses a soft edge into the next face.
  • Growth stops before the order rises. A region whose surface is of order 44 can stop growing at order 33 when the cubic fits the part it has grown to within τ\tau and no neighbor lies within β\beta, as in the noisy example.
  • Thin regions. On a strip of 55 columns any function of xx alone equals a quartic in xx, so a quintic surface can be cut into strips that each pass the test. The tests show this.
  • Creases. At an edge where two surfaces meet without a step, the pixels along the edge fit both; the first region takes them.
  • Curvature from noise. The sign map uses second derivatives and is the most noise-sensitive part. Without smoothing, flat regions fall apart into random types and get no seed.

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.

re1lin.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the re1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra for the re1 fitting pages.

Vectors are tuples or lists of numbers, matrices are lists of rows. The
elimination routines work with int, Fraction or float entries: with Fraction
they are exact. The Jacobi routine is float only. The helper holds no
fitting algorithm of any page.
"""

from fractions import Fraction
from math import atan2, cos, sin, sqrt
from typing import List, Optional, Sequence, Tuple

Vec = Sequence
Mat = List[List]


# ---- vectors ----


def dot(a: Vec, b: Vec):
    return sum(x * y for x, y in zip(a, b))


def add(a: Vec, b: Vec) -> tuple:
    return tuple(x + y for x, y in zip(a, b))


def sub(a: Vec, b: Vec) -> tuple:
    return tuple(x - y for x, y in zip(a, b))


def scale(s, a: Vec) -> tuple:
    return tuple(s * x for x in a)


def norm(a: Vec) -> float:
    return sqrt(float(dot(a, a)))


def cross(a: Vec, b: Vec) -> tuple:
    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])


# ---- matrices ----


def zeros(n: int, m: int, z=0) -> Mat:
    return [[z] * m for _ in range(n)]


def transpose(a: Mat) -> Mat:
    return [list(r) for r in zip(*a)]


def mat_vec(a: Mat, x: Vec) -> list:
    return [dot(r, x) for r in a]


def mat_mul(a: Mat, b: Mat) -> Mat:
    bt = transpose(b)
    return [[dot(r, c) for c in bt] for r in a]


def gram(rows: Sequence[Vec]) -> Mat:
    """The matrix sum over the rows u of u u^T."""
    n = len(rows[0])
    g = zeros(n, n)
    for u in rows:
        for i in range(n):
            if u[i] == 0:
                continue
            for j in range(n):
                g[i][j] += u[i] * u[j]
    return g


# ---- elimination (exact with Fraction) ----


def solve(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
    """Solve a x = b for a square a by Gaussian elimination with partial pivoting.

    Returns None when a pivot has absolute value at most tol (singular
    matrix). With Fraction entries and tol = 0 the answer is exact.
    """
    n = len(a)
    m = [list(a[i]) + [b[i]] for i in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[p][c]) <= tol:
            return None
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0:
                for k in range(c, n + 1):
                    m[r][k] -= f * m[c][k]
    x = [0] * n
    for r in range(n - 1, -1, -1):
        s = m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))
        x[r] = s / m[r][r]
    return x


def lstsq(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
    """Least squares solution of a x = b by the normal equations (a^T a) x = a^T b."""
    at = transpose(a)
    return solve(mat_mul(at, a), mat_vec(at, b), tol)


def nullspace(a: Mat) -> List[list]:
    """A basis of the null space of a, by reduced row echelon form. Exact for Fraction entries."""
    m = [[Fraction(x) for x in r] for r in a]
    rows, cols = len(m), len(m[0])
    piv = []
    r = 0
    for c in range(cols):
        p = next((i for i in range(r, rows) if m[i][c] != 0), None)
        if p is None:
            continue
        m[r], m[p] = m[p], m[r]
        inv = 1 / m[r][c]
        m[r] = [x * inv for x in m[r]]
        for i in range(rows):
            if i != r and m[i][c] != 0:
                f = m[i][c]
                m[i] = [x - f * y for x, y in zip(m[i], m[r])]
        piv.append(c)
        r += 1
        if r == rows:
            break
    free = [c for c in range(cols) if c not in piv]
    basis = []
    for f in free:
        v = [Fraction(0)] * cols
        v[f] = Fraction(1)
        for i, c in enumerate(piv):
            v[c] = -m[i][f]
        basis.append(v)
    return basis


def rank(a: Mat) -> int:
    return len(a[0]) - len(nullspace(a))


# ---- symmetric matrices (float) ----


def cholesky(a: Mat, rtol: float = 0.0) -> Mat:
    """Lower triangular l with l l^T = a, for a symmetric positive definite a.

    Raises ValueError when a pivot is at most rtol times the largest diagonal entry.
    """
    n = len(a)
    l = zeros(n, n, 0.0)
    big = max(abs(float(a[i][i])) for i in range(n))
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
            if i == j:
                if s <= rtol * big:
                    raise ValueError("matrix is not positive definite")
                l[i][i] = sqrt(s)
            else:
                l[i][j] = s / l[j][j]
    return l


def lower_solve(l: Mat, b: Vec) -> list:
    x = []
    for i in range(len(l)):
        x.append((b[i] - sum(l[i][k] * x[k] for k in range(i))) / l[i][i])
    return x


def upper_solve_t(l: Mat, b: Vec) -> list:
    """Solve l^T x = b for a lower triangular l."""
    n = len(l)
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (b[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
    return x


def jacobi_eigen(a: Mat, sweeps: int = 100, eps: float = 1e-15) -> Tuple[list, Mat]:
    """Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations.

    Returns (values, vectors) with the values in ascending order and
    vectors[k] the unit eigenvector of values[k].
    """
    n = len(a)
    s = [[float(x) for x in r] for r in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(s[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off <= eps * eps * max(1.0, sum(s[i][i] ** 2 for i in range(n))):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if s[p][q] == 0.0:
                    continue
                th = 0.5 * atan2(2 * s[p][q], s[q][q] - s[p][p])
                c, sn = cos(th), sin(th)
                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
                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
    order = sorted(range(n), key=lambda i: s[i][i])
    return [s[i][i] for i in order], [[v[k][i] for k in range(n)] for i in order]
variable_order_surface_fitting.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variable-order-surface-fitting/. The authors are listed in prov/710BVP.jsonl.

"""Variable-order surface fitting segmentation of a range image, after Besl and Jain.

A range image is a grid Z[i][j] of heights z over the points x = j h, y = i h.
The method has three parts:

1. The HK sign map: at every pixel the mean curvature H and the Gaussian
   curvature K of the graph z = f(x, y) are estimated by a local quadratic fit,
   and the pixel gets one of the eight surface types of (sign H, sign K).
2. Seeds: a seed is a 5 by 5 block of unused pixels of one surface type, the
   one deepest inside its block of equal types.
3. Variable-order growth: a polynomial of total degree d = 1 (planar),
   2 (biquadratic), 3 (bicubic) or 4 (biquartic) is fitted to the region by
   least squares. If its RMS error is above tol, the order goes up; if the
   order is already 4, the seed is rejected. Otherwise the region grows to all
   pixels connected to it through unused pixels whose residual is at most band,
   and the fit is repeated, until the region stops growing.

There is no merging of regions and no refinement of boundaries here.
"""

from collections import deque
from math import sqrt
from typing import List, Optional, Sequence, Set, Tuple

from re1lin import solve

Pixel = Tuple[int, int]
ORDER_NAMES = {1: "planar", 2: "biquadratic", 3: "bicubic", 4: "biquartic"}

# surface types of Besl and Jain by (sign of H, sign of K); H > 0 for a cup z = x^2 + y^2
SURFACE_TYPES = {(-1, 1): "peak", (-1, 0): "ridge", (-1, -1): "saddle ridge", (0, 0): "flat",
                 (0, -1): "minimal", (1, 1): "pit", (1, 0): "valley", (1, -1): "saddle valley"}


def monomials(d: int) -> List[Tuple[int, int]]:
    """The exponents (a, b) of x^a y^b with a + b <= d: (d + 1)(d + 2) / 2 of them."""
    return [(t - b, b) for t in range(d + 1) for b in range(t + 1)]


class Poly:
    """A bivariate polynomial in the shifted and scaled variables u = (x - cx) / s, v = (y - cy) / s."""

    def __init__(self, d: int, coef: Sequence[float], cx: float, cy: float, s: float):
        self.d, self.coef, self.cx, self.cy, self.s = d, list(coef), cx, cy, s
        self.mons = monomials(d)

    def __call__(self, x: float, y: float) -> float:
        u, v = (x - self.cx) / self.s, (y - self.cy) / self.s
        return sum(c * u ** a * v ** b for c, (a, b) in zip(self.coef, self.mons))


def fit_polynomial(pts: Sequence[Tuple[float, float, float]], d: int) -> Tuple[Poly, float]:
    """Least-squares polynomial of total degree d through the points (x, y, z), and its RMS error.

    Uses modified Gram-Schmidt, done twice, on the shifted and scaled monomials.
    Raises ValueError when the points do not determine the polynomial.
    Cost: Theta(n q^2) for n points and q = (d + 1)(d + 2) / 2 unknowns.
    """
    n = len(pts)
    cx = sum(p[0] for p in pts) / n
    cy = sum(p[1] for p in pts) / n
    s = max(max(abs(p[0] - cx), abs(p[1] - cy)) for p in pts) or 1.0
    mons = monomials(d)
    q = len(mons)
    if n < q:
        raise ValueError("too few points for this order")
    uv = [((p[0] - cx) / s, (p[1] - cy) / s) for p in pts]
    cols = [[u ** a * v ** b for u, v in uv] for a, b in mons]
    R = [[0.0] * q for _ in range(q)]
    for k in range(q):
        size = sqrt(sum(x * x for x in cols[k]))
        for _ in range(2):
            for i in range(k):
                r = sum(a * b for a, b in zip(cols[i], cols[k]))
                R[i][k] += r
                cols[k] = [b - r * a for a, b in zip(cols[i], cols[k])]
        nk = sqrt(sum(x * x for x in cols[k]))
        if nk <= 1e-10 * size:
            raise ValueError("the points do not determine a polynomial of this order")
        R[k][k] = nk
        cols[k] = [x / nk for x in cols[k]]
    z = [p[2] for p in pts]
    qz = [sum(a * b for a, b in zip(c, z)) for c in cols]
    coef = [0.0] * q
    for k in range(q - 1, -1, -1):
        coef[k] = (qz[k] - sum(R[k][j] * coef[j] for j in range(k + 1, q))) / R[k][k]
    f = Poly(d, coef, cx, cy, s)
    rms = sqrt(sum((f(x, y) - zz) ** 2 for x, y, zz in pts) / n)
    return f, rms


# ---- the HK sign map ----


def curvatures(fx: float, fy: float, fxx: float, fxy: float, fyy: float) -> Tuple[float, float]:
    """Mean and Gaussian curvature of the graph z = f(x, y), with the normal pointing up."""
    g = 1 + fx * fx + fy * fy
    H = ((1 + fy * fy) * fxx - 2 * fx * fy * fxy + (1 + fx * fx) * fyy) / (2 * g ** 1.5)
    K = (fxx * fyy - fxy * fxy) / (g * g)
    return H, K


def hk_map(Z: Sequence[Sequence[float]], h: float, eps_h: float, eps_k: float, half: int = 2
           ) -> List[List[Optional[str]]]:
    """Surface type of every pixel from a local quadratic fit on a (2 half + 1)^2 window; None near the border."""
    rows, cols = len(Z), len(Z[0])
    offs = [(di, dj) for di in range(-half, half + 1) for dj in range(-half, half + 1)]
    # the quadratic fit on the window is one fixed linear filter per coefficient
    basis = [(1.0, dj * h, di * h, (dj * h) ** 2, dj * h * di * h, (di * h) ** 2) for di, dj in offs]
    A =[[sum(b[r] * b[c] for b in basis) for c in range(6)] for r in range(6)]
    filters = []
    for k in range(6):
        e = [1.0 if r == k else 0.0 for r in range(6)]
        w = solve(A, e)                                     # row k of A^{-1}
        filters.append([sum(w[r] * b[r] for r in range(6)) for b in basis])
    types: List[List[Optional[str]]] = [[None] * cols for _ in range(rows)]
    for i in range(half, rows - half):
        for j in range(half, cols - half):
            vals = [Z[i + di][j + dj] for di, dj in offs]
            c = [sum(f * z for f, z in zip(filt, vals)) for filt in filters]
            H, K = curvatures(c[1], c[2], 2 * c[3], c[4], 2 * c[5])
            sh = 0 if abs(H) <= eps_h else (1 if H > 0 else -1)
            sk = 0 if abs(K) <= eps_k else (1 if K > 0 else -1)
            types[i][j] = SURFACE_TYPES.get((sh, sk))        # (0, +1) cannot occur exactly; it gets None
    return types


# ---- seeds and growth ----


def pick_seed(types: List[List[Optional[str]]], blocked: Set[Pixel], radius: int = 2) -> Optional[Set[Pixel]]:
    """The (2 radius + 1)^2 block around the pixel deepest inside a block of one surface type."""
    rows, cols = len(types), len(types[0])

    def ok(i, j):
        return types[i][j] is not None and (i, j) not in blocked

    depth = [[1 if ok(i, j) else 0 for j in range(cols)] for i in range(rows)]
    level = 1
    while True:
        nxt = [[0] * cols for _ in range(rows)]
        changed = False
        for i in range(1, rows - 1):
            for j in range(1, cols - 1):
                if depth[i][j] >= level and all(depth[i + a][j + b] >= level and types[i + a][j + b] == types[i][j]
                                                for a in (-1, 0, 1) for b in (-1, 0, 1)):
                    nxt[i][j] = 1
                    changed = True
        if not changed:
            break
        for i in range(rows):
            for j in range(cols):
                if nxt[i][j]:
                    depth[i][j] = level + 1
        level += 1
    best = max(((depth[i][j], -i, -j) for i in range(rows) for j in range(cols)), default=(0, 0, 0))
    if best[0] < radius + 1:
        return None
    ci, cj = -best[1], -best[2]
    return {(ci + a, cj + b) for a in range(-radius, radius + 1) for b in range(-radius, radius + 1)}


def grow_region(Z: Sequence[Sequence[float]], h: float, seed: Set[Pixel], used: Set[Pixel], tol: float,
                band: float, max_order: int = 4) -> Optional[Tuple[Set[Pixel], Poly, int]]:
    """Variable-order region growing from a seed: (region, polynomial, order), or None if no order fits."""
    rows, cols = len(Z), len(Z[0])
    R, d = set(seed), 1                                                        # @line L3
    while True:
        f, rms = fit_polynomial([(j * h, i * h, Z[i][j]) for i, j in sorted(R)], d)  # @line L4
        if rms > tol:
            if d == max_order:
                return None
            d += 1                                                             # @line L5
            continue
        grown, queue = set(R), deque(R)                                        # @line L6
        while queue:
            i, j = queue.popleft()
            for a, b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
                if 0 <= a < rows and 0 <= b < cols and (a, b) not in grown and (a, b) not in used \
                        and abs(Z[a][b] - f(b * h, a * h)) <= band:
                    grown.add((a, b))
                    queue.append((a, b))
        if len(grown) == len(R):                                               # @line L7
            return R, f, d
        R = grown


def variable_order_segmentation(Z: Sequence[Sequence[float]], h: float, tol: float, band: float,
                                eps_h: float = 1e-6, eps_k: float = 1e-6, max_order: int = 4
                                ) -> List[Tuple[Set[Pixel], Poly, int]]:
    """Segment a range image into regions, each with a polynomial of order 1 to max_order.

    Precondition: Z is a rectangular grid of heights with spacing h; tol is the
    largest RMS error accepted for a region and band >= tol the largest residual
    of a pixel added to a region. Cost: Theta(N w^2) for the HK map on N pixels
    with a w by w window, plus Theta(N r) per seed search with r the largest
    depth, plus Theta(|R| q^2) per fit with q <= 15 unknowns.
    """
    types = hk_map(Z, h, eps_h, eps_k)                                         # @line L1
    used: Set[Pixel] = set()
    blocked: Set[Pixel] = set()
    regions = []
    while True:
        seed = pick_seed(types, blocked)                                       # @line L2
        if seed is None:
            break
        blocked |= seed
        result = grow_region(Z, h, seed, used, tol, band, max_order)
        if result is not None:
            region = result[0]
            regions.append(result)
            used |= region
            blocked |= region
    return regions                                                             # @line L8
test_variable_order_surface_fitting.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variable-order-surface-fitting/. The authors are listed in prov/710BVP.jsonl.

import random
import unittest
from fractions import Fraction

from re1lin import solve
from variable_order_surface_fitting import (curvatures, fit_polynomial, grow_region, hk_map, monomials,
                                            variable_order_segmentation)

N = 24
H2 = 2.0 / (N - 1)          # pixel spacing for the domain [0, 2] x [0, 2]

QUADRANT_POLYS = [
    (1, lambda x, y: 0.3 * x - 0.2 * y + 0.1),
    (2, lambda x, y: x * x + y * y + 0.5 * x * y + 3),
    (3, lambda x, y: x * x + y * y + 0.4 * x ** 3 - 0.2 * x * y * y + 6),
    (4, lambda x, y: x * x + y * y + 0.3 * x ** 4 + 0.2 * x * x * y * y - 0.1 * y ** 3 + 9),
]


def quadrant(i, j, n=N):
    return (1 if j >= n // 2 else 0) + (2 if i >= n // 2 else 0)


def quadrant_image(h, noise=0.0, rng=None):
    return [[QUADRANT_POLYS[quadrant(i, j)][1](j * h, i * h) + (rng.gauss(0, noise) if noise else 0.0)
             for j in range(N)] for i in range(N)]


def random_poly(rng, d):
    """x^2 + y^2 plus small random terms of total degree <= d, with a nonzero term of degree d."""
    coef = {m: rng.uniform(-0.05, 0.05) for m in monomials(d)}
    coef[(d, 0)] = rng.choice((-1, 1)) * rng.uniform(0.03, 0.05)
    if d >= 2:
        coef[(2, 0)] += 1.0
        coef[(0, 2)] += 1.0

    def g(x, y):
        return sum(c * x ** a * y ** b for (a, b), c in coef.items())
    return g


class TestWorkedExample(unittest.TestCase):
    def test_four_quadrants_get_their_true_orders(self):
        h = 1.0 / (N - 1)
        Z = quadrant_image(h)
        regions = variable_order_segmentation(Z, h, tol=1e-9, band=1e-7)
        self.assertEqual(len(regions), 4)
        found = {}
        for R, f, d in regions:
            quads = {quadrant(i, j) for i, j in R}
            self.assertEqual(len(quads), 1)
            q = quads.pop()
            self.assertEqual(len(R), 144)                       # the whole quadrant
            found[q] = d
            self.assertLess(max(abs(f(j * h, i * h) - Z[i][j]) for i, j in R), 1e-10)
        self.assertEqual(found, {0: 1, 1: 2, 2: 3, 3: 4})


class TestStopsAtTrueOrder(unittest.TestCase):
    def test_random_polynomial_patches(self):
        rng = random.Random(7)
        exact = trials = 0
        for d in (1, 2, 3, 4):
            for _ in range(5):
                g = random_poly(rng, d)
                Z = [[g(j * H2, i * H2) for j in range(N)] for i in range(N)]
                regions = variable_order_segmentation(Z, H2, tol=1e-9, band=1e-7)
                trials += 1
                self.assertEqual(len(regions), 1)
                R, f, order = regions[0]
                self.assertEqual(order, d)
                self.assertEqual(len(R), N * N)
                self.assertLess(max(abs(f(j * H2, i * H2) - Z[i][j]) for i, j in R), 1e-10)
                exact += 1
        self.assertEqual(exact, trials)                          # proved: every trial is exact

    def test_lower_orders_leave_a_positive_error_on_the_seed(self):
        rng = random.Random(8)
        for d in (2, 3, 4):
            g = random_poly(rng, d)
            seed = [(j * H2, i * H2, g(j * H2, i * H2)) for i in range(5) for j in range(5)]
            for lower in range(1, d):
                self.assertGreater(fit_polynomial(seed, lower)[1], 1e-7)
            self.assertLess(fit_polynomial(seed, d)[1], 1e-12)


class TestFitAgainstExactOracle(unittest.TestCase):
    def test_least_squares_matches_exact_normal_equations(self):
        rng = random.Random(9)
        for d in (1, 2, 3, 4):
            pts = [(Fraction(rng.randint(-20, 20), 10), Fraction(rng.randint(-20, 20), 10),
                    Fraction(rng.randint(-100, 100), 50)) for _ in range(30)]
            mons = monomials(d)
            rows = [[x ** a * y ** b for a, b in mons] for x, y, _ in pts]
            A = [[sum(r[i] * r[j] for r in rows) for j in range(len(mons))] for i in range(len(mons))]
            c = solve(A, [sum(r[i] * p[2] for r, p in zip(rows, pts)) for i in range(len(mons))])
            if c is None:
                continue
            f, _ = fit_polynomial([tuple(map(float, p)) for p in pts], d)
            for x, y, _ in pts:
                exact = sum(ci * x ** a * y ** b for ci, (a, b) in zip(c, mons))
                self.assertAlmostEqual(f(float(x), float(y)), float(exact), places=8)


class TestHKMap(unittest.TestCase):
    def test_surface_types_of_quadrics(self):
        h = 0.1
        cases = [(lambda x, y: x * x + y * y, "pit"), (lambda x, y: -x * x - y * y, "peak"),
                 (lambda x, y: x * x, "valley"), (lambda x, y: -y * y, "ridge"),
                 (lambda x, y: 0.2 * x - y, "flat"), (lambda x, y: x * y, "minimal"),
                 (lambda x, y: x * x - 0.5 * y * y, "saddle valley"), (lambda x, y: 0.5 * x * x - y * y, "saddle ridge")]
        for g, name in cases:
            Z = [[g((j - 5) * h, (i - 5) * h) for j in range(11)] for i in range(11)]
            self.assertEqual(hk_map(Z, h, 1e-9, 1e-9)[5][5], name, name)

    def test_curvature_formulas(self):
        # the sphere z = sqrt(1 - x^2 - y^2) at its top: H = -1, K = 1 with the upward normal
        H, K = curvatures(0.0, 0.0, -1.0, 0.0, -1.0)
        self.assertEqual((H, K), (-1.0, 1.0))
        # the cylinder z = x^2 / 2 at x = 1: curvature 1 / (1 + 1)^(3/2), mean curvature half of it
        H, K = curvatures(1.0, 0.0, 1.0, 0.0, 0.0)
        self.assertAlmostEqual(H, 0.5 / 2 ** 1.5, places=15)
        self.assertEqual(K, 0.0)


class TestEdgeCases(unittest.TestCase):
    def test_constant_image_is_one_planar_region(self):
        Z = [[2.5] * 12 for _ in range(12)]
        regions = variable_order_segmentation(Z, 0.1, 1e-9, 1e-7)
        self.assertEqual([(len(R), d) for R, _, d in regions], [(144, 1)])

    def test_too_small_for_a_seed(self):
        self.assertEqual(variable_order_segmentation([[0.0] * 6 for _ in range(6)], 0.1, 1e-9, 1e-7), [])

    def test_sphere_needs_more_than_a_quartic(self):
        # a sphere cap is no polynomial: every seed fails at order 4 and is rejected
        Z = [[(9 - (j * H2 - 1) ** 2 - (i * H2 - 1) ** 2) ** 0.5 for j in range(N)] for i in range(N)]
        self.assertEqual(variable_order_segmentation(Z, H2, 1e-9, 1e-7), [])

    def test_a_quintic_in_x_is_a_quartic_on_five_columns(self):
        # x^5 agrees with a quartic in x on 5 distinct x values, so thin strips are accepted
        Z = [[(j * H2) ** 5 + (i * H2) ** 2 + (j * H2) ** 2 for j in range(N)] for i in range(N)]
        regions = variable_order_segmentation(Z, H2, 1e-9, 1e-7)
        self.assertTrue(regions)
        for R, _, d in regions:
            self.assertEqual(d, 4)
            self.assertLessEqual(len({j for _, j in R}), 5)

    def test_region_never_enters_used_pixels(self):
        h = 1.0 / (N - 1)
        Z = [[0.0] * N for _ in range(N)]
        used = {(i, j) for i in range(N) for j in range(N) if j >= 12}
        seed = {(i, j) for i in range(5) for j in range(5)}
        R, f, d = grow_region(Z, h, seed, used, 1e-9, 1e-7)
        self.assertEqual(len(R), N * 12)
        self.assertFalse(R & used)
        self.assertEqual(d, 1)


class TestNoisy(unittest.TestCase):
    def test_measured_purity_and_coverage(self):
        # measured, not proved: with noise the regions stay inside one quadrant
        rng = random.Random(5)
        for sigma in (1e-4, 1e-3):
            Z = quadrant_image(H2, sigma, rng)
            regions = variable_order_segmentation(Z, H2, 2 * sigma, 6 * sigma, eps_h=0.1, eps_k=0.1)
            covered = 0
            for R, _, _ in regions:
                self.assertEqual(len({quadrant(i, j) for i, j in R}), 1)
                covered += len(R)
            self.assertGreaterEqual(covered / (N * N), 0.8)
            self.assertEqual(sorted(d for _, _, d in regions)[:2], [1, 2])


if __name__ == "__main__":
    unittest.main()

History

Besl and Jain studied the mean and Gaussian curvature of range images as features that do not change with the viewpoint in 1986, and classified surfaces into eight types by their signs. In 1988 they built on this the segmentation by variable-order surface fitting, which became a standard method for range images; Besl's book Surfaces in Range Image Understanding (1988) gives the full account. Later comparisons of range image segmentation, such as the one by Hoover and others in 1996 on planar scenes, used it as a reference, and the seed and grow scheme with surface fits carried over to the face-based segmentation of point clouds in reverse engineering.

References

  1. Paul J. Besl and Ramesh C. Jain, Segmentation through variable-order surface fitting, IEEE Transactions on Pattern Analysis and Machine Intelligence 10(2), 1988, 167 to 192, the HK sign map with eight surface types, the seed regions found by erosion, the iterative variable-order region growing with planar, biquadratic, bicubic and biquartic surfaces, and the merging of regions
  2. Paul J. Besl and Ramesh C. Jain, Invariant surface characteristics for 3D object recognition in range images, Computer Vision, Graphics, and Image Processing 33(1), 1986, 33 to 80, the mean and Gaussian curvature of a range image as invariant characteristics, their estimation by local fits, and the classification of regions into eight surface types by their signs
  3. Tamás Várady, Ralph R. Martin and Jordan Cox, Reverse engineering of geometric models, an introduction, Computer-Aided Design 29(4), 1997, 255 to 268, the section on segmentation, with face-based segmentation by region growing and the use of curvature signs to classify points

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.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