Algorithmcore
Spin images
Also called spin image descriptor.
Describe an oriented point by the 2D histogram of its neighbors' distance from the normal axis and height along it, invariant to rotation about the normal.
- Time
- O(n (n + W^2)) worstO(n (log n + k + W^2)) averageΩ(n (k + W^2)) best
- Space
- Θ(n W^2) extra
- Where
- W = the image width in cells; k = the number of points in the support region; n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactneeds normalsofflineiterativerigid motion invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrew E. Johnson, Martial Hebert, 1999
A spin image describes the shape of a surface around one point with a normal, an oriented point, by a small 2D picture. For every other point it records two numbers: , the distance from the line through the point along the normal, and , the height along that line. It then counts the points in a grid of cells, spreading each point over four cells by bilinear interpolation. The picture is what one would get by spinning a sheet of paper about the normal and letting the surface leave marks on it, hence the name. Johnson and Hebert (1999) introduced spin images for object recognition in cluttered 3D scenes. They are simple to compute and need only the normal of the point, not a full local frame; the price is that turning parts of the surface about the normal does not change the picture.
In plain words
Stand at a point of a surface and look along its normal. Every other point is at some distance from the normal line and at some height above or below the point. Forget in which direction around the line it lies, and keep only these two numbers. Then put a grid on the two numbers and count how many points fall in each cell, with a point near a cell border shared between the cells around it.
The grid is the spin image. If you turn the object or move it, the distances and heights stay the same, so the picture stays the same. Two points on two scans of the same object get similar pictures, which lets you find which points match.
The problem
The input is a cloud of points with unit normals, an oriented point , a bin size , an image width in cells and a support angle . The output is a array of nonnegative numbers that describes the cloud around , does not change when the cloud and the oriented point move together by a rotation and translation, and changes little when the points move a little. As for every local descriptor, there is no single correct output; the requirements are the invariance, the robustness to noise, clutter and occlusion, and the power to tell shapes apart.
The algorithm
SPIN-IMAGE(P, N, p, n, b, W, A)- 1
img ← a W × W array of zeros; β_max ← (W - 1) b / 2; α_max ← (W - 1) b - 2
for each point x of P, with normal n_x do - 3
if n · n_x < cos A then skip x - 4
β ← n · (x - p); α ← sqrt(‖x - p‖² - β²) - 5
if α > α_max or |β| > β_max then skip x - 6
u ← (β_max - β) / b; s ← α / b - 7
i ← ⌊u⌋; j ← ⌊s⌋; a ← u - i; c ← s - j - 8
add (1 - a)(1 - c) to img[i][j], a(1 - c) to img[i+1][j], (1 - a) c to img[i][j+1] and a c to img[i+1][j+1] - 9
return img
Line L4 is the spin map: is the height of along the normal, and is its distance from the normal line, the length of the part of orthogonal to . These are cylindrical coordinates about the normal line without the angle. Line L3 is the support angle test: a point whose normal turns away from by more than is likely on the other side of the object or a self occluding part, and it is left out. Line L5 is the support distance test, which keeps the description local. Line L6 puts in row 0 and in column 0, so that the rows go down as the height goes down. Lines L7 and L8 split the unit weight of the point over its four nearest cells, by how near the point is to each. At the far border of the grid one of the four cells is outside it, and its weight is then 0, so the code leaves it out.
The point is a point of the cloud and adds weight 1 at , . Images are compared by their correlation coefficient; Johnson and Hebert compare only the cells where both images have data, and combine the correlation with the number of such cells.
Example
Take with , the bin size , the width and the support angle . Then and . The cloud has six points:
| point | normal | angle to | cells and weights | ||
|---|---|---|---|---|---|
| 0° | : 1 | ||||
| 0° | : 1 | ||||
| 0° | , , , : 0.25 each | ||||
| 45° | : 0.6, : 0.4 | ||||
| 0° | out of support, | ||||
| 180° | out of support, angle above 60° |
The spin image, with row 0 at and column 0 at :
| row | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | |
| 0 | 0.25 | 0.25 | 0 | 0 | |
| 1 | 1.25 | 0.25 | 0 | 0 | |
| 0 | 0 | 0.6 | 0.4 | 0 | |
| 0 | 0 | 0 | 0 | 0 |
The entries sum to 4, the number of supported points. The point and any point would give the same contribution, because the image does not see the angle about the normal.
Correctness
By Pythagoras, is the distance from to the normal line and the height along it, and two points have the same exactly when a rotation about the normal line maps one to the other. A rigid motion of the cloud together with the oriented point keeps , and , so the same points pass lines L3 and L5 with the same coordinates, and the image does not change. The bilinear weights of line L8 are nonnegative and sum to 1, and each cell gets the product of two tent functions, so the entries sum to the number of supported points and change continuously as a supported point moves. The full proof is below.
Proof: A spin image counts each supported point with total weight 1, in the cells around its cylindrical coordinates, and does not change under rigid motionsfull
Fix the oriented point with , the bin size , the width and the support angle . Let and . For a point with normal , write . A point is supported when it passes the tests of lines L3 and L5: , and . The tent is .
Lemma 1 (the coordinates). With and as in line L4, is the signed height of along the line , and is the distance from to . Two points have the same if and only if a rotation about maps one to the other.
Proof. Write with . By Pythagoras, , so , and the square root is real. The nearest point of to is , at distance . A rotation about fixes and and turns in the plane orthogonal to , so it keeps and . Conversely, two vectors and of the same length in that plane differ by a rotation about , which maps to when the heights are also equal.
Lemma 2 (bilinear weights). For a supported point, let and as in line L6. Then , and lines L7 and L8 add to every cell of the grid and nothing else. These amounts are nonnegative and their sum over the grid is 1.
Proof. From follows , and from follows . Line L7 sets and . If , then , both rows and are in the grid, and , , and for every other row, since there. If , then , , row gets , and row is outside the grid but its weight is 0, so leaving it out loses nothing; every other row has . The same holds for the columns with and . Line L8 adds the product of a row weight and a column weight to the four cells, so cell gets . The row weights sum to and the column weights to 1, so the four products sum to 1, and all are nonnegative.
Theorem 1 (the image). The image of line L9 has, in cell , the value over the supported points . Its entries are nonnegative and sum to the number of supported points.
Proof. Line L1 starts from zeros, and line L2 visits every point once. Lines L3 and L5 skip exactly the points that are not supported, and by Lemma 2 each supported point adds to each cell, with total 1. Summing over the points gives the claim.
Theorem 2 (invariance). Let with a rotation. Move every point to , every normal to , and the oriented point to . Then the spin image does not change. In particular, a rotation of the cloud about the line , which fixes and , does not change it.
Proof. The offset becomes . Since , the new height is , the new length is , so is the same, and the normal test uses . So the same points are supported, with the same and , and Theorem 1 gives the same image. A rotation about is the case and .
What the image does not keep. By Lemma 1, the image forgets the angle of each point about . So two surfaces that differ by turning parts of them about by different angles can give the same image, and this is the price of the invariance. The weights are continuous in the point positions, so a small move of a point that stays supported gives a small change of the image. The support tests are not continuous: a point that crosses the support angle or the edge of the support region adds or removes up to 1 at the border of the image, and this is why a small support angle and a support region that is not too large make the image less sensitive to clutter and self occlusion.
Complexity
The model is the real RAM, with points, an image of cells, and points in the support region of a point.
- One image. Line L1 costs . By brute force, lines L2 to L8 cost . With a k-d tree and a range query for the ball of radius , they cost on average on well spread points.
- All points. by brute force and with a tree.
- Space. for one image, to keep the images of all points for matching.
- Matching. Comparing two images costs . Johnson and Hebert compress the images of a model with principal component analysis to make the search for the best match faster.
Properties
- Rigid motion invariant. The image depends only on distances and dot products with the normal.
- Needs only a normal. No full local reference frame is needed, unlike SHOT; the normal line has no sign problem about its own axis.
- Loses the angle. Turning parts of the surface about the normal line does not change the image, so some different shapes look the same.
- Depends on the normal sign. Flipping flips the image upside down; the normals must be oriented consistently.
- Not scale invariant. The bin size sets the scale, and two scans must use the same one.
- Depends on sampling density. The counts grow with the density; the original works on meshes with a uniform resolution, and the correlation coefficient removes a global scale of the counts.
Variants and improvements
- Mesh resampling. The original resamples the mesh to an even resolution and sets the bin size near that resolution, so that counts on two scans are comparable.
- Compressed spin images. Projecting the images on their principal components gives short vectors for a fast nearest neighbor search.
- Face based spin images. Spreading the area of each mesh face, not its vertices, over the image makes it less dependent on the sampling.
- Learned and frame based descriptors. FPFH and SHOT keep more of the shape and are now more common baselines.
When to use it
Use spin images for 3D keypoint matching when the normals are reliable but a full local frame is not, for example on surfaces with near symmetric patches, and when a simple, well understood descriptor is enough. They are a classic choice for object recognition in range data and for the coarse alignment before ICP. On scans with very different densities, or when the patches are rich in detail, FPFH or SHOT usually match better.
Pitfalls
- Missing support angle. Without line L3, points on the back of a thin object, with normals that point away, fall in the image and make it depend on the view.
- Unoriented normals. Line L4 uses the sign of . Normals from PCA have random signs, and an image from a flipped normal is the original upside down, so orient the normals first.
- Rows and columns swapped. Line L6 sets rows by and columns by . Mixing them up still gives an image, but one that does not match images from other code.
- Cells out of the grid. At or , line L8 refers to a row or column outside the grid. Its weight is 0, but the code must check the index, not write past the end of the array.
- Bin size against density. With a bin size much smaller than the point spacing, line L8 gives a sparse, noisy image; with a much larger one, all detail is lost.
- Negative values under the root. Rounding can make slightly negative at line L4 when is on the normal line. Clamp it to 0.
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/spin-images/. The authors are listed in prov/9YPF70.jsonl.
"""Spin images, after Johnson and Hebert (1999).
An oriented point (p, n) gives every point x two cylindrical coordinates:
beta = n . (x - p) the height along the normal,
alpha = sqrt(|x - p|^2 - beta^2) the distance from the normal line.
The spin image is the 2D histogram of (alpha, beta) over the points x whose
normal makes an angle at most the support angle with n. The image has
width x width cells of size bin_size. Rows run from beta = +beta_max (row 0)
down to -beta_max, and columns from alpha = 0 to alpha_max, with
beta_max = (width - 1) * bin_size / 2, alpha_max = (width - 1) * bin_size,
so the cell centers are at the grid nodes. Each point spreads its unit
weight over the four cells around it by bilinear interpolation. A point
with alpha > alpha_max or |beta| > beta_max is out of support.
The point p itself is a point of the cloud and adds its weight at alpha = 0,
beta = 0, as in the original, where every mesh vertex is counted.
"""
from __future__ import annotations
import math
from typing import List, Optional, Sequence, Tuple
Image = List[List[float]]
def spin_coordinates(p: Sequence[float], n: Sequence[float], x: Sequence[float]) -> Tuple[float, float]:
"""The (alpha, beta) coordinates of x in the spin basis of (p, n)."""
d = [x[0] - p[0], x[1] - p[1], x[2] - p[2]]
beta = n[0] * d[0] + n[1] * d[1] + n[2] * d[2]
alpha = math.sqrt(max(0.0, d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - beta * beta))
return alpha, beta
def spin_image(points: Sequence[Sequence[float]], normals: Sequence[Sequence[float]],
p: Sequence[float], n: Sequence[float], bin_size: float, width: int,
support_angle_degrees: float = 60.0) -> Image:
"""The width x width spin image of the oriented point (p, n), with unit n."""
if bin_size <= 0 or width < 2:
raise ValueError("bin_size must be positive and width at least 2")
img = [[0.0] * width for _ in range(width)] # @line L1
beta_max = (width - 1) * bin_size / 2.0
alpha_max = (width - 1) * bin_size
min_cos = math.cos(math.radians(support_angle_degrees))
for x, nx in zip(points, normals): # @line L2
if n[0] * nx[0] + n[1] * nx[1] + n[2] * nx[2] < min_cos: # @line L3
continue
alpha, beta = spin_coordinates(p, n, x) # @line L4
if alpha > alpha_max or abs(beta) > beta_max: # @line L5
continue
u = (beta_max - beta) / bin_size # @line L6
s = alpha / bin_size
i, j = min(width - 1, int(u)), min(width - 1, int(s)) # @line L7
a, c = u - i, s - j
for di, wi in ((0, 1.0 - a), (1, a)): # @line L8
for dj, wj in ((0, 1.0 - c), (1, c)):
if i + di < width and j + dj < width:
img[i + di][j + dj] += wi * wj
return img # @line L9
def correlation(a: Image, b: Image) -> Optional[float]:
"""The Pearson correlation of two images of the same size, over all
cells, or None when one image is constant."""
xs = [v for row in a for v in row]
ys = [v for row in b for v in row]
if len(xs) != len(ys):
raise ValueError("images of different sizes")
m = len(xs)
mx, my = sum(xs) / m, sum(ys) / m
sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
sxx = sum((x - mx) ** 2 for x in xs)
syy = sum((y - my) ** 2 for y in ys)
if sxx == 0 or syy == 0:
return None
return sxy / math.sqrt(sxx * syy)
test_spin_images.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spin-images/. The authors are listed in prov/9YPF70.jsonl.
import math
import random
import pytest
from spin_images import correlation, spin_coordinates, spin_image
def unit(v):
length = math.sqrt(sum(x * x for x in v))
return [x / length for x in v]
def rotation(rng):
w, x, y, z = unit([rng.gauss(0, 1) for _ in range(4)])
return (
(1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)),
(2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)),
(2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)),
)
def axis_rotation(axis, angle):
"""Rodrigues' rotation about a unit axis."""
x, y, z = axis
c, s, t = math.cos(angle), math.sin(angle), 1 - math.cos(angle)
return (
(t * x * x + c, t * x * y - s * z, t * x * z + s * y),
(t * x * y + s * z, t * y * y + c, t * y * z - s * x),
(t * x * z - s * y, t * y * z + s * x, t * z * z + c),
)
def apply(R, v, t=(0.0, 0.0, 0.0)):
return [sum(R[r][c] * v[c] for c in range(3)) + t[r] for r in range(3)]
def surface(rng, n):
pts, nrm = [], []
for _ in range(n):
x, y = rng.uniform(-2, 2), rng.uniform(-2, 2)
pts.append([x, y, 0.2 * x * x - 0.1 * y * y + 0.05 * x * y])
nrm.append(unit([-(0.4 * x + 0.05 * y), -(-0.2 * y + 0.05 * x), 1.0]))
return pts, nrm
def close(a, b, tol=1e-9):
return all(abs(u - v) < tol for ra, rb in zip(a, b) for u, v in zip(ra, rb))
def example():
pts = [[0, 0, 0], [1, 0, 0], [0, 1.5, 0.5], [-2.4, 0, -1], [3, 4, 0], [0.5, 0, 0]]
nrm = [[0, 0, 1], [0, 0, 1], [0, 0, 1], unit([1, 0, 1]), [0, 0, 1], [0, 0, -1]]
return pts, nrm
def test_example() -> None:
pts, nrm = example()
img = spin_image(pts, nrm, (0, 0, 0), (0, 0, 1), 1.0, 5, 60.0)
expected = [
[0, 0, 0, 0, 0],
[0, 0.25, 0.25, 0, 0],
[1, 1.25, 0.25, 0, 0],
[0, 0, 0.6, 0.4, 0],
[0, 0, 0, 0, 0],
]
assert close(img, expected)
al, be = spin_coordinates((0, 0, 0), (0, 0, 1), (-2.4, 0, -1))
assert abs(al - 2.4) < 1e-12 and be == -1
def test_weights_sum_to_the_accepted_points() -> None:
rng = random.Random(71)
pts, nrm = surface(rng, 300)
for i in range(10):
img = spin_image(pts, nrm, pts[i], nrm[i], 0.25, 9, 60.0)
accepted = 0
for x, nx in zip(pts, nrm):
if sum(a * b for a, b in zip(nrm[i], nx)) < math.cos(math.radians(60)):
continue
al, be = spin_coordinates(pts[i], nrm[i], x)
if al <= 2.0 and abs(be) <= 1.0:
accepted += 1
assert abs(sum(map(sum, img)) - accepted) < 1e-9
assert min(min(row) for row in img) >= 0
def oracle(points, normals, p, n, b, w, angle):
"""Tent-function form of bilinear binning, cell by cell."""
bmax, amax = (w - 1) * b / 2, (w - 1) * b
img = [[0.0] * w for _ in range(w)]
for x, nx in zip(points, normals):
if sum(u * v for u, v in zip(n, nx)) < math.cos(math.radians(angle)):
continue
d = [x[k] - p[k] for k in range(3)]
be = sum(n[k] * d[k] for k in range(3))
al = math.sqrt(max(0.0, sum(t * t for t in d) - be * be))
if al > amax or abs(be) > bmax:
continue
for r in range(w):
for c in range(w):
wr = max(0.0, 1 - abs((bmax - be) / b - r))
wc = max(0.0, 1 - abs(al / b - c))
img[r][c] += wr * wc
return img
def test_matches_oracle() -> None:
rng = random.Random(72)
pts, nrm = surface(rng, 200)
for i in range(8):
a = spin_image(pts, nrm, pts[i], nrm[i], 0.3, 8, 70.0)
b = oracle(pts, nrm, pts[i], nrm[i], 0.3, 8, 70.0)
assert close(a, b)
def test_rigid_motion_invariance() -> None:
rng = random.Random(73)
pts, nrm = surface(rng, 250)
R = rotation(rng)
t = (3.0, -1.0, 2.0)
mp = [apply(R, p, t) for p in pts]
mn = [apply(R, m) for m in nrm]
for i in range(8):
a = spin_image(pts, nrm, pts[i], nrm[i], 0.25, 10, 60.0)
b = spin_image(mp, mn, mp[i], mn[i], 0.25, 10, 60.0)
assert close(a, b)
def test_rotation_about_the_normal_moves_only_the_cloud() -> None:
# Rotating the cloud about the normal line of p, with p and n fixed,
# does not change the image of p.
rng = random.Random(74)
pts, nrm = surface(rng, 250)
p, n = pts[0], nrm[0]
R = axis_rotation(n, 1.234)
mp = [[a + b for a, b in zip(apply(R, [q[k] - p[k] for k in range(3)]), p)] for q in pts]
mn = [apply(R, m) for m in nrm]
assert close(spin_image(pts, nrm, p, n, 0.3, 9), spin_image(mp, mn, p, n, 0.3, 9))
def test_flipping_the_normal_reverses_the_rows() -> None:
rng = random.Random(75)
pts, nrm = surface(rng, 200)
p, n = pts[3], nrm[3]
a = spin_image(pts, nrm, p, n, 0.3, 9, 180.0)
b = spin_image(pts, nrm, p, [-v for v in n], 0.3, 9, 180.0)
assert close(a, b[::-1])
def test_support() -> None:
pts, nrm = example()
# Point 5 has an opposite normal: a support angle of 180 degrees takes it.
wide = spin_image(pts, nrm, (0, 0, 0), (0, 0, 1), 1.0, 5, 180.0)
narrow = spin_image(pts, nrm, (0, 0, 0), (0, 0, 1), 1.0, 5, 60.0)
assert abs(sum(map(sum, wide)) - sum(map(sum, narrow)) - 1) < 1e-12
assert abs(wide[2][0] - narrow[2][0] - 0.5) < 1e-12
# Point 4 has alpha = 5 > alpha_max = 4. A width of 7 gives alpha_max = 6 and takes it.
big = spin_image(pts, nrm, (0, 0, 0), (0, 0, 1), 1.0, 7, 60.0)
assert abs(sum(map(sum, big)) - 5) < 1e-12
def test_correlation() -> None:
rng = random.Random(76)
pts, nrm = surface(rng, 200)
a = spin_image(pts, nrm, pts[0], nrm[0], 0.3, 8)
assert abs(correlation(a, a) - 1) < 1e-12
assert abs(correlation(a, [[2 * v + 1 for v in row] for row in a]) - 1) < 1e-12
assert correlation(a, [[0.0] * 8 for _ in range(8)]) is None
with pytest.raises(ValueError):
correlation(a, [[0.0]])
def test_edges() -> None:
assert spin_image([], [], (0, 0, 0), (0, 0, 1), 1.0, 3) == [[0.0] * 3 for _ in range(3)]
with pytest.raises(ValueError):
spin_image([], [], (0, 0, 0), (0, 0, 1), 0.0, 3)
with pytest.raises(ValueError):
spin_image([], [], (0, 0, 0), (0, 0, 1), 1.0, 1)
History
Andrew Johnson developed spin images in his 1997 thesis at Carnegie Mellon, with Martial Hebert, for matching surfaces from range sensors. Johnson and Hebert (1999) gave the method its best known form: the spin map to , the bin size, image width and support angle as parameters, bilinear binning, a similarity measure built on the correlation coefficient, compression of the model images by principal component analysis, and a recognition pipeline that groups point matches by geometric consistency and checks each pose with ICP. The name comes from the picture of a sheet of paper spinning about the normal. Spin images were among the first local 3D descriptors in wide use, and they are still a standard baseline, next to the later point feature histograms and SHOT, and they are part of the Point Cloud Library.
References
- Andrew E. Johnson and Martial Hebert, Using spin images for efficient object recognition in cluttered 3D scenes, IEEE Transactions on Pattern Analysis and Machine Intelligence 21(5), 1999, The spin map to the coordinates alpha and beta, the bin size, image width and support angle, the bilinear binning, the comparison of spin images, and the recognition pipeline
- Andrew E. Johnson, Spin-images: a representation for 3-D surface matching, PhD thesis, Carnegie Mellon University, 1997, The full account of the representation and of its parameters
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 9YPF70 Edit this page History Report an error Markdown