Algorithmadvanced
SHOT descriptor
Also called signature of histograms of orientations.
A 3D descriptor that builds a repeatable local reference frame from the neighbor covariance and histograms normal angles in a spherical grid around it.
- Time
- O(n^2) worstO(n (log n + k)) averageΩ(n k) best
- Space
- Θ(n + k) extra
- Where
- k = the number of neighbors within the radius; n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactneeds normalsofflineiterativerigid motion invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Federico Tombari, Samuele Salti, Luigi Di Stefano, 2010
The SHOT descriptor (signature of histograms of orientations) describes the shape of a point cloud around one point by 352 numbers, for matching points between scans or between a model and a scene. Tombari, Salti and Di Stefano (2010) built it in two steps. First, a local reference frame: three axes at the point, computed from the neighbors alone, so that the same surface patch gets the same axes in any scan. The axes are the eigenvectors of a distance weighted covariance matrix of the neighbors around the point, with a sign rule that makes each axis point to the side with more neighbors. Second, a grid: the sphere around the point is cut, in this frame, into 32 volumes, and each volume holds a histogram of the angles between the neighbors' normals and the frame's axis. The frame makes the descriptor invariant to rotations, and the grid keeps where on the patch each normal sits. SHOT is more discriminative than FPFH and spin images on many benchmarks, at the cost of a longer vector and a frame that can be unstable on symmetric patches.
In plain words
To compare a patch of one scan with a patch of another, you first need a common way to hold them. SHOT finds three directions on each patch from its own shape: the direction in which the patch spreads most, the direction in which it spreads least, and a third one at right angles to both. Each direction gets its sign from the side that has more points. Two copies of the same patch, turned in any way, get the same three directions.
Then it cuts the ball around the point into 32 pieces, like the slices of an orange, cut again into an upper and a lower half and into an inner and an outer part. In each piece it counts how much the surface normals tilt away from the main direction. The 32 small counts, one after the other, are the description.
The problem
The input is a cloud of points with unit normals, a feature point and a radius . The output is a vector of 352 numbers with unit length, such that patches of the same shape give close vectors, patches of different shapes give distant ones, and a rotation and translation of the cloud do not change the vector. As for every local descriptor, there is no single correct output; the requirements are invariance, repeatability under noise and a change of sampling, and the power to tell shapes apart.
The algorithm
SHOT(P, N, p, R)- 1
Q ← the points q_i of P with 0 < ‖q_i - p‖ < R, and d_i ← ‖q_i - p‖ - 2
M ← Σ_i (R - d_i)(q_i - p)(q_i - p)ᵀ / Σ_i (R - d_i) - 3
(x⁺, y⁺, z⁺) ← the unit eigenvectors of M for its largest, middle and smallest eigenvalue - 4
x ← ±x⁺, with the sign for which more of the q_i - p have a positive projection - 5
z ← ±z⁺ by the same rule; y ← z × x - 6
h ← 352 zeros - 7
for each q_i in Q do - 8
(a, b, c) ← ((q_i - p) · x, (q_i - p) · y, (q_i - p) · z) - 9
v ← the volume of (a, b, c): one of 8 azimuth sectors, 2 halves by the sign of c, and 2 shells split at R/2 - 10
k ← the bin of n_i · z among 11 equal bins of [-1, 1] - 11
h[11 v + k] ← h[11 v + k] + 1 - 12
return h / ‖h‖
Lines L1 to L5 build the local reference frame. Unlike the covariance of normal estimation, the matrix of line L2 is centered at the feature point , not at the centroid, and each neighbor has the weight , so that far points, which are the first to change with clutter, count less. The axis plays the part of the normal, and is the direction of largest spread. Lines L4 and L5 fix the signs: each axis points to the side that holds more of the neighbors. The code breaks a tie in the counts by the sign of the sum of the projections.
Lines L6 to L11 fill the signature. The volume of line L9 comes from the azimuth , cut in sectors of 45°, the sign of the elevation , and whether the distance is below . Line L10 bins the cosine, not the angle: equal steps of the cosine are coarse near the axis and fine near the tangent plane, where small changes of the normal matter more. The original method then spreads each count over the neighboring bins and volumes by quadrilinear interpolation, which makes the descriptor less sensitive to points near cell borders; the code below bins each count in one cell. Line L12 makes the vector a unit vector, so that point density does not change it much.
Example
Take , and five neighbors on the surface , with the surface normals. The weighted covariance of line L2 gives the frame, to four places:
| axis | vector |
|---|---|
The axis is close to the surface normal at , tilted a little because the neighbors are not spread evenly. Then each neighbor goes to its cell:
| neighbor | local | distance | azimuth | volume | bin | entry | |
|---|---|---|---|---|---|---|---|
| 1.020 | 326.7° | 31 | 0.965 | 10 | 351 | ||
| 0.503 | 145.8° | 14 | 0.949 | 10 | 164 | ||
| 0.803 | 55.9° | 6 | 0.987 | 10 | 76 | ||
| 0.400 | 236.7° | 22 | 0.984 | 10 | 252 | ||
| 0.855 | 11.1° | 2 | 0.992 | 10 | 32 |
For the first neighbor, the azimuth 326.7° is in sector 7, the elevation is positive, so the half is 1, and the distance 1.020 is above , so the shell is 1: the volume is , and the entry is . All normals are within 20° of , so every count falls in the last cosine bin. The five entries get 1 each, and line L12 scales them to .
Correctness
The matrix of line L2 is symmetric and positive semidefinite, and a rigid motion turns it into . When its three eigenvalues are distinct, its eigenvectors are fixed up to sign and move with the cloud. The sign rule of lines L4 and L5 gives the same axis whichever sign the eigenvalue solver returns, as long as the neighbors are not balanced on the two sides of the axis. Then is an orthonormal right handed frame that depends only on the neighborhood and moves with it, so every neighbor has the same local coordinates and the same cosine after the motion, and the descriptor does not change, up to values that lie exactly on cell borders. Each neighbor adds to exactly one of the 352 entries. The full proof is below.
Proof: The SHOT reference frame is orthonormal and moves with the cloud, so the descriptor is invariant under rigid motionsfull
Fix the feature point , the radius , and the neighbors of line L1, with offsets and distances , , and . A rigid motion here is with a rotation, and ; it acts on points by this map and on normals by .
Lemma 1 (the matrix). The matrix of line L2 is symmetric and positive semidefinite. Under a rigid motion it becomes .
Proof. Each weight is positive, so is a positive combination of the matrices , each symmetric with . A rigid motion keeps distances, so the neighbor set and the weights stay the same, and it maps to , because the translation cancels in the difference. So becomes .
By the spectral theorem, has an orthonormal basis of eigenvectors. When its three eigenvalues are distinct, each eigenvector is fixed up to its sign, and the eigenvectors of are , , .
The sign rule of lines L4 and L5 compares, for an axis , the number of offsets with and the number with , and keeps if the first is larger, or flips it if the second is larger. If the counts are equal, it flips when and keeps it otherwise. Call the axis decided when the two counts differ or the sum of the projections is not 0. Both conditions are the same for and .
Lemma 2 (the sign rule). Let be the result of the sign rule for an axis and the offsets . If is decided, then , and the rule applied to and the offsets returns .
Proof. Replacing by swaps the two counts and negates the sum. If the counts differ, the larger count moves to the other side, so the rule flips exactly when it keeps , and both give the same vector. If the counts are equal and the sum is not 0, the sum changes sign, and the same argument applies. The projections are the same for the moved data, so the rule makes the same choice, and returns .
An axis that is not decided has a neighborhood that is balanced on the two sides of the plane orthogonal to it. The rule then keeps the sign from the eigenvalue solver, and no rule that uses only the projections can do better, because these projections give the same counts and the same sum for both signs.
Theorem 1 (the frame). Suppose has three distinct eigenvalues and the axes and are decided. Then the frame of lines L3 to L5 is orthonormal and right handed, it depends only on and the neighbors (not on the signs returned by the eigenvalue solver), and under a rigid motion it becomes .
Proof. and are unit eigenvectors for different eigenvalues of a symmetric matrix, so they are orthogonal. Then is a unit vector orthogonal to both, and , so the frame is right handed. The eigenvectors are fixed up to sign, and by Lemma 2 the sign rule gives the same and from either sign, so the frame does not depend on the solver. Under a rigid motion, the eigenvectors become and by Lemma 1, and Lemma 2 gives and . Since is a rotation, .
Theorem 2 (the descriptor). Under the assumptions of Theorem 1, the following hold.
- Each neighbor adds 1 to exactly one of the 352 entries, so before the scaling at line L12 the entries sum to , and the result has unit Euclidean norm.
- Under a rigid motion, every neighbor has the same local coordinates and the same cosine, so the descriptor is unchanged, except for a value that lies exactly on a cell border, where rounding can move it to the next cell.
Proof. (1) The volume index of line L9 is with a sector , a half and a shell , so it is an integer in , and each triple gives a different index. The bin of line L10 is in . So is a one to one map onto , and line L11 adds 1 to one entry. With the vector is not zero, and line L12 divides it by its norm.
(2) By Theorem 1 the moved frame is , and the moved offset is , so the local coordinates are , and the same for and . The moved normal is , and . The distance, the azimuth, the sign of the elevation and the cosine are functions of these numbers, so every neighbor lands in the same cell, and the descriptor is the same.
What the assumptions exclude. If two eigenvalues of are equal, as on a symmetric neighborhood, the eigenvectors in their eigenspace can be any orthonormal pair, and the frame, and so the descriptor, is not repeatable. If an axis is not decided, its sign is arbitrary. These are properties of the neighborhood, not of the procedure; they are the main source of error of SHOT on real data, together with noise near cell borders, which the quadrilinear interpolation of the original method softens.
Complexity
The model is the real RAM, with points in the cloud and neighbors within the radius.
- One descriptor. The neighbor search costs by brute force, or on average with a k-d tree on well-spread points. Line L2 costs , line L3 is a eigenproblem, , and lines L7 to L11 cost . Line L12 costs .
- All points. by brute force and with a tree.
- Space. for the neighbors and for one descriptor, plus the tree.
In practice SHOT is computed at a few thousand keypoints, not at every point.
Properties
- Rigid motion invariant. As long as the frame is defined, a rotation and translation of the cloud leave the descriptor unchanged.
- Unique frame, when it exists. The frame has no free choice, unlike frames that fix only the normal and leave the rotation about it open.
- Unstable on symmetric patches. On a plane, a sphere or a cylinder two eigenvalues are equal or close, and the axis can turn freely; the descriptor is then not repeatable.
- Not scale invariant. The radius sets the size of the patch.
- Long. 352 values, against 33 for FPFH, which makes matching slower and memory larger.
- Sensitive to normal signs. Flipping a neighbor's normal moves its count to the mirror bin. Orient the normals first, or use the absolute cosine.
Variants and improvements
- Color SHOT. The journal version adds a second signature of color differences in the same grid, for scans with color.
- Interpolation. The original spreads each count over the neighboring cosine bins, azimuth sectors, halves and shells, which the code here leaves out.
- Better sign rules. Later work fixes the signs of the axes with more robust rules, for example from the points nearest to the median projection, which helps on balanced neighborhoods.
- Other frames. The frame of line L2 to L5 is used by other descriptors too, such as rotational projection statistics; other frames use the normal and a single dominant direction.
- Learned descriptors. Networks trained on scans give more discriminative descriptors and are slower and depend on their training data.
When to use it
Use SHOT for 3D keypoint matching in object recognition and in the coarse registration of scans, when the surfaces have enough detail to fix the frame. It needs normals and a radius large enough to see a distinctive part of the shape, but small enough to avoid clutter. For fast registration of clean scans, FPFH is cheaper. For clouds of simple shapes such as planes and cylinders, a local descriptor has little to work with: detect the shapes instead.
Pitfalls
- Centroid in place of the point. Line L2 is centered at , not at the centroid of the neighbors. Using the centroid changes the frame and makes it depend more on the sampling.
- Eigenvalue order. Line L3 needs for the largest eigenvalue and for the smallest. Solvers return them in different orders; a mix-up gives a frame that is still orthonormal but not the SHOT frame.
- Signs from the solver. Skipping lines L4 and L5 leaves signs that change from one run to the next or between two scans. The descriptor then fails to match even on identical data.
- Left-handed frame. Setting by its eigenvector at line L5, in place of , gives a reflected frame for about half of the points. The descriptor then confuses a shape with its mirror image.
- Balanced neighborhoods. When the counts of line L4 are tied, the sign is decided by noise. On a symmetric patch this happens often; check the gap between the counts and drop keypoints with a small gap.
- The point itself. Line L1 excludes , which has distance 0 and adds nothing to , but it would add a count to the histograms.
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 computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.
A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.
Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
1e-8.
This module holds no algorithm of a computer vision page.
"""
from __future__ import annotations
import cmath
import math
from typing import List, Sequence, Tuple
Matrix = List[List[float]]
Vector = List[float]
_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100
# ---------------------------------------------------------------- basics
def zeros(m: int, n: int) -> Matrix:
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n: int) -> Matrix:
"""The n x n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a) -> bool:
return len(a) > 0 and isinstance(a[0], (list, tuple))
def transpose(a: Sequence[Sequence[float]]) -> Matrix:
"""The transpose of a matrix."""
return [list(col) for col in zip(*a)]
def add(a, b):
"""a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, c):
"""c times a, for a vector or a matrix a and a number c."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
"""The matrix product a b."""
if len(a[0]) != len(b):
raise ValueError("mul: shapes do not match")
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
"""The product a x of a matrix and a vector."""
if len(a[0]) != len(x):
raise ValueError("matvec: shapes do not match")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x: Sequence[float], y: Sequence[float]) -> float:
"""The inner product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(a) -> float:
"""The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
if _is_matrix(a):
return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
return math.sqrt(sum(float(x) * float(x) for x in a))
def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
"""The cross product a x b of two 3-vectors."""
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 skew(a: Sequence[float]) -> Matrix:
"""The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
z = a[0] - a[0]
return [[z, -a[2], a[1]],
[a[2], z, -a[0]],
[-a[1], a[0], z]]
# ---------------------------------------------------- Gaussian elimination
def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
"""Reduce [a | b] to upper triangular form with partial pivoting.
Works in place on copies made by the caller. Returns a, b and the sign
of the row permutation.
"""
n = len(a)
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("singular matrix")
if p != k:
a[k], a[p] = a[p], a[k]
b[k], b[p] = b[p], b[k]
sign = -sign
piv = a[k][k]
for i in range(k + 1, n):
f = a[i][k] / piv
if f == 0:
continue
ai, ak = a[i], a[k]
for j in range(k, n):
ai[j] = ai[j] - f * ak[j]
bi, bk = b[i], b[k]
for j in range(len(bi)):
bi[j] = bi[j] - f * bk[j]
return a, b, sign
def solve(a: Sequence[Sequence[float]], b):
"""Solve a x = b for a square a, by Gaussian elimination with partial
pivoting. b is a vector or a matrix (several right-hand sides); the
result has the same form. Raises ValueError on an exact zero pivot."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("solve: matrix is not square")
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
if len(rhs) != n:
raise ValueError("solve: shapes do not match")
u, c, _ = _eliminate([list(row) for row in a], rhs)
m = len(c[0]) if n else 0
x = [[0.0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = c[i][j]
for k in range(i + 1, n):
s = s - u[i][k] * x[k][j]
x[i][j] = s / u[i][i]
return [row[0] for row in x] if vec else x
def inv(a: Sequence[Sequence[float]]) -> Matrix:
"""The inverse of a square matrix. Raises ValueError if it is singular."""
n = len(a)
one = a[0][0] - a[0][0] + 1 if n else 1.0
ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
return solve(a, ident)
def det(a: Sequence[Sequence[float]]) -> float:
"""The determinant of a square matrix, by Gaussian elimination."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("det: matrix is not square")
if n == 0:
return 1.0
try:
u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
except ValueError:
return a[0][0] - a[0][0]
d = u[0][0] - u[0][0] + sign
for i in range(n):
d = d * u[i][i]
return d
# ------------------------------------------------------- Jacobi methods
def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
"""Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
a is read (the lower triangle is taken as its mirror)."""
n = len(a)
s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
v = eye(n)
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
apq = s[p][q]
if apq == 0.0:
continue
app, aqq = s[p][p], s[q][q]
if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
abs(apq) < 1e-300:
s[p][q] = s[q][p] = 0.0
continue
rotated = True
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
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
s[p][q] = s[q][p] = 0.0
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
if not rotated:
break
order = sorted(range(n), key=lambda i: s[i][i])
w = [s[i][i] for i in order]
vs = [[v[k][i] for i in order] for k in range(n)]
return w, vs
def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
"""Replace the columns with index in need by unit vectors orthogonal to
all other columns (Gram-Schmidt on the standard basis)."""
keep = [c for i, c in enumerate(cols) if i not in need]
for i in need:
best, best_norm = None, -1.0
for e in range(m):
x = [0.0] * m
x[e] = 1.0
for _ in range(2):
for c in keep:
d = dot(c, x)
x = [xi - d * ci for xi, ci in zip(x, c)]
nx = norm(x)
if nx > best_norm:
best, best_norm = x, nx
u = [xi / best_norm for xi in best]
cols[i] = u
keep.append(u)
def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
m, n = len(a), len(a[0])
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
cp, cq = cols[p], cols[q]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cq)
gamma = sum(x * y for x, y in zip(cp, cq))
if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
continue
rotated = True
zeta = (beta - alpha) / (2.0 * gamma)
t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
c = 1.0 / math.sqrt(1.0 + t * t)
s = c * t
cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
vp, vq = vcols[p], vcols[q]
vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
if not rotated:
break
sv = [norm(c) for c in cols]
order = sorted(range(n), key=lambda i: -sv[i])
sv = [sv[i] for i in order]
cols = [cols[i] for i in order]
vcols = [vcols[i] for i in order]
smax = sv[0] if sv else 0.0
ucols: List[Vector] = []
need: List[int] = []
for i, c in enumerate(cols):
if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
ucols.append([x / sv[i] for x in c])
else:
ucols.append([0.0] * m)
need.append(i)
if need:
_complete_basis(ucols, m, need)
return transpose(ucols), sv, transpose(vcols)
def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
"""Thin singular value decomposition by the one-sided Jacobi method.
For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
size m x k, S a list of k values in descending order and V of size
n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
For m >= n, V is square (n x n)."""
m, n = len(a), len(a[0])
if m >= n:
return _svd_tall(a)
u, s, v = _svd_tall(transpose(a))
return v, s, u
def nullvec(a: Sequence[Sequence[float]]) -> Vector:
"""A unit vector x that minimizes ||a x||: the right singular vector of
the smallest singular value. If a has fewer rows than columns, zero rows
are added first, so the result is in the null space. The sign is not
fixed."""
m, n = len(a), len(a[0])
rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
_, _, v = _svd_tall(rows)
return [v[i][n - 1] for i in range(n)]
# ---------------------------------------------- orthogonal factorizations
def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""QR factorization by Householder reflections. For an m x n matrix a,
returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
m, n = len(a), len(a[0])
r = [[float(x) for x in row] for row in a]
q = eye(m)
for k in range(min(m - 1, n)):
x = [r[i][k] for i in range(k, m)]
nx = norm(x)
if nx == 0.0:
continue
alpha = -nx if x[0] >= 0 else nx
v = list(x)
v[0] -= alpha
nv = norm(v)
if nv == 0.0:
continue
v = [vi / nv for vi in v]
for j in range(n):
d = sum(v[i - k] * r[i][j] for i in range(k, m))
if d != 0.0:
for i in range(k, m):
r[i][j] -= 2.0 * v[i - k] * d
for i in range(m):
d = sum(q[i][l] * v[l - k] for l in range(k, m))
if d != 0.0:
for l in range(k, m):
q[i][l] -= 2.0 * d * v[l - k]
for k in range(min(m, n)):
if r[k][k] < 0:
r[k] = [-x for x in r[k]]
for i in range(m):
q[i][k] = -q[i][k]
for i in range(m):
for j in range(min(i, n)):
r[i][j] = 0.0
return q, r
def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""RQ factorization of a square matrix: returns R (upper triangular,
with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
from the QR factorization of the transpose of the row-reversed matrix."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("rq: matrix is not square")
flipped = transpose([list(row) for row in reversed(a)])
q1, r1 = qr(flipped)
rt = transpose(r1)
r = [list(reversed(row)) for row in reversed(rt)]
q = [list(row) for row in reversed(transpose(q1))]
return r, q
def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
"""The lower triangular L with a = L L^T, for a symmetric positive
definite a. Raises ValueError if a pivot is not positive."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
if d <= 0:
raise ValueError("cholesky: matrix is not positive definite")
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return low
# ---------------------------------------------------------- polynomials
def _horner(c: Sequence[complex], x):
p = 0.0
for ci in c:
p = p * x + ci
return p
def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
"""Real roots of the polynomial with the given coefficients, highest
power first. All complex roots are found by the Durand-Kerner method.
A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
part is then polished by Newton steps on the real polynomial. Returns
the real roots in ascending order, with repeats for multiple roots."""
c = [float(x) for x in coeffs]
while c and c[0] == 0.0:
c.pop(0)
n = len(c) - 1
if n < 1:
return []
c = [x / c[0] for x in c]
rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
if rho == 0.0:
return [0.0] * n
z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
for _ in range(2000):
moved = 0.0
for k in range(n):
den = 1.0 + 0j
for j in range(n):
if j != k:
den *= z[k] - z[j]
if den == 0:
den = 1e-12 * rho
step = _horner(c, z[k]) / den
z[k] -= step
moved = max(moved, abs(step) / max(1.0, abs(z[k])))
if moved <= 1e-15:
break
deriv = [c[i] * (n - i) for i in range(n)]
roots = []
for zk in z:
if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
continue
x = zk.real
px = _horner(c, x)
for _ in range(8):
dp = _horner(deriv, x)
if dp == 0.0 or px == 0.0:
break
xn = x - px / dp
pn = _horner(c, xn)
if abs(pn) >= abs(px):
break
x, px = xn, pn
roots.append(x)
return sorted(roots)
# ------------------------------------------------------------ self-test
def self_test() -> None:
"""Check svd, sym_eig and polyroots_real. Raises AssertionError."""
import random
rng = random.Random(7)
for _ in range(3):
a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
u, s, v = svd(a)
rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
assert norm(sub(rec, a)) <= 1e-10
assert all(s[i] >= s[i + 1] for i in range(4))
sym = add(a, transpose(a))
w, vv = sym_eig(sym)
rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
assert norm(sub(rec, sym)) <= 1e-10
assert all(w[i] <= w[i + 1] for i in range(4))
r = polyroots_real([1.0, -6.0, 11.0, -6.0])
assert len(r) == 3
assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))
if __name__ == "__main__":
self_test()
shot_descriptor.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shot-descriptor/. The authors are listed in prov/KZZVS0.jsonl.
"""The SHOT descriptor (signature of histograms of orientations), after
Tombari, Salti and Di Stefano (2010).
1. Local reference frame. The neighbors q_i within the radius R of the
feature point p give the weighted covariance
M = sum (R - d_i) (q_i - p)(q_i - p)^T / sum (R - d_i),
centered at p, with d_i = |q_i - p|. Its eigenvectors for the largest,
middle and smallest eigenvalue are x, y and z, up to sign. The signs of x
and z are chosen so that each points to the side with more neighbors,
and y = z x x.
2. Spherical grid. The sphere of radius R in this frame is cut into 32
volumes: 8 azimuth sectors, 2 elevation halves and 2 radial shells
(split at R/2).
3. Histograms. In each volume, the cosines n_i . z of the neighbors'
normals with the z axis are counted in 11 bins of [-1, 1]. The 32
histograms of 11 bins give 352 values, scaled to unit Euclidean norm.
This code bins each count in one cell. The original also spreads each count
over neighboring cells by quadrilinear interpolation, to soften the effect
of cell borders; that step is left out here.
The sign rule: count the neighbors with a positive and with a negative
projection on the axis. If the counts are equal, use the sign of the sum of
the projections, and if that is 0 too, keep the eigenvector as computed.
"""
from __future__ import annotations
import math
from typing import List, Optional, Sequence, Tuple
from cvla import cross, sym_eig
AZIMUTH, ELEVATION, RADIAL, BINS = 8, 2, 2, 11
LENGTH = AZIMUTH * ELEVATION * RADIAL * BINS # 352
Vec = List[float]
def _sub(a, b) -> Vec:
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
def _dot(a, b) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def neighbors(points: Sequence[Sequence[float]], p: Sequence[float], radius: float) -> List[int]:
"""The indices of the points with 0 < |q - p| < radius."""
return [i for i, q in enumerate(points) if 0.0 < math.dist(p, q) < radius]
def disambiguate(axis: Sequence[float], offsets: Sequence[Sequence[float]]) -> Vec:
"""Return axis or -axis, whichever has more of the offsets on its
positive side (ties: the sign of the sum of the projections)."""
proj = [_dot(axis, o) for o in offsets]
pos = sum(1 for t in proj if t > 0)
neg = sum(1 for t in proj if t < 0)
if neg > pos or (neg == pos and sum(proj) < 0):
return [-a for a in axis]
return list(axis)
def local_reference_frame(points: Sequence[Sequence[float]], p: Sequence[float],
radius: float) -> Optional[Tuple[Vec, Vec, Vec]]:
"""The frame (x, y, z) at p, or None with fewer than 3 neighbors."""
idx = neighbors(points, p, radius) # @line L1
if len(idx) < 3:
return None
offsets = [_sub(points[i], p) for i in idx]
m = [[0.0] * 3 for _ in range(3)]
total = 0.0
for o in offsets: # @line L2
w = radius - math.sqrt(_dot(o, o))
total += w
for r in range(3):
for c in range(3):
m[r][c] += w * o[r] * o[c]
m = [[x / total for x in row] for row in m]
_, v = sym_eig(m) # @line L3
x_plus = [v[k][2] for k in range(3)]
z_plus = [v[k][0] for k in range(3)]
x = disambiguate(x_plus, offsets) # @line L4
z = disambiguate(z_plus, offsets) # @line L5
y = cross(z, x)
return x, y, z
def volume_index(local: Sequence[float], radius: float) -> int:
"""The index in [0, 32) of the grid volume of a point with local
coordinates (a, b, c), at distance below the radius."""
a, b, c = local
azimuth = math.atan2(b, a) % (2.0 * math.pi)
sector = min(AZIMUTH - 1, int(azimuth / (2.0 * math.pi / AZIMUTH)))
half = 1 if c >= 0.0 else 0
shell = 1 if math.sqrt(a * a + b * b + c * c) >= radius / 2.0 else 0
return (sector * ELEVATION + half) * RADIAL + shell
def cosine_bin(cosine: float) -> int:
"""The bin of a cosine among 11 equal bins of [-1, 1]."""
return min(BINS - 1, max(0, int((cosine + 1.0) / 2.0 * BINS)))
def shot(points: Sequence[Sequence[float]], normals: Sequence[Sequence[float]],
p: Sequence[float], radius: float) -> Optional[List[float]]:
"""The 352-value SHOT descriptor at p (unit Euclidean norm), or None
when p has fewer than 3 neighbors within the radius."""
frame = local_reference_frame(points, p, radius)
if frame is None:
return None
x, y, z = frame
h = [0.0] * LENGTH # @line L6
for i in neighbors(points, p, radius): # @line L7
o = _sub(points[i], p)
local = (_dot(o, x), _dot(o, y), _dot(o, z)) # @line L8
v = volume_index(local, radius) # @line L9
k = cosine_bin(_dot(normals[i], z)) # @line L10
h[v * BINS + k] += 1.0 # @line L11
length = math.sqrt(sum(t * t for t in h))
return [t / length for t in h] # @line L12
test_shot_descriptor.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shot-descriptor/. The authors are listed in prov/KZZVS0.jsonl.
import math
import random
import pytest
from shot_descriptor import (
LENGTH,
cosine_bin,
disambiguate,
local_reference_frame,
neighbors,
shot,
volume_index,
)
def unit(v):
length = math.sqrt(sum(x * x for x in v))
return [x / length for x in v]
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
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 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, a=0.3, b=0.1, c=0.05):
"""Points on z = a x^2 + b y^2 + c x y^2 (no symmetry), with normals."""
pts, nrm = [], []
for _ in range(n):
x, y = rng.uniform(-1, 1), rng.uniform(-1, 1)
pts.append([x, y, a * x * x + b * y * y + c * x * y * y])
nrm.append(unit([-(2 * a * x + c * y * y), -(2 * b * y + 2 * c * x * y), 1.0]))
return pts, nrm
def example():
xy = [(1, 0), (-0.5, 0), (0, 0.8), (0, -0.4), (0.6, 0.6)]
pts = [[x, y, 0.2 * x * x + 0.1 * y * y] for x, y in xy]
nrm = [unit([-0.4 * x, -0.2 * y, 1.0]) for x, y in xy]
return pts, nrm
def test_example() -> None:
pts, nrm = example()
x, y, z = local_reference_frame(pts, (0, 0, 0), 2.0)
assert all(abs(a - b) < 1e-4 for a, b in zip(x, (0.8239, 0.5517, 0.1293)))
assert all(abs(a - b) < 1e-4 for a, b in zip(z, (-0.1201, -0.0531, 0.9913)))
h = shot(pts, nrm, (0, 0, 0), 2.0)
nonzero = [i for i, v in enumerate(h) if v]
assert nonzero == [32, 76, 164, 252, 351]
assert all(abs(h[i] - 1 / math.sqrt(5)) < 1e-12 for i in nonzero)
def test_frame_is_orthonormal_and_right_handed() -> None:
rng = random.Random(61)
pts, _ = surface(rng, 200)
for p in pts[:20]:
x, y, z = local_reference_frame(pts, p, 0.6)
for a in (x, y, z):
assert abs(dot(a, a) - 1) < 1e-12
assert abs(dot(x, y)) < 1e-12 and abs(dot(y, z)) < 1e-12 and abs(dot(x, z)) < 1e-12
cz = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]]
assert all(abs(a - b) < 1e-12 for a, b in zip(cz, z))
def test_frame_moves_with_the_cloud() -> None:
rng = random.Random(62)
pts, _ = surface(rng, 200)
R = rotation(rng)
t = (2.0, -3.0, 0.5)
moved = [apply(R, p, t) for p in pts]
for i in range(15):
f = local_reference_frame(pts, pts[i], 0.6)
g = local_reference_frame(moved, moved[i], 0.6)
for a, b in zip(f, g):
assert all(abs(u - v) < 1e-8 for u, v in zip(apply(R, a), b))
def test_descriptor_is_rigid_invariant_and_unit() -> None:
rng = random.Random(63)
pts, nrm = surface(rng, 300)
R = rotation(rng)
t = (-1.0, 4.0, 2.0)
mp = [apply(R, p, t) for p in pts]
mn = [apply(R, m) for m in nrm]
for i in range(10):
a = shot(pts, nrm, pts[i], 0.7)
b = shot(mp, mn, mp[i], 0.7)
assert len(a) == LENGTH
assert abs(sum(v * v for v in a) - 1) < 1e-12
assert max(abs(u - v) for u, v in zip(a, b)) < 1e-12
def oracle(points, normals, p, radius):
"""Spherical coordinates by acos, binned without the helper functions."""
x, y, z = local_reference_frame(points, p, radius)
h = [0] * 352
for q, n in zip(points, normals):
o = [q[k] - p[k] for k in range(3)]
d = math.sqrt(dot(o, o))
if not 0 < d < radius:
continue
a, b, c = dot(o, x), dot(o, y), dot(o, z)
az = math.degrees(math.atan2(b, a)) % 360
sector = int(az // 45)
half = int(c >= 0)
shell = int(d >= radius / 2)
cos_t = dot(n, z)
k = min(10, int((cos_t + 1) * 5.5))
h[((sector * 2 + half) * 2 + shell) * 11 + k] += 1
s = math.sqrt(sum(v * v for v in h))
return [v / s for v in h]
def test_matches_oracle() -> None:
rng = random.Random(64)
pts, nrm = surface(rng, 250)
for i in range(10):
a, b = shot(pts, nrm, pts[i], 0.8), oracle(pts, nrm, pts[i], 0.8)
assert max(abs(u - v) for u, v in zip(a, b)) < 1e-12
def test_disambiguation() -> None:
offs = [[1, 0, 0], [2, 0, 0], [-1, 0, 0]]
assert disambiguate([1, 0, 0], offs) == [1, 0, 0]
assert disambiguate([-1, 0, 0], offs) == [1, 0, 0]
# A tie in the counts goes by the sum of the projections.
assert disambiguate([-1, 0, 0], [[3, 0, 0], [-1, 0, 0]]) == [1, 0, 0]
def test_bins() -> None:
assert cosine_bin(-1.0) == 0 and cosine_bin(1.0) == 10 and cosine_bin(0.0) == 5
assert volume_index((1.0, 0.0, 0.1), 2.0) == 3
assert volume_index((0.1, 0.0, -0.1), 2.0) == 0
assert volume_index((0.0, -0.1, 0.1), 2.0) == (6 * 2 + 1) * 2
assert {volume_index((math.cos(t), math.sin(t), s), 3.0)
for t in [math.radians(22.5 + 45 * j) for j in range(8)] for s in (-0.1, 0.1)} == set(range(0, 32, 2))
def test_edges() -> None:
assert shot([[0, 0, 0], [1, 0, 0]], [[0, 0, 1]] * 2, (0, 0, 0), 2.0) is None
assert neighbors([[0, 0, 0], [1, 0, 0], [3, 0, 0]], (0, 0, 0), 2.0) == [1]
with pytest.raises(TypeError):
shot(None, None, (0, 0, 0), 1.0)
History
Local 3D descriptors before SHOT fell into two groups, as Tombari, Salti and Di Stefano (2010) put it: signatures, which describe the neighborhood in a local frame by its geometric measurements at positions in that frame, and histograms, which count measurements over the whole neighborhood. Signatures are discriminative but need a repeatable frame; histograms are robust but lose the positions. Most frames of the time fixed only the normal, as in spin images, or were not unique. Tombari, Salti and Di Stefano proposed a unique frame from a weighted covariance around the feature point with a sign rule for the axes, and a descriptor that is a signature of histograms: one histogram of normal cosines in each volume of a spherical grid. Salti, Tombari and Di Stefano (2014) extended it with color and analyzed the frame further. SHOT is part of the Point Cloud Library and is a common baseline for 3D local descriptors.
References
- Federico Tombari, Samuele Salti and Luigi Di Stefano, Unique signatures of histograms for local surface description, European Conference on Computer Vision (ECCV) 2010, Lecture Notes in Computer Science 6313, The local reference frame from the weighted covariance with the sign disambiguation, the spherical grid of 32 volumes, the histograms of normal cosines, the quadrilinear interpolation and the normalization
- Samuele Salti, Federico Tombari and Luigi Di Stefano, SHOT: Unique signatures of histograms for surface and texture description, Computer Vision and Image Understanding 125, 2014, The journal version: the reference frame, the descriptor, its color extension, and the experiments on repeatability and matching
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 KZZVS0 Edit this page History Report an error Markdown