Algorithmadvanced
Consistent normal orientation
Also called Hoppe normal orientation.
Orient the normals of a point cloud consistently by propagating along a minimum spanning tree of a neighbor graph weighted by how parallel the normals are.
- Time
- O(n^2 log n) worstO(n k log n) averageΩ(n k) best
- Space
- Θ(n k) extra
- Where
- k = the number of neighbors per point; n = the number of points
- Model
- Real RAM
- Properties
- deterministicnot exactheuristicinput sign invariantofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hugues Hoppe, Tony DeRose, Tom Duchamp, John McDonald, Werner Stuetzle, 1992
Consistent normal orientation chooses the sign of each normal of a point cloud so that neighboring normals point to the same side of the surface. Normal estimation by local plane fitting gives each normal only up to its sign, and a cloud with signs chosen at random is useless for shading, for surface reconstruction and for any method that needs an inside and an outside. The method of Hoppe and his coauthors (1992) builds a graph of near points, gives each edge a cost that is small when the two normals are close to parallel, and takes a minimum spanning tree of this graph. It fixes the sign at the highest point so that its normal points up, then walks the tree and flips each child normal that points against its parent. The tree prefers flat, smooth paths, where the sign decision is easy. The method is a heuristic: it can fail at thin parts and sharp edges.
In plain words
Each point has a normal, a short arrow that sticks out of the surface, but some arrows point out and some point in. You want them all to point out.
Start at the highest point of the cloud. Its arrow must point up to be on the outside, so turn it up if it points down. Then go to a near point. If its arrow points against the arrow you just fixed, turn it around. Keep going, from fixed points to near points, until every point is done.
The order of the walk matters. A step between two points on a flat part is safe, because their arrows are almost the same. A step across a sharp edge or between the two sides of a thin sheet is risky. So the walk goes along a tree that uses the safest steps first.
The problem
The input is a list of points in sampled from a surface, unit normals with arbitrary signs, and a neighborhood size . The output is a sign for each point, and the oriented normals .
The wanted output is the orientation of the true surface, for example the outward normals of a closed object. The surface is unknown, so this goal has no exact form. The method replaces it with a local rule: the normals of neighboring points should have a positive dot product. On a smooth, well-sampled surface the true orientation obeys this rule, but at a sharp edge or across a thin part it does not.
The algorithm
ORIENT-NORMALS(P, N, k)- 1
G ← the graph with the edges of the Euclidean MST of P and the edges to the k nearest neighbors - 2
give each edge (i, j) of G the cost 1 - |n_i · n_j| - 3
r ← the point of P with the largest z coordinate - 4
T ← a minimum spanning tree of G, grown by Prim's algorithm from r - 5
if n_r · e_z < 0 then n_r ← -n_r - 6
S ← a stack that holds r - 7
while S is not empty do - 8
i ← POP(S) - 9
for each child j of i in T do - 10
if n_i · n_j < 0 then n_j ← -n_j - 11
PUSH(S, j) - 12
return N
Line L1 builds what Hoppe and his coauthors call the Riemannian graph. The nearest neighbor edges connect points on the same part of the surface. The Euclidean minimum spanning tree edges make sure the graph is connected even when the cloud has gaps. Line L2 uses the absolute value, so the cost does not depend on the current signs: it is 0 for parallel or antiparallel normals and 1 for perpendicular ones. Line L3 picks a point whose outward normal is known: on a closed surface, the highest point has the normal . Line L4 is Prim's algorithm on the costs of line L2. Any minimum spanning tree method works, for example Kruskal's algorithm followed by a traversal. Lines L6 to L11 are a depth-first traversal of the tree. A child is handled after its parent is final, so line L10 compares it with a normal that will not change again.
Example
Take five points on the unit circle in the plane, at the angles 90°, 60°, 30°, 120° and 150°, numbered 0 to 4. The true outward normal of each point is the point itself. The input normals have the signs , and .
Neighbors on the arc are 30° apart, so their normals have and the cost . Points 60° apart have the cost . The graph has the edges 0-1, 1-2, 0-3 and 3-4 of cost , and 0-2 and 0-4 of cost . The tree takes the four cheap edges. The root is point 0, the highest.
| point | angle | input normal | parent | dot with parent | action | output |
|---|---|---|---|---|---|---|
| 0 | 90° | root | keep | |||
| 1 | 60° | 0 | flip | |||
| 2 | 30° | 1 | keep | |||
| 3 | 120° | 0 | keep | |||
| 4 | 150° | 3 | flip |
The four tree edges have the same cost up to rounding, so the order in which the stack handles the two branches depends on the last bits of the costs. The result does not: each branch only reads its own parents. Every output normal points away from the center of the circle. Point 4 is compared with the new normal of point 3, and point 2 with the new normal of point 1, never with an input normal.
Correctness
After the traversal, the root normal has and every child has a nonnegative dot product with its parent. Each point is pushed once, as a child of its parent, after the parent is final, so this holds on every tree edge. When no tree edge has a zero dot product, these conditions fix every sign, so the output does not depend on the input signs. If a true orientation agrees along every tree edge, the output equals it up to one global sign, and the sign is right when the true normal at the highest point points up. The tree is a minimum spanning tree for the cost , so it avoids edges where the normals turn fast. The full proof is below.
Nothing makes a true orientation agree along the tree. The guarantee is conditional, and the method is a heuristic.
Proof: The propagation makes the normals agree along every tree edge, and it recovers a true orientation whenever that orientation agrees along the treefull
Let the points be with unit normals of arbitrary signs. An orientation is a choice of signs , giving the normals . Write for the output normal of point .
Lemma 1 (a spanning tree). Lines L1 to L4 build a spanning tree of the points, rooted at the point of largest , that has the least total cost among the spanning trees of the Riemannian graph .
Proof. The graph of line L1 contains the edges of a Euclidean minimum spanning tree of all the points, so it is connected. Line L4 is Prim's algorithm from on with the costs of line L2, so it returns a minimum spanning tree of ; this is the cut property of minimum spanning trees. The cost of an edge does not change when either normal changes sign, because it uses . So does not depend on the input signs.
For a point let be its parent in .
Lemma 2 (agreement on tree edges). The output satisfies , for every , and for every .
Proof. Line L5 sets the sign of the root so that its component is at least zero, and the root is never changed later, because it is no child. Every other point is pushed on the stack exactly once, as a child of its parent at line L11, so line L10 runs exactly once for , after its parent was popped at line L8. At that time the parent's normal is final: the parent is changed only when it is handled as a child, which happened before it was pushed. Line L10 compares with zero and flips when it is negative, so afterwards the product is at least zero. Only signs change, so .
Lemma 3 (uniqueness). Suppose for every tree edge, and has a nonzero component. Then the output of Lemma 2 is the only orientation with the three properties of Lemma 2. In particular, the output does not depend on the input signs.
Proof. The sign at the root is fixed by . If the sign of the parent is fixed, the sign of a child is fixed by , since the product is nonzero and changes sign with . Induction over the depth in fixes every sign. By Lemma 1 the tree does not depend on the input signs, and the conditions only involve , so the output does not either.
Theorem (what the method guarantees). Let be a true orientation, for example the outward normals of a closed surface, and assume that for every edge of . Then the output is for all , with one global sign , and when the true normal at the root has a positive component.
Proof. The orientation , with chosen so that the root normal has , satisfies all three properties of Lemma 2: the product along each tree edge is . The hypothesis also gives on all tree edges. If the root normal has , line L5 keeps it, and the same induction as in Lemma 3 shows that the output is with the sign given at the root; otherwise Lemma 3 says the output is this orientation. On a closed surface the point of largest has the outward normal when the surface is smooth there, so .
What is not guaranteed. The hypothesis of the theorem is about the tree, and nothing forces it. If a tree edge joins two points whose true normals point in opposite directions, the method flips one side wrongly, and the error passes to the whole subtree below that edge. This happens on thin parts, where points of the two opposite sheets are near neighbors with parallel normals of cost 0, and at sharp edges, where the true normals of the two faces are near orthogonal and the sign test of line L10 decides on a product near zero. The cost makes the tree prefer paths over flat, smooth regions, which is why the method works well in practice, but it is a heuristic.
Complexity
The model is the real RAM, with points and neighbors per point. The graph has edges, because the minimum spanning tree adds only .
- Brute force. A dense Prim on all pairs gives the Euclidean MST in time. A scan of all points with a heap of size gives the nearest neighbors of one point in , so in total. Prim's algorithm with a binary heap on the graph costs . The traversal costs . The total is .
- With spatial search. A k-d tree finds the neighbors in on well-spread points. For such points the Euclidean MST can be taken from the Delaunay triangulation, or the MST edges can be left out when the nearest neighbor graph is already connected. Prim's algorithm then dominates, with .
- Space. for the graph, and for the tree and the stack.
Every edge of the graph is looked at once, so the time is at least .
Properties
- Input sign invariant. The costs, the tree and the root do not depend on the input signs, so the output is the same whatever signs come in, except when a tree edge has a zero dot product.
- Locally consistent. Neighbors along the tree have normals with a nonnegative dot product.
- Global sign from one point. The outward side comes from the highest point only. If that point lies on a sharp tip or on a noisy part, the whole result can come out inward.
- Error propagation. One wrong decision flips the whole subtree below it, often a large connected patch.
- Deterministic. With a fixed tie rule, the same input gives the same output.
Variants and improvements
- Viewpoint orientation. When the cloud comes from one sensor at a known position , flip each normal to face . This needs no graph, and it is right for every point the sensor saw. Clouds merged from many scans keep the sensor position of each point for this test.
- Graph without the EMST. Most libraries use only the nearest neighbor graph, or a radius graph, and orient each connected component on its own. This is faster, but a component can get a sign that disagrees with the rest.
- Other edge costs. The cost can also grow with the distance between the points or with the curvature, which keeps the tree away from edges and thin parts.
- Multiple roots. Start the traversal at several points whose orientation is known, such as the extreme points along each axis, and grow the trees together.
- Global methods. Other methods choose all signs together, for example by an energy over all graph edges or by making a signed distance field or a winding number field consistent. They cost more and handle thin parts and noise better.
- Orientation inside reconstruction. Some reconstruction methods take unoriented normals or none and find the inside and outside as part of the fit, which removes this step.
When to use it
Use propagation along a minimum spanning tree when the cloud has no sensor positions, the surface is smooth at the scale of the sampling, and the sampling is dense compared with the thickness of the thinnest part. This holds for many scans of single objects, and it is the usual step before Poisson surface reconstruction or a signed distance function fit. When the sensor positions are known, orient by the viewpoint. For thin sheets, sharp CAD models and very noisy clouds, use a global method or check the result.
Pitfalls
- Thin parts. At line L1 the nearest neighbors of a point on one side of a thin plate include points of the other side. Their normals are parallel, so line L2 gives the cost 0, the tree crosses the plate, and line L10 makes both sides point the same way. Choose small compared with the thickness, or downsample less.
- Sharp edges. Across a 90° edge the dot product at line L10 is near 0, and noise decides its sign. The cost of line L2 makes such edges expensive, but the tree must still cross the edge once to reach the other face.
- A bad root. Line L5 assumes that the highest point has a normal near . On a cloud with the highest point at a sharp tip, an open boundary or an outlier, the guess can be wrong and every normal comes out inward. Remove outliers first, or test the global sign afterwards.
- Comparing with the input normal. Line L10 must compare the child with the parent's final normal, not with the parent's input normal. A breadth-first or depth-first order over the tree does this. Flipping by a loop over the tree edges in an arbitrary order does not.
- A disconnected graph. Without the EMST edges of line L1, the nearest neighbor graph of a cloud with gaps has several components, and line L4 reaches only the component of the root. The other points keep their input signs.
- Signed costs. Using the cost at line L2, without the absolute value, makes the tree depend on the input signs and steers it toward edges whose input signs happen to agree.
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
# Part of https://algorithm.tamnd.com/consistent-normal-orientation/. The authors are listed in prov/4CA5PS.jsonl.
"""Consistent orientation of point cloud normals by propagation along a
minimum spanning tree (Hoppe, DeRose, Duchamp, McDonald and Stuetzle, 1992).
1. The Riemannian graph has the edges of the Euclidean minimum spanning tree
(EMST) of the points and the edges of the k-nearest neighbor graph.
2. The edge (i, j) has the cost 1 - |n_i . n_j|: small when the two normals
are close to parallel, whatever their signs.
3. A minimum spanning tree of this graph is taken, and rooted at the point of
largest z, whose normal is turned to have n_z >= 0.
4. A depth-first traversal from the root flips each child normal that points
against its parent's normal.
This is a heuristic: it is exact along the tree edges, but it can fail where
the tree crosses a thin part or a sharp edge.
The EMST is computed here by Prim's algorithm on the complete graph, O(n^2),
and the k nearest neighbors by a brute force scan.
"""
from __future__ import annotations
import heapq
import math
from typing import Dict, List, Sequence, Set, Tuple
Vec3 = Tuple[float, float, float]
def _dot(a: Sequence[float], b: Sequence[float]) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def emst_edges(points: Sequence[Sequence[float]]) -> List[Tuple[int, int]]:
"""The edges of a Euclidean minimum spanning tree, by dense Prim, O(n^2)."""
n = len(points)
if n == 0:
return []
inside = [False] * n
best = [math.inf] * n
parent = [-1] * n
best[0] = 0.0
edges = []
for _ in range(n):
u = min((i for i in range(n) if not inside[i]), key=lambda i: best[i])
inside[u] = True
if parent[u] >= 0:
edges.append((parent[u], u))
for v in range(n):
if not inside[v]:
d = math.dist(points[u], points[v])
if d < best[v]:
best[v], parent[v] = d, u
return edges
def riemannian_graph(points: Sequence[Sequence[float]], k: int) -> Dict[int, Set[int]]:
"""EMST edges plus the symmetric k-nearest neighbor edges."""
n = len(points)
adj: Dict[int, Set[int]] = {i: set() for i in range(n)}
for i, j in emst_edges(points):
adj[i].add(j)
adj[j].add(i)
for i in range(n):
others = heapq.nsmallest(k, (j for j in range(n) if j != i),
key=lambda j: math.dist(points[i], points[j]))
for j in others:
adj[i].add(j)
adj[j].add(i)
return adj
def orient_normals(points: Sequence[Sequence[float]], normals: Sequence[Sequence[float]],
k: int) -> List[Vec3]:
"""Return the normals with signs made consistent. The input normals are
unit vectors with arbitrary signs."""
n = len(points)
if n == 0:
return []
adj = riemannian_graph(points, k) # @line L1
weight = lambda i, j: 1.0 - abs(_dot(normals[i], normals[j])) # @line L2
# Prim's algorithm on the Riemannian graph, rooted at the highest point.
root = max(range(n), key=lambda i: (points[i][2], -i)) # @line L3
inside = [False] * n
children: List[List[int]] = [[] for _ in range(n)]
heap = [(0.0, root, -1)]
while heap: # @line L4
w, v, p = heapq.heappop(heap)
if inside[v]:
continue
inside[v] = True
if p >= 0:
children[p].append(v)
for u in adj[v]:
if not inside[u]:
heapq.heappush(heap, (weight(v, u), u, v))
# The EMST edges make the graph connected, so every point is now inside.
out: List[Vec3] = [tuple(m) for m in normals] # type: ignore[misc]
if out[root][2] < 0: # @line L5
out[root] = (-out[root][0], -out[root][1], -out[root][2])
stack = [root] # @line L6
while stack: # @line L7
i = stack.pop() # @line L8
for j in children[i]: # @line L9
if _dot(out[i], out[j]) < 0: # @line L10
out[j] = (-out[j][0], -out[j][1], -out[j][2])
stack.append(j) # @line L11
return out # @line L12
test_consistent_normal_orientation.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/consistent-normal-orientation/. The authors are listed in prov/4CA5PS.jsonl.
import math
import random
from collections import deque
from consistent_normal_orientation import emst_edges, orient_normals, riemannian_graph
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def kruskal(n, edges):
"""Minimum spanning tree by Kruskal with union-find. edges: (w, i, j)."""
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
tree = []
for w, i, j in sorted(edges):
a, b = find(i), find(j)
if a != b:
parent[a] = b
tree.append((w, i, j))
return tree
def oracle(points, normals, k):
"""Kruskal on the same graph, then breadth-first propagation."""
n = len(points)
adj = riemannian_graph(points, k)
edges = [(1.0 - abs(dot(normals[i], normals[j])), i, j) for i in adj for j in adj[i] if i < j]
tree = kruskal(n, edges)
nb = {i: [] for i in range(n)}
for _, i, j in tree:
nb[i].append(j)
nb[j].append(i)
root = max(range(n), key=lambda i: (points[i][2], -i))
out = [tuple(m) for m in normals]
if out[root][2] < 0:
out[root] = tuple(-x for x in out[root])
seen = {root}
queue = deque([root])
while queue:
i = queue.popleft()
for j in nb[i]:
if j not in seen:
seen.add(j)
if dot(out[i], out[j]) < 0:
out[j] = tuple(-x for x in out[j])
queue.append(j)
return out
def sphere(rng, n, r=1.0):
pts, nrm = [], []
for _ in range(n):
u = [rng.gauss(0, 1) for _ in range(3)]
lu = math.sqrt(dot(u, u))
u = [x / lu for x in u]
pts.append(tuple(r * x for x in u))
s = rng.choice([-1.0, 1.0])
nrm.append(tuple(s * x for x in u))
return pts, nrm
def test_example_arc() -> None:
ts = [math.radians(a) for a in (90, 60, 30, 120, 150)]
pts = [(math.cos(t), 0.0, math.sin(t)) for t in ts]
signs = [1, -1, 1, 1, -1]
nrm = [tuple(s * x for x in p) for s, p in zip(signs, pts)]
out = orient_normals(pts, nrm, 2)
for p, m in zip(pts, out):
assert all(abs(a - b) < 1e-12 for a, b in zip(p, m))
def test_sphere_becomes_outward() -> None:
rng = random.Random(31)
pts, nrm = sphere(rng, 120)
out = orient_normals(pts, nrm, 6)
assert all(dot(p, m) > 0 for p, m in zip(pts, out))
def test_plane_and_paraboloid() -> None:
rng = random.Random(32)
pts, nrm = [], []
for _ in range(80):
x, y = rng.uniform(-1, 1), rng.uniform(-1, 1)
z = 0.3 * (x * x - y * y)
g = (-0.6 * x, 0.6 * y, 1.0)
lg = math.sqrt(dot(g, g))
s = rng.choice([-1.0, 1.0])
pts.append((x, y, z))
nrm.append(tuple(s * c / lg for c in g))
out = orient_normals(pts, nrm, 6)
assert all(m[2] > 0 for m in out)
def test_matches_kruskal_oracle() -> None:
rng = random.Random(33)
for _ in range(5):
pts, nrm = sphere(rng, 60, r=rng.uniform(0.5, 2.0))
noisy = []
for m in nrm:
v = [x + rng.gauss(0, 0.05) for x in m]
lv = math.sqrt(dot(v, v))
noisy.append(tuple(x / lv for x in v))
assert orient_normals(pts, noisy, 5) == oracle(pts, noisy, 5)
def test_output_does_not_depend_on_input_signs() -> None:
rng = random.Random(34)
pts, nrm = sphere(rng, 50)
flipped = [tuple(-x for x in m) if rng.random() < 0.5 else m for m in nrm]
assert orient_normals(pts, nrm, 5) == orient_normals(pts, flipped, 5)
def test_emst_is_minimum() -> None:
rng = random.Random(35)
for _ in range(5):
pts = [tuple(rng.uniform(0, 1) for _ in range(3)) for _ in range(25)]
e = emst_edges(pts)
assert len(e) == 24
total = sum(math.dist(pts[i], pts[j]) for i, j in e)
allp = [(math.dist(pts[i], pts[j]), i, j) for i in range(25) for j in range(i + 1, 25)]
best = sum(w for w, _, _ in kruskal(25, allp))
assert abs(total - best) < 1e-12
def test_thin_plate_is_a_known_failure() -> None:
# Two sheets 0.05 apart, the top and the bottom of a thin plate. The true
# outward normals are +z on top and -z below, but every normal is
# parallel to every other, so propagation gives all of them one sign.
rng = random.Random(36)
top = [(rng.uniform(0, 1), rng.uniform(0, 1), 0.05) for _ in range(30)]
bottom = [(rng.uniform(0, 1), rng.uniform(0, 1), 0.0) for _ in range(30)]
nrm = [(0.0, 0.0, rng.choice([-1.0, 1.0])) for _ in range(60)]
out = orient_normals(top + bottom, nrm, 6)
assert all(m == (0.0, 0.0, 1.0) for m in out)
def test_edges() -> None:
assert orient_normals([], [], 3) == []
assert orient_normals([(0.0, 0.0, 1.0)], [(0.0, 0.0, -1.0)], 3) == [(0.0, 0.0, 1.0)]
History
Hoppe, DeRose, Duchamp, McDonald and Stuetzle (1992) reconstructed surfaces from unorganized points by a signed distance function to a set of tangent planes. The sign of the distance needs oriented planes, so they oriented the plane normals by propagation. They first used the Euclidean minimum spanning tree as the order of propagation, saw that it failed where the surface has thin or curved parts, and then added the nearest neighbor edges to form the Riemannian graph with the cost , rooting the tree at the point of largest . The method became the standard first step for orienting normals of unorganized clouds. Later work changed the graph and the costs, used the sensor positions when they are known, and replaced the local propagation with global optimization.
References
- Hugues Hoppe, Tony DeRose, Tom Duchamp, John McDonald and Werner Stuetzle, Surface reconstruction from unorganized points, Computer Graphics (Proceedings of SIGGRAPH 92) 26(2), 1992, 71-78, The consistent orientation of the tangent planes: the Riemannian graph of the Euclidean minimum spanning tree and the k nearest neighbor edges, the cost 1 - |n_i . n_j|, and the traversal of its minimum spanning tree from the point of largest z
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 4CA5PS Edit this page History Report an error Markdown