Algorithmadvanced
Shape diameter function
Also called Shapira-Shamir-Cohen-Or segmentation.
Shapira, Shamir and Cohen-Or's local thickness measure from rays cast inward in a cone, used to segment meshes into parts that stay stable under pose changes.
- Time
- O(r F^2) worst
- Space
- Θ(r) extra
- Where
- F = the number of faces; r = the number of rays for each face
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lior Shapira, Ariel Shamir, Daniel Cohen Or, 2008
The shape diameter function (SDF) gives each face of a closed triangle mesh a number that measures how thick the shape is at that face. From the centroid of the face, a few dozen rays go into the shape, inside a cone about the inward normal. Each ray stops where it leaves the shape on the other side. The lengths far from the median are dropped, and the mean of the rest is the SDF of the face. On a finger the value is small, on a torso it is large, and it changes little when an arm bends at the elbow, because the thickness of the arm does not change. Shapira, Shamir and Cohen-Or (2008) introduced the function and built a mesh segmentation on it: cluster the values with a Gaussian mixture, then smooth the labels with a graph cut. The SDF is related to the medial axis: it is meant to approximate the diameter of the largest ball inside the shape near the face, but it is computed from rays and needs no medial axis.
In plain words
Stand inside a hollow statue, on the inner side of its skin, and look straight in. Measure how far it is to the skin on the other side. Do the same while looking a little to the left, to the right, up and down. Throw away the strange answers, and take the average of the rest. That number is the thickness of the statue at that spot.
In a thin part, such as a finger, all the answers are small. In a thick part, such as the body, they are large. When the statue raises its arm, the arm keeps its thickness, so the numbers on the arm stay almost the same.
Once every small piece of the skin has its number, the pieces with similar numbers are put in groups, and the groups become the parts: head, arms, legs, body.
The problem
The input is a closed triangle mesh with outward normals, the boundary of a solid, and a face of it. The output is a positive number that measures the thickness of the solid near , or nothing if no ray leaves the solid in a valid way. For a segmentation, the input also has a number of clusters, and the output is a label for each face.
There is no exact target value. For a slab of thickness , a single ray along the normal gives , and the cone of rays gives a fixed multiple of . On other shapes the SDF is a measured quantity, and its use is to compare faces of the same mesh, or faces of meshes of the same object in different poses.
The algorithm
SDF(closed mesh with outward normals, face f, number of rays r, cone angle γ)- 1
o ← the centroid of f; n ← the inward normal of f - 2
D ← n and r − 1 more directions in rings of 8 around n, at angles up to γ/2 from n - 3
for each direction d in D do - 4
(t, G) ← the smallest t > 0 with o + t d on a face other than f, and the faces G hit at that t - 5
if there is a hit and d · n_g > 0 for some g in G then append the length t |d| to ℓ - 6
m ← the median of ℓ; s ← the standard deviation of ℓ - 7
K ← the lengths of ℓ with |ℓ_i − m| ≤ s - 8
return the mean of K, or nothing if ℓ is empty
Line L2 sets the cone. The CGAL implementation uses a cone with an opening of , so , and 25 rays by default. The code uses the axis and three rings of eight rays, at , and . Line L4 is a ray-triangle test against every face. The code computes it with exact rational numbers: the coordinates, the centroid and the directions are turned into fractions, so the hit parameter , the choice of the first face and the test of line L5 are decided without rounding. Only the length is a float. Line L5 keeps a ray only if it leaves the solid at the first hit, that is if the ray goes in the direction of the outward normal of the face it hits. On a mesh with holes or with wrongly oriented faces, a ray can leave through a hole (no hit) or reach a face from its outer side; both rays are dropped. Lines L6 and L7 remove outliers. A ray that slips through a narrow gap into a far part of the mesh, or that hits the far end of a long part at a flat angle, gives a length far from the others.
Normalization. The values are then mapped to with
where and are taken over the faces of the mesh. A larger spreads out the small values, which are the thin parts. The values do not depend on the scale of the mesh.
Segmentation. The paper then cuts the mesh into parts in two steps.
- Soft clustering. Fit a mixture of Gaussians to the normalized values with the EM algorithm. Each face gets a probability for each cluster. Thin parts and thick parts fall into different Gaussians.
- Hard clustering. Choose one label for each face by minimizing an energy on the graph of faces, where two faces are adjacent when they share an edge. The data term of a face is of the probability of its label. The smoothness term charges each pair of adjacent faces with different labels, and the charge is small along concave edges, where parts usually meet. The minimization uses alpha-expansion graph cuts. A weight between the two terms sets how smooth the borders are.
A part is then a connected set of faces with the same label. The SDF can be smoothed over the surface before the clustering, for example with a bilateral filter on the faces, as CGAL does. The code of this page computes the SDF and the normalization, not the segmentation.
Example
A slab. Take the box , with the big sides cut into unit squares and each square into two triangles, and a face of the top side near its center. All 25 rays reach the bottom side. Their lengths are (the axis), (eight rays), (eight rays) and (eight rays). The median is and the standard deviation is , so line L7 drops the eight rays of length , and
The SDF is 17% larger than the thickness, because the cone tilts the rays. For the slab of thickness the value is , half as large. With one ray along the normal, the SDF is , the thickness.
A bar that bends. Take the bar , cut into 208 triangles. On the faces of the long sides, away from the ends, the SDF is between and , with a mean of . On the faces of the two ends it is on average, because the rays from an end hit the long sides soon. Now bend the bar into a quarter circle, with the same triangles: each vertex goes to the point at the arc length along a circle of radius . On the long sides away from the ends, the SDF now has a mean of , between and . The value of each such face changes by on average and by at most. The largest change on the whole mesh is , at a face next to an end, where the SDF goes from to . So the measure stays close to the thickness of the bar, not to its shape in space. This is the stability that the segmentation uses.
Why the test is exact. A ray aimed at a point of an edge shared by two triangles must hit one of them. In floating point, the computed barycentric coordinates can put the point just outside both triangles, and the ray then passes through the closed surface. In a search over random triangles with float coordinates, with each ray aimed at the exact midpoint of the shared edge, this happened in 1612 of 20000 trials. The exact test hits both triangles at the same in all of them.
Correctness
The proof shows these facts about the code.
- The ray-triangle test is exact. The test solves by Cramer's rule and checks , , and on rationals. It returns the hit exactly when the ray meets the closed triangle, and two faces that share the hit point are both found.
- The exit test keeps the right rays. On a closed mesh with outward normals, a ray that starts inside the face and goes inward, and whose first hit is inside a face , has . So line L5 keeps it. The choice on an edge or a vertex is not proved to be the right one in all cases.
- The slab. On a slab of thickness , for a face far enough from the side walls, every ray is kept, a ray at the angle has length , one ray gives , and the SDF is times a constant that depends only on the angles of the rays. For the 25 rays of the code the constant is .
- It stops. Each face needs times ray-triangle tests.
The rest is measured, not proved. That the SDF is close to the local diameter on other shapes, that it changes little when the pose changes, and that the segmentation finds the parts a person would choose, are results of experiments, in the paper and in the example above.
Proof: The exact ray test, the exit test, and the shape diameter of a slabfull
Setup. The mesh has vertices with rational coordinates (every float is a rational number) and faces of positive area. It is closed and bounds a solid , and its faces are oriented outward: near every point inside a face , the points are outside and the points are inside, for all small , where . For a face , the algorithm takes the centroid of , a list of rational directions with , and for each the ray , . All arithmetic in lines L1 to L5 is on rationals, so it is exact.
Lemma 1 (the ray-triangle test). Let , , and . If , the function returns exactly when lies in the closed triangle and , and it returns None otherwise. If , it returns None.
Proof. The point equals exactly when . This is a linear system in with the columns . Its determinant is . If , Cramer's rule gives the unique solution
which are the values that the function computes, with pv and qv . The point is in the closed triangle exactly when , and . The function returns None as soon as one of these fails, and returns only when also . The early test only rejects points that also fail or . All values are rational and all comparisons are exact. If , then is parallel to the plane of the triangle, and the ray meets the plane in no point or in a whole line; the function treats both as a miss.
Lemma 2 (the first hit). For each ray, line L4 returns the smallest such that lies on a face other than (among faces not parallel to ), and the set of all such faces at that .
Proof. By Lemma 1, each call returns the exact parameter of the hit or None. The loop keeps the smallest value seen and the faces that reach it, with exact comparisons, so two faces that meet the ray at the same point, as at a shared edge or vertex, are both in the set.
Lemma 3 (the exit test keeps every ray that leaves through the inside of a face). Let the first hit of a ray be at , and suppose lies inside a single face (not on its boundary) and is not parallel to . Then , so line L5 keeps the ray.
Proof. The face is not hit again: , so the line meets the plane of only at . Since lies inside and , the points are on the side of for small , so they are inside by the orientation. By Lemma 2 the open segment from to meets no face, so it does not cross the boundary of , and it is connected; so all its points are inside . In particular is inside for small . Now . If , then , so is on the side of , which is outside by the orientation. This is a contradiction, so .
When the first hit is on an edge or a vertex, the code keeps the ray if one of the faces there has . That this is always the right choice is not proved. When the faces of the mesh are not consistently oriented, Lemma 3 does not apply, and the code drops the rays that reach a face from its outer side.
Theorem 1 (termination and cost). For one face, the algorithm stops after ray-triangle tests and exit tests, where is the number of faces, and lines L6 to L8 take time.
Proof. Each loop runs over a finite list, and each ray-triangle test is a fixed number of exact operations on rationals. The median needs a sort of at most lengths.
Theorem 2 (the slab). Let the mesh be the box with , and let be a face of the top side whose centroid satisfies and , where is the opening angle of the cone. Then every ray of is kept, and a ray at the angle from the inward normal has the length . With one ray (), the SDF is . For a fixed list of angles, the SDF is times a number that does not depend on , on , or on the position of in the region above.
Proof. A ray with reaches the plane at , at the length , and its horizontal distance from there is . By the condition on , this point lies inside the bottom side, not on its border, so it is on one or two bottom faces. Before the ray is strictly between the planes and strictly inside the side walls, so it meets no other face. The bottom faces have along , so , and the ray is kept (also when it hits a shared edge of two bottom faces, because both have ). With one ray, and the length is . The directions depend only on the normal direction , so they do not change with , or . The list of lengths is times the list of the , and the median, the standard deviation, the set kept by line L7 and the mean of line L8 all scale by .
For the 25 directions of the code, at , , and (eight at each nonzero angle), the lengths are , , and . The median is and the standard deviation is , so line L7 drops the eight rays at , and the SDF is , up to the rounding of the directions to floats.
What is not proved. That the SDF approximates the diameter of the shape near a face, that it changes little when a shape changes its pose, and that the segmentation built on it finds meaningful parts are claims about typical shapes. They are measured, not proved here.
Complexity
For one face, line L4 tests each ray against every face, so the time is tests on the real RAM, and the sort of line L6 adds . For all faces the time is . The extra space is for the lengths of one face. A bounding volume hierarchy makes each ray cost about tests on typical meshes, so all faces take about time; the worst case stays . Exact rational arithmetic is slower than floats by a large factor: the pure Python code took about 40 seconds for the 208 faces of the bar. A robust float test, such as a watertight ray-triangle test, is the usual choice for large meshes.
Properties
- Invariant under scaling, nearly invariant under rigid motions. Scaling the mesh scales all lengths, and the normalized values do not change. A rigid motion moves the cone with the face, but the code may turn the rings of rays about the axis, so the values can change slightly, as on the rotated slab of the tests, where they agree to .
- Nearly invariant under pose changes. A bend at a joint changes the SDF mostly near the joint. This is measured, not proved.
- Volume based. The SDF looks at the solid, not only at the surface near the face. Two faces on opposite sides of a thin part get similar values.
- Deterministic. The directions are fixed, so the same mesh gives the same values.
- Needs a closed, oriented mesh. Holes and flipped faces make rays drop, and a face with no kept ray gets no value.
Variants and improvements
- Skeletons. The paper also uses the SDF to build a skeleton of the parts: a point pushed inward from a face by half its SDF lies near the middle of the shape.
- Smoothing on the surface. CGAL smooths the SDF with a bilateral filter over the faces before the clustering, and gives faces with no value the mean of their neighbours.
- Volumetric versions. The thickness can also be computed from a voxel grid or from a medial axis, for example as the diameter of the largest inscribed ball that touches the point. This is more expensive but has no rays to choose.
- Other ray descriptors. Ambient occlusion casts rays outward, not inward, and measures how hidden a point is. Both are per-face features that learning-based segmentation can use together.
- Fewer faces. The values of neighbouring faces are close, so the SDF can be computed on a subset of the faces and spread to the others.
When to use it
Use the SDF when the parts of a shape differ in thickness, such as the limbs of an animal, the legs of a chair or the handle of a cup, and when the segmentation must be the same for the same object in different poses. It is a good feature for comparing shapes of articulated objects and for learning-based segmentation. For a segmentation into nearly flat patches, as for mechanical parts or buildings, a normal-based method such as variational shape approximation fits better. For a mesh that is not closed, repair it first, or expect missing values near the holes.
Pitfalls
- Float ray tests leak. A float ray-triangle test can miss both faces at a shared edge, and the ray then finds a face far away or none. Use exact or watertight tests, or at least treat lengths far from the median as outliers.
- Hitting the starting face. A ray from the centroid of meets the plane of at . Skip itself and require , or the SDF is 0.
- Wrong orientation. With flipped faces, the exit test drops rays that should count, or keeps rays that reached a face from outside. Orient the mesh consistently first.
- Too wide a cone. At from the normal a ray is twice as long as the thickness, and near the end of a part it can hit the far end. The outlier removal handles a few such rays, not most of them.
- Not a distance. The SDF of a slab is times its thickness with the cone of the code, and the factor changes with the number and the angles of the rays. Compare SDF values only when they come from the same settings.
- Parts of equal thickness. Two parts with the same thickness, such as the upper and the lower leg, fall into the same cluster. The graph cut separates them only where the surface has a concave edge between them.
- Cost. Without an acceleration structure the cost is quadratic in the number of faces.
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 mx1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes and dense linear algebra, used by the mx1 pages.
Points are tuples of three numbers. Faces are tuples of three vertex indices,
counterclockwise when seen from outside, so that the face normals point out.
Only the standard library is used. The geometric signs (an obtuse angle, the
side of a plane) are decided exactly, with Fraction, from the float input.
The linear solvers work on float input and on Fraction input.
"""
import math
from fractions import Fraction
# ---------------------------------------------------------------- vectors
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def scale(s, a):
return tuple(s * x for x in a)
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def norm(a):
return math.sqrt(dot(a, a))
def unit(a):
n = norm(a)
return tuple(x / n for x in a)
def exact(p):
"""The exact rational value of a point with float or Fraction coordinates."""
return tuple(Fraction(x) for x in p)
def sign(x):
return (x > 0) - (x < 0)
def dot_sign(a, b, c):
"""The exact sign of (b - a) . (c - a): positive for an acute angle at a, negative for an obtuse one."""
a, b, c = exact(a), exact(b), exact(c)
return sign(dot(sub(b, a), sub(c, a)))
def orient3d(a, b, c, d):
"""The exact sign of det(b - a, c - a, d - a): positive when d lies on the side of the plane abc that its normal points to."""
a, b, c, d = exact(a), exact(b), exact(c), exact(d)
return sign(dot(cross(sub(b, a), sub(c, a)), sub(d, a)))
# ---------------------------------------------------------------- topology
def edges(faces):
"""The undirected edges as sorted pairs, in sorted order."""
s = set()
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
s.add((min(i, j), max(i, j)))
return sorted(s)
def neighbours(n, faces):
nb = [set() for _ in range(n)]
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
nb[i].add(j)
nb[j].add(i)
return [sorted(s) for s in nb]
def edge_faces(faces):
"""Map each undirected edge to the list of the faces that hold it."""
m = {}
for t, f in enumerate(faces):
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
m.setdefault((min(i, j), max(i, j)), []).append(t)
return m
def face_adjacency(faces):
"""For each face, the sorted list of the faces that share an edge with it."""
adj = [set() for _ in faces]
for fs in edge_faces(faces).values():
for a in fs:
for b in fs:
if a != b:
adj[a].add(b)
return [sorted(s) for s in adj]
def boundary_vertices(faces):
b = set()
for (i, j), fs in edge_faces(faces).items():
if len(fs) == 1:
b.update((i, j))
return b
def vertex_faces(n, faces):
vf = [[] for _ in range(n)]
for t, f in enumerate(faces):
for i in f:
vf[i].append(t)
return vf
# ---------------------------------------------------------------- face geometry
def face_cross(points, f):
"""cross(b - a, c - a): twice the area times the unit normal."""
a, b, c = (points[i] for i in f)
return cross(sub(b, a), sub(c, a))
def face_area(points, f):
return norm(face_cross(points, f)) / 2
def face_normal(points, f):
return unit(face_cross(points, f))
def centroid(points, f):
a, b, c = (points[i] for i in f)
return tuple((x + y + z) / 3 for x, y, z in zip(a, b, c))
def cot_at(a, b, c):
"""The cotangent of the angle at a in the triangle a, b, c."""
u, v = sub(b, a), sub(c, a)
return dot(u, v) / norm(cross(u, v))
def cotan_weights(points, faces):
"""w_ij = (cot alpha_ij + cot beta_ij) / 2, with alpha and beta the angles opposite the edge ij."""
w = {}
for f in faces:
for k in range(3):
i, j, o = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
e = (min(i, j), max(i, j))
w[e] = w.get(e, 0.0) + cot_at(points[o], points[i], points[j]) / 2
return w
def stiffness_rows(n, weights):
"""The cotangent stiffness matrix C = -L as a list of dict rows: C_ij = -w_ij, C_ii = sum of w_ij."""
C = [dict() for _ in range(n)]
for (i, j), w in weights.items():
C[i][j] = C[i].get(j, 0) - w
C[j][i] = C[j].get(i, 0) - w
C[i][i] = C[i].get(i, 0) + w
C[j][j] = C[j].get(j, 0) + w
return C
def barycentric_area(points, faces):
A = [0.0] * len(points)
for f in faces:
a = face_area(points, f) / 3
for i in f:
A[i] += a
return A
def mixed_area(points, faces):
"""The mixed Voronoi area of Meyer, Desbrun, Schroeder and Barr (2003).
A triangle with no obtuse angle gives each corner its Voronoi part,
(|ij|^2 cot k + |ik|^2 cot j) / 8. An obtuse triangle gives half its area
to the obtuse corner and a quarter to each other corner.
"""
A = [0.0] * len(points)
for f in faces:
P = [points[i] for i in f]
obtuse = [dot_sign(P[k], P[(k + 1) % 3], P[(k + 2) % 3]) < 0 for k in range(3)]
area = face_area(points, f)
for k in range(3):
i, pj, pk, pi = f[k], P[(k + 1) % 3], P[(k + 2) % 3], P[k]
if not any(obtuse):
eij, eik = sub(pj, pi), sub(pk, pi)
A[i] += (dot(eij, eij) * cot_at(pk, pi, pj) + dot(eik, eik) * cot_at(pj, pi, pk)) / 8
else:
A[i] += area / 2 if obtuse[k] else area / 4
return A
def mean_curvature_normal(points, faces, area="mixed"):
"""K_i = (1 / (2 A_i)) sum_j (cot alpha_ij + cot beta_ij)(x_i - x_j), which is 2 H n_i with outward n_i."""
A = mixed_area(points, faces) if area == "mixed" else barycentric_area(points, faces)
w = cotan_weights(points, faces)
K = [[0.0, 0.0, 0.0] for _ in points]
for (i, j), wij in w.items():
d = sub(points[i], points[j])
for c in range(3):
K[i][c] += wij * d[c]
K[j][c] -= wij * d[c]
return [tuple(x / A[i] for x in K[i]) for i in range(len(points))]
def area_gradient(points, faces):
"""The gradient of the total area with respect to each vertex, summed face by face.
For a face with corner i and other corners j, k, the gradient at i is
(cot k (x_i - x_j) + cot j (x_i - x_k)) / 2, where cot j is the cotangent of the angle at j.
"""
g = [[0.0, 0.0, 0.0] for _ in points]
for f in faces:
for k in range(3):
i, j, l = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
pi, pj, pl = points[i], points[j], points[l]
cl, cj = cot_at(pl, pi, pj), cot_at(pj, pi, pl)
for c in range(3):
g[i][c] += (cl * (pi[c] - pj[c]) + cj * (pi[c] - pl[c])) / 2
return [tuple(v) for v in g]
def total_area(points, faces):
return sum(face_area(points, f) for f in faces)
# ---------------------------------------------------------------- dense linear algebra
def identity(n, one=1):
return [[one if i == j else 0 * one for j in range(n)] for i in range(n)]
def transpose(A):
return [list(r) for r in zip(*A)]
def mat_mul(A, B):
Bt = transpose(B)
return [[sum(a * b for a, b in zip(r, c)) for c in Bt] for r in A]
def mat_vec(A, x):
return [sum(a * b for a, b in zip(r, x)) for r in A]
def det3(A):
return dot(A[0], cross(A[1], A[2]))
def solve_dense(A, b):
"""Solve A x = b by Gaussian elimination with partial pivoting. Exact on Fraction input."""
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 M[p][c] == 0:
raise ValueError("singular matrix")
M[c], M[p] = M[p], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
if f:
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):
x[r] = (M[r][n] - sum(M[r][k] * x[k] for k in range(r + 1, n))) / M[r][r]
return x
def cholesky(A):
"""The lower triangular L with A = L L^T, for a symmetric positive definite A."""
n = len(A)
L = [[0.0] * n for _ in range(n)]
for j in range(n):
d = A[j][j] - sum(L[j][k] ** 2 for k in range(j))
if d <= 0:
raise ValueError("matrix is not positive definite")
L[j][j] = math.sqrt(d)
for i in range(j + 1, n):
L[i][j] = (A[i][j] - sum(L[i][k] * L[j][k] for k in range(j))) / L[j][j]
return L
def cholesky_solve(L, b):
n = len(L)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(L[i][k] * y[k] for k in range(i))) / L[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(L[k][i] * x[k] for k in range(i + 1, n))) / L[i][i]
return x
def _rotation(theta):
"""c, s of the Jacobi rotation for the cotangent theta of twice its angle."""
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1))
c = 1 / math.sqrt(1 + t * t)
return c, t * c
def jacobi_eigen(A, tol=1e-15, sweeps=100):
"""Eigenvalues (ascending) and unit eigenvectors of a symmetric matrix, by cyclic Jacobi rotations."""
n = len(A)
a = [[float(x) for x in r] for r in A]
v = identity(n, 1.0)
for _ in range(sweeps):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(i + 1, n))
if off <= tol * tol * sum(a[i][i] ** 2 for i in range(n)) or off == 0:
break
for p in range(n):
for q in range(p + 1, n):
if a[p][q] == 0:
continue
c, s = _rotation((a[q][q] - a[p][p]) / (2 * a[p][q]))
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
order = sorted(range(n), key=lambda k: a[k][k])
return [a[k][k] for k in order], [[v[i][k] for i in range(n)] for k in order]
def svd3(A, sweeps=60):
"""A = U diag(s) V^T for a 3 x 3 matrix, with s descending and U, V orthogonal (one-sided Jacobi)."""
U = [[float(x) for x in r] for r in A]
V = identity(3, 1.0)
for _ in range(sweeps):
done = True
for p, q in ((0, 1), (0, 2), (1, 2)):
al = sum(U[i][p] ** 2 for i in range(3))
be = sum(U[i][q] ** 2 for i in range(3))
ga = sum(U[i][p] * U[i][q] for i in range(3))
if ga == 0 or abs(ga) <= 1e-15 * math.sqrt(al * be):
continue
done = False
c, s = _rotation((be - al) / (2 * ga))
for M in (U, V):
for i in range(3):
mp, mq = M[i][p], M[i][q]
M[i][p], M[i][q] = c * mp - s * mq, s * mp + c * mq
if done:
break
sig = [math.sqrt(sum(U[i][k] ** 2 for i in range(3))) for k in range(3)]
order = sorted(range(3), key=lambda k: -sig[k])
s = [sig[k] for k in order]
cols = [[U[i][k] for i in range(3)] for k in order]
vcols = [[V[i][k] for i in range(3)] for k in order]
tiny = 1e-13 * max(s[0], 1e-300)
u = [tuple(x / s[k] for x in cols[k]) for k in range(3) if s[k] > tiny]
while len(u) < 3: # complete U where A has a null direction
if not u:
u.append((1.0, 0.0, 0.0))
elif len(u) == 1:
e = min(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), key=lambda t: abs(dot(t, u[0])))
u.append(unit(cross(u[0], e)))
else:
u.append(cross(u[0], u[1]))
Um = [[u[k][i] for k in range(3)] for i in range(3)]
Vm = [[vcols[k][i] for k in range(3)] for i in range(3)]
return Um, s, Vm
def best_rotation(S):
"""The rotation R (det 1) that maximizes trace(R S): with S = U diag(s) V^T, R = V diag(1, 1, d) U^T, d = det(V U^T)."""
U, _, V = svd3(S)
d = 1.0 if det3(mat_mul(V, transpose(U))) > 0 else -1.0
return mat_mul(mat_mul(V, [[1.0, 0, 0], [0, 1.0, 0], [0, 0, d]]), transpose(U))
def rotation_matrix(axis, angle):
"""The rotation by angle about the unit vector axis (Rodrigues)."""
x, y, z = unit(axis)
c, s = math.cos(angle), math.sin(angle)
C = 1 - c
return [[c + x * x * C, x * y * C - z * s, x * z * C + y * s],
[y * x * C + z * s, c + y * y * C, y * z * C - x * s],
[z * x * C - y * s, z * y * C + x * s, c + z * z * C]]
# ---------------------------------------------------------------- test meshes
def orient_outward(points, faces):
"""Flip each face of a mesh around the origin so that its normal points away from the origin (exact test)."""
out = []
o = (0, 0, 0)
for f in faces:
a, b, c = (points[i] for i in f)
out.append(tuple(f) if orient3d(a, b, c, o) < 0 else (f[0], f[2], f[1]))
return out
def octahedron():
p = [(1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0)]
f = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
return p, orient_outward(p, f)
def icosahedron():
t = (1 + math.sqrt(5)) / 2
raw = [(-1, t, 0), (1, t, 0), (-1, -t, 0), (1, -t, 0), (0, -1, t), (0, 1, t), (0, -1, -t), (0, 1, -t),
(t, 0, -1), (t, 0, 1), (-t, 0, -1), (-t, 0, 1)]
p = [unit(tuple(float(x) for x in q)) for q in raw]
f = [(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4), (11, 10, 2), (10, 7, 6),
(7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10),
(8, 6, 7), (9, 8, 1)]
return p, orient_outward(p, f)
def icosphere(level, radius=1.0):
"""The icosahedron with each triangle cut into four `level` times, projected to the sphere."""
p, f = icosahedron()
p = list(p)
for _ in range(level):
mid = {}
def m(i, j):
e = (min(i, j), max(i, j))
if e not in mid:
mid[e] = len(p)
p.append(unit(scale(0.5, add(p[i], p[j]))))
return mid[e]
nf = []
for a, b, c in f:
ab, bc, ca = m(a, b), m(b, c), m(c, a)
nf += [(a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca)]
f = nf
return [scale(radius, q) for q in p], f
def cylinder(radius, height, m, k, twisted=False):
"""An open tube of m vertices around and k + 1 rings, axis z, centred at the origin, normals outward.
Plain: each rectangle is cut by the same diagonal. Twisted: ring l is turned by l half steps,
so that each vertex has six neighbours, as in a grid of near-equilateral triangles.
"""
p = []
for l in range(k + 1):
z = height * l / k - height / 2
for s in range(m):
th = 2 * math.pi * (s + (l / 2 if twisted else 0)) / m
p.append((radius * math.cos(th), radius * math.sin(th), z))
f = []
for l in range(k):
for s in range(m):
a, b = l * m + s, l * m + (s + 1) % m
c, d = b + m, a + m
if twisted: # the ring above is turned half a step forward
f += [(a, b, d), (b, c, d)]
else:
f += [(a, b, c), (a, c, d)]
return p, f
def box_mesh(size, div):
"""The closed surface of the box [-a/2, a/2] x [-b/2, b/2] x [-c/2, c/2], each side a grid of div cells.
size = (a, b, c) may hold Fractions, div = (na, nb, nc) are the numbers of cells along each axis.
Each grid cell is cut into two triangles. The normals point out.
"""
index, p, f = {}, [], []
def vid(key):
if key not in index:
index[key] = len(p)
p.append(tuple(size[a] * Fraction(key[a], div[a]) - Fraction(size[a]) / 2 for a in range(3)))
return index[key]
for ax in range(3):
u, w = [a for a in range(3) if a != ax]
for side in (0, div[ax]):
out = 1 if side else -1
eu = [0, 0, 0]
ew = [0, 0, 0]
eu[u], ew[w] = 1, 1
flip = cross(eu, ew)[ax] != out
for s in range(div[u]):
for t in range(div[w]):
q = []
for ds, dt in ((0, 0), (1, 0), (1, 1), (0, 1)):
key = [0, 0, 0]
key[ax], key[u], key[w] = side, s + ds, t + dt
q.append(vid(tuple(key)))
tris = [(q[0], q[1], q[2]), (q[0], q[2], q[3])]
f += [(a, c, b) if flip else (a, b, c) for a, b, c in tris]
return p, f
def to_float(points):
return [tuple(float(x) for x in q) for q in points]
shape_diameter_function.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shape-diameter-function/. The authors are listed in prov/WRAPDK.jsonl.
"""Shape diameter function (Shapira, Shamir and Cohen-Or, The Visual Computer 2008).
For a face f of a closed triangle mesh with outward normals, rays leave the
centroid of f inside a cone about the inward normal. Each ray stops at the
first face it hits. The lengths that are far from the median are dropped,
and the mean of the others is the SDF of f, a measure of the local thickness.
The ray-triangle tests are exact: all coordinates, ray origins and ray
directions are turned into Fractions, so the hit parameter t, the choice of
the first face and the side from which the ray reaches it are decided without
rounding. Only the final lengths t |d| are floats.
"""
import math
import statistics
from mx1mesh import cross, dot, exact, norm, sub, unit
def ray_triangle(o, d, a, b, c):
"""The exact t > 0 with o + t d in the closed triangle abc, or None. A ray parallel to the plane of abc misses."""
o, d, a, b, c = exact(o), exact(d), exact(a), exact(b), exact(c)
e1, e2 = sub(b, a), sub(c, a)
pv = cross(d, e2)
det = dot(e1, pv)
if det == 0:
return None
s = sub(o, a)
u = dot(s, pv) / det
if u < 0 or u > 1:
return None
qv = cross(s, e1)
v = dot(d, qv) / det
if v < 0 or u + v > 1:
return None
t = dot(e2, qv) / det
return t if t > 0 else None
def exact_cross(points, face):
"""cross(b - a, c - a) of the face, computed exactly: its direction is the outward normal."""
a, b, c = (exact(points[i]) for i in face)
return cross(sub(b, a), sub(c, a))
def first_hit(points, faces, o, d, skip):
"""The smallest exact t of a hit of the ray o + t d with a face other than skip, and the faces hit at that t."""
best, hit = None, []
for g, (a, b, c) in enumerate(faces):
if g == skip:
continue
t = ray_triangle(o, d, points[a], points[b], points[c])
if t is None:
continue
if best is None or t < best:
best, hit = t, [g]
elif t == best:
hit.append(g) # the ray passes through an edge or a vertex
return best, hit
def cone_directions(n, rays, angle):
"""Directions in the cone of full opening angle about the vector n: n itself, then rings of 8.
rays is rounded down to 1 + 8 k. The ring r of k sits at the angle (angle / 2) r / k from n.
The directions are floats made exact with Fraction, so every later test on them is exact.
"""
axis = unit(n)
helper = (1.0, 0.0, 0.0) if abs(axis[0]) < 0.9 else (0.0, 1.0, 0.0)
u = unit(cross(axis, helper))
w = cross(axis, u)
out = [exact(n)]
rings = (rays - 1) // 8
for r in range(1, rings + 1):
th = angle / 2 * r / rings
for k in range(8):
ph = 2 * math.pi * (k + r / 2) / 8
d = tuple(math.cos(th) * axis[i] + math.sin(th) * (math.cos(ph) * u[i] + math.sin(ph) * w[i]) for i in range(3))
out.append(exact(d))
return out
def ray_lengths(points, faces, f, rays=25, angle=2 * math.pi / 3):
"""The lengths of the rays of face f that leave the solid at their first hit."""
a, b, c = (exact(points[i]) for i in faces[f])
o = tuple((x + y + z) / 3 for x, y, z in zip(a, b, c)) # @line L1
inward = tuple(-x for x in exact_cross(points, faces[f]))
lengths = []
directions = cone_directions(inward, rays, angle) # @line L2
for d in directions: # @line L3
t, hit = first_hit(points, faces, o, d, f) # @line L4
if t is None:
continue # the ray leaves through a hole
if any(dot(d, exact_cross(points, faces[g])) > 0 for g in hit): # exact: the ray goes out at g
lengths.append(float(t) * norm(tuple(float(x) for x in d))) # @line L5
return lengths
def shape_diameter(points, faces, f, rays=25, angle=2 * math.pi / 3):
"""The SDF of face f: the mean of the ray lengths within one standard deviation of their median, or None."""
lengths = ray_lengths(points, faces, f, rays, angle)
if not lengths:
return None
m = statistics.median(lengths) # @line L6
s = statistics.pstdev(lengths)
kept = [x for x in lengths if abs(x - m) <= s] # @line L7
return sum(kept) / len(kept) # @line L8
def normalize(values, alpha=4):
"""Map SDF values to [0, 1] with log(alpha (x - min) / (max - min) + 1) / log(alpha + 1)."""
lo, hi = min(values), max(values)
if hi == lo:
return [0.0 for _ in values]
return [math.log(alpha * (x - lo) / (hi - lo) + 1) / math.log(alpha + 1) for x in values]
test_shape_diameter_function.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shape-diameter-function/. The authors are listed in prov/WRAPDK.jsonl.
import math
from fractions import Fraction
from mx1mesh import box_mesh, centroid, cross, dot, exact, mat_vec, sub, to_float
from shape_diameter_function import normalize, ray_lengths, ray_triangle, shape_diameter
def slab(h):
"""The box 6 x 6 x h, cut into unit squares on the big sides, and a face of the top side near its centre."""
p, f = box_mesh((6, 6, h), (6, 6, 1))
top = [g for g in range(len(f)) if all(p[v][2] == Fraction(h) / 2 for v in f[g])]
centre = [g for g in top if all(abs(x) <= 1 for x in centroid(p, f[g])[:2])]
return p, f, centre[0]
def slab_sdf(h):
"""The SDF of a slab of thickness h from the formula: all 25 rays hit the far side, at the lengths h / cos(theta)."""
lengths = [h] + [h / math.cos(math.radians(a)) for a in (20, 40, 60) for _ in range(8)]
lengths.sort()
m = lengths[12]
s = math.sqrt(sum((x - sum(lengths) / 25) ** 2 for x in lengths) / 25)
kept = [x for x in lengths if abs(x - m) <= s]
return sum(kept) / len(kept)
def float_ray_triangle(o, d, a, b, c):
"""The same test as ray_triangle, in floating point."""
e1, e2 = sub(b, a), sub(c, a)
pv = cross(d, e2)
det = dot(e1, pv)
if det == 0:
return None
s = sub(o, a)
u = dot(s, pv) / det
if u < 0 or u > 1:
return None
qv = cross(s, e1)
v = dot(d, qv) / det
if v < 0 or u + v > 1:
return None
t = dot(e2, qv) / det
return t if t > 0 else None
def test_the_ray_triangle_test_is_exact_on_edges_and_vertices() -> None:
a, b, c = (0, 0, 0), (1, 0, 0), (0, 1, 0)
assert ray_triangle((Fraction(1, 2), Fraction(1, 2), 1), (0, 0, -1), a, b, c) == 1 # on the edge bc
assert ray_triangle((1, 0, 2), (0, 0, -1), a, b, c) == 2 # through the vertex b
assert ray_triangle((Fraction(1, 2), Fraction(1, 2) + Fraction(1, 10**30), 1), (0, 0, -1), a, b, c) is None
assert ray_triangle((0, 0, 1), (1, 0, 0), a, b, c) is None # parallel to the plane
assert ray_triangle((Fraction(1, 4), Fraction(1, 4), -1), (0, 0, -1), a, b, c) is None # the plane is behind
def test_a_ray_through_a_shared_edge_does_not_leak() -> None:
a = (0.07695759147568859, 0.24697890559501023, 0.22490492956545127)
b = (-0.08370639980055117, -0.9440500318323153, -0.5407899374459522)
c = (-0.6455774821228346, 0.16892174155688267, 0.7220177217066497)
o = (0.5968778811548521, 0.5941951252709925, 0.6328747411213818)
mid = tuple((x + y) / 2 for x, y in zip(b, c))
assert exact(mid) == tuple((Fraction(x) + Fraction(y)) / 2 for x, y in zip(b, c)) # mid is exactly on the edge bc
d = sub(mid, o)
assert exact(d) == tuple(Fraction(x) - Fraction(y) for x, y in zip(mid, o))
e = tuple(2 * m - x for m, x in zip(mid, a)) # abc and cbe share the edge bc
assert ray_triangle(o, d, a, b, c) == 1 and ray_triangle(o, d, c, b, e) == 1
assert float_ray_triangle(o, d, a, b, c) is None and float_ray_triangle(o, d, c, b, e) is None
def test_one_ray_gives_the_thickness_of_a_slab() -> None:
for h in (1, Fraction(1, 2), Fraction(3, 7)):
p, f, g = slab(h)
assert ray_lengths(p, f, g, rays=1) == [float(h)]
def test_the_sdf_of_a_slab_follows_the_formula() -> None:
for h in (1, Fraction(1, 2)):
p, f, g = slab(h)
lengths = ray_lengths(p, f, g)
assert len(lengths) == 25 # every ray reaches the bottom side
assert abs(shape_diameter(p, f, g) - slab_sdf(float(h))) < 1e-12
p, f, g = slab(1)
assert abs(shape_diameter(to_float(p), f, g) - slab_sdf(1.0)) < 1e-12 # float input, the same exact tests
def test_the_sdf_does_not_change_under_a_rational_rotation() -> None:
p, f, g = slab(1)
R1 = [[Fraction(3, 5), Fraction(-4, 5), 0], [Fraction(4, 5), Fraction(3, 5), 0], [0, 0, 1]]
R2 = [[1, 0, 0], [0, Fraction(5, 13), Fraction(-12, 13)], [0, Fraction(12, 13), Fraction(5, 13)]]
q = [tuple(mat_vec(R2, mat_vec(R1, x))) for x in p]
assert abs(shape_diameter(q, f, g) - slab_sdf(1.0)) < 1e-9
def test_rays_that_reach_a_face_from_outside_are_dropped() -> None:
p, f, g = slab(1)
bottom = {k for k in range(len(f)) if all(p[v][2] == Fraction(-1, 2) for v in f[k])}
flipped = [(a, c, b) if k in bottom else (a, b, c) for k, (a, b, c) in enumerate(f)]
assert ray_lengths(p, flipped, g) == []
assert shape_diameter(p, flipped, g) is None
def test_every_ray_of_a_cube_leaves_the_solid() -> None:
p, f = box_mesh((2, 2, 2), (2, 2, 2))
for g in range(0, len(f), 7):
lengths = ray_lengths(p, f, g)
assert len(lengths) == 25
assert all(0 < x <= math.sqrt(12) for x in lengths)
assert 0 < shape_diameter(p, f, g) < slab_sdf(2.0)
def test_the_normalization_keeps_the_order() -> None:
v = [0.3, 1.2, 0.5, 0.9, 0.3]
n = normalize(v)
assert n[0] == 0.0 and n[1] == 1.0
assert all((a < b) == (x < y) for a, x in zip(v, n) for b, y in zip(v, n))
assert normalize([2.0, 2.0]) == [0.0, 0.0]
History
Shapira, Shamir and Cohen-Or defined the shape diameter function in a paper in The Visual Computer in 2008. They cast a cone of rays inward from each face, removed the outlier lengths, and used the result for two tasks: a segmentation of meshes into parts by a Gaussian mixture and graph cuts, which gave the same parts for the same object in different poses, and the construction of skeletons. The ray-triangle test they relied on goes back to Möller and Trumbore (1997), and the graph cut step to the alpha-expansion of Boykov, Veksler and Zabih (2001). The function was later included in the CGAL library, with the segmentation, and became a common feature for the segmentation of meshes.
References
- Lior Shapira, Ariel Shamir and Daniel Cohen-Or, Consistent mesh partitioning and skeletonisation using the shape diameter function, The Visual Computer 24(4), 2008, 249 to 259, the definition of the shape diameter function, the cone of rays and the removal of outliers, the normalization, the soft clustering with a Gaussian mixture and the hard clustering with graph cuts, and the use of the function for skeletons
- Tomas Möller and Ben Trumbore, Fast, minimum storage ray-triangle intersection, Journal of Graphics Tools 2(1), 1997, 21 to 28, the ray-triangle test that solves for the distance and the barycentric coordinates with triple products, without the plane equation
- Yuri Boykov, Olga Veksler and Ramin Zabih, Fast approximate energy minimization via graph cuts, IEEE Transactions on Pattern Analysis and Machine Intelligence 23(11), 2001, 1222 to 1239, the alpha-expansion move, the graph cut that computes the best move, and the bound on the energy of a local minimum for a metric smoothness term
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 WRAPDK Edit this page History Report an error Markdown