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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and the Gaussian curvature are estimated at every pixel, and the signs of and 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 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 on a rectangular grid of pixels at ; an error bound for the RMS error of a region; a band for the residual of a pixel that joins a region; thresholds and below which a curvature counts as zero.
Output. Disjoint regions of pixels, each 4-connected, with a polynomial of total degree for each region, whose RMS error on the region is at most . Pixels may stay unlabeled. Besl and Jain call the four orders planar, biquadratic, bicubic and biquartic, although the polynomials are of total degree to , with , , and coefficients.
The algorithm
VARIABLE-ORDER-SEGMENTATION(z, h, τ, β)- 1
type(p) ← (sign H(p), sign K(p)) at each pixel p, from a local quadratic fit - 2
while some 5 by 5 block of unblocked pixels has one type: S ← the deepest such block; block S - 3
R ← S; d ← 1 - 4
f ← the least-squares polynomial of total degree d on R; e ← its RMS error on R - 5
if e > τ: if d = 4 reject S, else d ← d + 1 and go to L4 - 6
R' ← R and the unused pixels connected to R through pixels q with |z(q) − f(q)| ≤ β - 7
if R' = R: accept (R, f, d), mark R used and blocked; else R ← R' and go to L4 - 8
return the accepted regions
Line L1. On a window of pixels the code fits ; since the window has the same shape everywhere, each coefficient is one fixed linear filter. With , , , , and , the curvatures of the graph with the upward normal are
from the fundamental forms of the graph. A cup has and , a pit. Each sign is when the value is within its threshold. The pair (sign = 0, sign > 0) cannot occur for exact curvatures, since .
Line L2. The depth of a pixel is the largest such that the block of side around it has one type and no blocked pixel; the code computes it by repeated erosion and takes the block around the deepest pixel. Besl and Jain also erode the largest regions of one type to get seeds. A seed needs pixels because Lemma 1 of the proof shows that a grid determines a polynomial of total degree , and a grid does not.
Lines L4 and L5. The fit uses the monomials with in the variables shifted to the centroid of the region and scaled to , and modified Gram-Schmidt done twice, which is stable for the columns of the quartic. The order rises only when the current order cannot fit the region within .
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 image with has four quadrants of pixels, with steps of about in height between them and four polynomials:
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 pixels, with and :
| quadrant | order 1 | order 2 | order 3 | order 4 | result |
|---|---|---|---|---|---|
| plane | 144 pixels, order 1 | ||||
| quadratic | 144 pixels, order 2 | ||||
| cubic | 144 pixels, order 3 | ||||
| quartic | 144 pixels, order 4 |
Each seed reaches its true order on its pixels, grows in one pass to the whole quadrant, and stops; the largest residual of a final fit is .
With noise. On the same quadrants over with Gaussian noise , , and curvature thresholds , the code found four regions, each inside one quadrant, with , , and pixels and orders , , and : the quartic quadrant was fitted within the noise by a cubic. At 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 in each variable that vanishes on a grid is zero. So every region that contains a 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 new pixels, so the algorithm stops after at most seeds and passes per seed.
- Exact recovery of one patch. Let a seed lie in a 4-connected set of unused pixels where for a polynomial of total degree exactly , let be smaller than the RMS errors of the lower orders on the seed, which are all positive, and let every unused pixel next to but outside it differ from by more than . Then the growth returns exactly , the polynomial and the order , in exact arithmetic.
The tests check the last statement on random polynomial patches, five of each order from to , and on the four quadrants; all 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 and 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 sit at with height . is the space of real polynomials in of total degree at most . For a set of pixels and , a least-squares polynomial of order on is an that minimizes , and is the RMS error of such an . A seed is a block of pixels. Lines L3 to L7 of the algorithm are the growth from one seed ; the set of used pixels does not change during it. All statements are in exact arithmetic.
Lemma 1 (unisolvence on a grid). Let and be sets of distinct numbers each. A polynomial of degree at most in and at most in that vanishes on is zero.
Proof. Write with polynomials of degree at most . For each , has degree at most and distinct roots , so all its coefficients vanish. So each has the distinct roots , and .
Corollary 1 (the fits exist and are unique). If contains a seed, then for every the least-squares polynomial of order on is unique.
Proof. The pixels of a seed have distinct values of and distinct values of . A polynomial of total degree at most has degree at most in each variable, so by Lemma 1 the only that vanishes on the seed, and hence on , is . So the map from the coefficients to the values on is injective, the design matrix has full column rank, and the least-squares solution is unique.
Lemma 1 is sharp for the seed size: on a grid with values , the quartic vanishes, so the quartic fit is not unique.
Theorem 1 (termination). The growth from a seed stops after at most passes of lines L4 to L7, and the whole algorithm stops after at most seeds, where 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 , which happens at most times since ; line L5 rejects; line L7 accepts; or line L7 replaces by with , so gains at least one pixel. A region has at most 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 pixels that are not blocked and then blocks them, so the blocked set grows by pixels per seed, and there are at most seeds.
Lemma 2 (lower orders leave an error). Let have total degree exactly , and let on a seed . Then for every .
Proof. Suppose for some . Then some agrees with on , so vanishes on the grid . It has degree at most in each variable, so by Lemma 1. But contains the nonzero terms of degree of , a contradiction.
Theorem 2 (exact recovery of a polynomial patch). Let be a 4-connected set of pixels with , let be a polynomial of total degree exactly with on , and let the seed lie in . Assume
- for every (these numbers are positive by Lemma 2), and ;
- every pixel that is a 4-neighbor of a pixel of has .
Then the growth from accepts the region with the polynomial and the order .
Proof. Line L3 sets and . For , line L4 gives the error by assumption 1, and since line L5 raises the order. So the order reaches with .
Now take any with and . Since fits with zero error, it is a least-squares polynomial, and by Corollary 1 it is the only one; so line L4 gives and , and line L5 passes to line L6. The search of line L6 starts from and moves through unused pixels with .
It reaches every pixel of : these are unused, have residual , and is 4-connected and contains .
It reaches no pixel outside : suppose it does, and let be the first such pixel reached. The pixel from which was reached is in or was reached earlier, so it is in , and is a 4-neighbor of , unused and outside . Assumption 2 gives , so the search does not enter , a contradiction.
So . If , line L7 accepts . Otherwise line L7 sets , and the next pass, by the same argument with , gives , and , and accepts .
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 , and the curvature thresholds. With floating point the fits have rounding errors of about times the size of the data, so the code uses a small positive in place of .
Complexity
The sign map costs per pixel, in all. One seed search erodes the type map up to times, . A fit on a region of pixels with coefficients costs , and a growth pass for the residuals; each seed has at most order raises and growth passes. With seeds and 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 .
Properties
- Lowest order first. A region gets the simplest of the four surfaces that fits within , 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 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 and , 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. and 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 can stop growing at order when the cubic fits the part it has grown to within and no neighbor lies within , as in the noisy example.
- Thin regions. On a strip of columns any function of alone equals a quartic in , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 710BVP Edit this page History Report an error Markdown