Algorithmadvanced
Harris-affine and Hessian-affine detectors
Also called Harris-affine, Hessian-affine, Mikolajczyk-Schmid affine detector.
Detect Harris or Hessian points at their characteristic scale and refine each to an affine covariant ellipse by shape adaptation.
- Solves
- Feature detection
- Time
- O(P K r^3) worst · averageO(P r^3) best
- Space
- O(r^2) extra
- Where
- K = the largest number of iterations per point; P = the number of input points; r = the radius of the largest Gaussian kernel in the normalized patch
- Model
- Real RAM
- Properties
- approximately affine invariantdeterministicnot exactheuristiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Krystian Mikolajczyk, Cordelia Schmid, 2004
The Harris-affine detector solves feature detection when the views differ by a change of viewpoint, not only by a change of scale. It starts from points with a scale, usually from the Harris-Laplace detector, and adapts the shape of the window around each point. In a loop, it warps the image near the point by a matrix , measures the second moment matrix of the warped patch, and multiplies by , until is close to a multiple of the identity. Each step also chooses the integration scale, the differentiation scale and the position again. The result is an ellipse that covers the same part of a surface in two views that differ by an affine map, so the region is affine covariant. The Hessian-affine detector is the same loop with the position chosen by the determinant of the Hessian instead of the Harris measure; it finds blobs instead of corners. With iterations, kernels of radius in the warped patch and start points, the cost is .
In plain words
A round window around a point covers a circle in one photograph. In a second photograph taken from the side, the same part of the scene is squeezed, so a circle there covers a different part. The detector fixes this by letting the window become an ellipse. It looks at the patch inside the window and asks in which direction the brightness changes more. It then stretches the window in the direction where the change is weaker, and asks again. When the brightness inside the window changes about equally in all directions, the window is right. The same scene part, seen from two directions, gives two ellipses that each look round after this stretching, and so they can be compared.
The problem
The input is a gray digital image with columns and rows of real values, and a list of points with a position and an integration scale. A pixel has coordinates : is the column and goes right, is the row and goes down. The image is read at real positions with bilinear interpolation.
A window shape is a symmetric positive definite matrix with largest eigenvalue . The normalized patch is , sampled at integer . For a patch, is the second moment matrix, where is smoothed with a Gaussian of standard deviation and is a Gaussian sum with standard deviation . The isotropy of a matrix is , which is for a multiple of the identity.
The output is a list of regions . Each region is the ellipse of the points with , and at the end the second moment matrix of its patch is close to isotropic. Points where the loop does not converge, or where the shape becomes too long, are dropped.
The parameters are the convergence bound , the bound on the axis ratio of , the number of iterations and the Harris constant . Mikolajczyk and Schmid use and drop a point when the eigenvalue ratio of is above 6. They search the integration scale over with from to in steps of the factor , and the ratio in . This page uses these values, with in steps of , and .
The algorithm
HARRIS-AFFINE(I, points, ε_C, ε_l, K)- 1
regions ← ∅ - 2
for each (x, σ_I) in points do - 3
U ← the identity matrix - 4
repeat at most K times - 5
W(p) ← I(x + U p) for the integer p in a square around 0 ▷ bilinear - 6
σ_I ← t σ_I for the t in {0.7, 0.77, …, 1.36} with the largest (t σ_I)² |ΔW| at p = 0 - 7
σ_D ← s σ_I for the s in {0.5, 0.55, …, 0.75} with the largest isotropy of μ_W(0) - 8
p ← the pixel among 0 and its 8 neighbours with the largest Harris measure, 0 on ties; x ← x + U p - 9
M ← μ_W(p); if M is singular then drop the point; P ← M^(-1/2) - 10
U ← the square root of (U P)(U P)^T, divided by its largest eigenvalue - 11
if λmax(U) / λmin(U) > ε_l then drop the point - 12
if 1 - λmin(P) / λmax(P) < ε_C then add (x, σ_I, U) to regions and go to the next point - 13
return regions
Line L6 chooses the integration scale as the maximum of the scale-normalized Laplacian at the center of the normalized patch, as in automatic scale selection. Line L7 chooses the differentiation scale that makes the matrix most isotropic; this is the measure of the 2004 paper. Line L8 moves the point to the best neighbour in the normalized patch and maps the step back to the image with . For Hessian-affine, line L8 uses in place of the Harris measure .
Line L10 is the shape step. If the patch has matrix , the patch with has the matrix , to first order. So the new window is . The product of two symmetric matrices is not symmetric in general, and with symmetric and a rotation. A rotation of the patch does not change its isotropy, so line L10 keeps . The division by the largest eigenvalue keeps the long axis of the ellipse at ; the scale is set by line L6.
Example
Take a image of an elongated Gaussian blob centered at , , with standard deviations and along axes turned by from the axis. Start at with , and use Hessian-affine, since the pattern is a blob.
| iteration 1 | iteration 2 | |
|---|---|---|
| before the step | identity | |
| from line L6 | 2.050 | 2.796 |
| from line L7 | 0.75 | 0.75 |
| isotropy of | 0.2725 | 0.9498 |
| isotropy of | 0.522 | 0.9746 |
| after the step |
In iteration 1 the round window sees a long blob. has eigenvalues and , so the brightness changes almost four times faster across the blob than along it, and becomes an ellipse with eigenvalues and . In iteration 2 the warped patch is nearly round, the isotropy of is , and , so the loop stops. The region has axes and , turned by . The blob has the axis ratio and the angle , so the shape is found within 3 percent. The position stays at . A round blob gives after one iteration, and a straight edge or a flat patch gives a singular and is dropped.
Correctness
The proof in proofs/correctness.md shows four things. The formulas for the square root, the inverse square root and the eigenvalues are exact. Line L10 makes the new patch isotropic to first order and keeps symmetric positive definite with largest eigenvalue . The loop is covariant: if for an invertible , the second moment matrices satisfy , so a window that is isotropic for one image maps to one that is isotropic for the other, and the two regions cover the same part of the pattern. And for an elongated Gaussian blob with covariance in the continuous plane, a shape with makes the patch an isotropic Gaussian, so the loop stops there.
The method does not prove that the loop converges from any start. It is a fixed point iteration, and in the experiments of the 2004 paper about 40 percent of the start points do not converge and are dropped. How well the regions repeat on real images is measured; see detector repeatability.
Proof: Correctness of the Harris-affine detectorfull
We prove that the formulas are exact, that line L10 keeps a valid shape and makes the patch isotropic to first order, that the second moment matrix is covariant under affine maps, and that the shape of an elongated Gaussian blob is a fixed point of the loop. Convergence of the loop from an arbitrary start is not claimed.
Write a symmetric matrix as .
Lemma 1 (eigenvalues). The eigenvalues of are .
Proof. They are the roots of . The discriminant is , and the quadratic formula gives the stated values.
Lemma 2 (square root). If is positive definite, let and . Then is symmetric positive definite and . So .
Proof. By the Cayley-Hamilton theorem . Then , so . The eigenvalues of are with the eigenvalues of , so is positive definite, and it is symmetric because is. The positive definite square root is unique, so .
Lemma 3 (the shape step). Let and be symmetric positive definite. Then is symmetric positive definite, for a rotation , and after line L10 is symmetric positive definite with largest eigenvalue .
Proof. is invertible, so is symmetric positive definite and exists by Lemma 2. Let . Then , and , so is a rotation. Dividing by its largest eigenvalue, which is positive, keeps it symmetric positive definite and makes its largest eigenvalue .
Lemma 4 (affine covariance of the second moment matrix). In the continuous plane, let be a patch, an invertible matrix and . Let be the second moment matrix of with Gaussian derivative and integration windows of covariances and at . Then the matrix of at with the windows and is .
Proof. By the chain rule , and smoothing commutes with the change of variables when the window is carried along: a Gaussian with covariance at becomes, after the substitution , a Gaussian with covariance in , with the same total weight. So pointwise, and the integration window carries over in the same way.
This is the relation of Mikolajczyk and Schmid. Two consequences follow. First, take with : then . The windows also change by , and the algorithm uses round windows in the new patch instead, so the new patch is isotropic only to first order; this is why line L10 is repeated. A rotation changes to , which has the same eigenvalues, so by Lemma 3 dropping does not change the isotropy. Second, let and . The patch of with shape is , the patch of with the matrix . If for a rotation , the two patches differ by the rotation , so every test of lines L6 to L12 has the same outcome on both, and the ellipse is the image under of the ellipse , which is the same set as over the unit disk. So converged regions correspond under . The normalization of the largest eigenvalue to changes only , which line L6 sets again.
Proposition 5 (the fixed point for a Gaussian blob). Let with positive definite, and let be symmetric positive definite with for some . Then the patch is the isotropic Gaussian , and its second moment matrix at with round windows is a multiple of the identity.
Proof. , and , so and , which is isotropic. A round Gaussian smoothing of an isotropic function is isotropic, so for some function . Then , and its round Gaussian sum at is . By symmetry under the swap of the two coordinates the diagonal entries are equal, and by symmetry under the off-diagonal entry is .
So at this shape is a multiple of the identity, , and line L12 stops. For Hessian-affine, the center of the isotropic patch is the maximum of , because is a round Gaussian there, so line L8 does not move the point.
Theorem. Every region that HARRIS-AFFINE returns is a triple where is symmetric positive definite with largest eigenvalue and axis ratio at most , and where the second moment matrix of the last patch satisfies . In the continuous setting the returned regions are covariant with affine maps of the image, and the shape of an elongated Gaussian blob is a fixed point.
Proof. Line L3 starts with the identity, which is a valid shape. By Lemma 3 every pass of line L10 gives a valid shape, and line L11 drops the point when the axis ratio is above . Line L9 drops the point when is singular, so exists by Lemma 2, and its eigenvalues are for the eigenvalues of , so . Line L12 adds a region only when , which is the stated bound. Lines L1, L2 and L13 collect the regions of all points that pass, and nothing else adds to the list. Covariance follows from Lemma 4 and the remarks after it, and the fixed point from Proposition 5.
Complexity
The model is the real RAM. Let be the radius of the largest Gaussian kernel used in the normalized patch, so the patch has pixels.
- Line L5 samples pixels.
- Line L6 evaluates the Laplacian at the center for 8 scales, each.
- Line L7 smooths a square of side for 6 values of , each a separable blur of , and sums at the center.
- Lines L8 and L9 compute at 9 pixels with separable sums, .
- Lines L10 to L12 are .
So one iteration costs , and a point costs . The total time is ; a point dropped in the first iteration costs . The extra space is the patch and its smoothed copies, . In practice the iterations for the many start points of Harris-Laplace dominate the time, and many points converge to the same region and must be merged.
Properties
- Affine covariance. If two views differ by an affine map near a point, the converged ellipses correspond under that map, up to a rotation, which the shape does not fix.
- Rotation is not fixed. An isotropic patch can still be turned. A descriptor must choose an orientation in the normalized patch, for example the main gradient direction, as SIFT does.
- Fixed point. At a converged region the patch is isotropic within . The final need not be a maximum of the Laplacian, because the stop test looks only at the shape.
- Corners and blobs. Harris-affine puts regions on corners and textured parts. Hessian-affine puts them on blobs and ridges. The two give different and complementary sets of regions.
- Brightness. An offset changes nothing. A gain scales but not its isotropy, so the shape is the same.
Variants and improvements
- Hessian-affine. Use the determinant of the Hessian for the position; the shape step is the same. The 2005 comparison of affine region detectors evaluates it next to Harris-affine.
- Fixed scales. Keep and from the start point and run only the shape and position steps. This is faster and is close to the method of Baumberg.
- Shape only once. Use one step of line L10 without iteration. On the example this already gives the axis ratio instead of .
- Other start points. Any detector with a scale can give the start points, for example the DoG or the determinant of the Hessian.
- Other affine regions. MSER finds affine covariant regions without iteration, from the level sets of the image.
When to use it
Use it to match images of the same scene from viewpoints that differ a lot, such as wide-baseline stereo and object recognition on flat surfaces, where scale invariant detectors lose many points. For small changes of viewpoint the scale invariant Harris-Laplace or DoG detectors are faster and need no iteration. For scenes with many uniform regions, MSER is a good choice and is much faster.
Pitfalls
- Wrong order of the factors. The new window is times when the patch is . With the other convention, , the update changes; mixing the two gives a wrong shape.
- Singular matrices. On an edge or a flat patch is singular, and does not exist. Drop the point.
- Long shapes. On edges the shape grows longer each iteration. The bound stops this.
- Too small a patch. The normalized patch must hold the Gaussian sums at the largest scale tried, or the border rule distorts .
- Duplicates. Several start points near the same corner converge to the same region. Merge regions whose ellipses overlap strongly.
- Thin structures. When the short axis of falls below about one pixel, the bilinear samples cannot show the structure, and is poor.
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/harris-affine-detector/. The authors are listed in prov/3SB3Q7.jsonl.
"""Affine shape adaptation of Harris and Hessian points, after Mikolajczyk and Schmid (2004).
An image is a list of H rows of W floats; pixel (u, v) is img[v][u], with u
the column (to the right) and v the row (down). Positions are real numbers
and the image is read with bilinear interpolation and the clamp border rule.
A region is (x, y, sigma_i, U). U = (a, b, c) is the symmetric positive
definite matrix [[a, b], [b, c]] with largest eigenvalue 1. The normalized
patch is W(p) = I((x, y) + U p), and the region is the ellipse of the points
(x, y) + sigma_i U p with |p| <= 1. At a converged region the second moment
matrix of W at its center is close to a multiple of the identity.
Gaussian sums are sampled, cut at radius ceil(3 sigma) and normalized.
"""
import math
from typing import List, Optional, Sequence, Tuple
Sym = Tuple[float, float, float]
Region = Tuple[float, float, float, Sym]
T_VALUES = tuple(0.7 * 1.1 ** j for j in range(8)) # 0.70 to 1.36, the search range for sigma_i
S_VALUES = (0.5, 0.55, 0.6, 0.65, 0.7, 0.75) # the ratios sigma_d / sigma_i
OFFSETS = [(p, q) for q in (-1, 0, 1) for p in (-1, 0, 1)]
def gaussian_kernel(sigma: float) -> List[float]:
rad = max(1, int(math.ceil(3 * sigma)))
k = [math.exp(-(i * i) / (2 * sigma * sigma)) for i in range(-rad, rad + 1)]
s = sum(k)
return [x / s for x in k]
def sym_eig(m: Sym) -> Tuple[float, float]:
"""Eigenvalues (smaller, larger) of [[a, b], [b, c]]."""
a, b, c = m
mid, rad = (a + c) / 2, math.hypot((a - c) / 2, b)
return mid - rad, mid + rad
def sym_sqrt(m: Sym) -> Sym:
"""The symmetric positive definite square root of a positive definite m."""
a, b, c = m
d = math.sqrt(a * c - b * b)
t = math.sqrt(a + c + 2 * d)
return (a + d) / t, b / t, (c + d) / t
def sym_inv(m: Sym) -> Sym:
a, b, c = m
det = a * c - b * b
return c / det, -b / det, a / det
def sym_inv_sqrt(m: Sym) -> Sym:
return sym_inv(sym_sqrt(m))
def bilinear(img: Sequence[Sequence[float]], x: float, y: float) -> float:
h, w = len(img), len(img[0])
x = min(max(x, 0.0), w - 1.0)
y = min(max(y, 0.0), h - 1.0)
u0, v0 = min(int(x), w - 2) if w > 1 else 0, min(int(y), h - 2) if h > 1 else 0
fx, fy = x - u0, y - v0
u1, v1 = min(u0 + 1, w - 1), min(v0 + 1, h - 1)
top = img[v0][u0] * (1 - fx) + img[v0][u1] * fx
bot = img[v1][u0] * (1 - fx) + img[v1][u1] * fx
return top * (1 - fy) + bot * fy
def warp(img: Sequence[Sequence[float]], x: float, y: float, U: Sym, R: int) -> List[List[float]]:
"""The patch P[R + q][R + p] = I((x, y) + U (p, q)) for -R <= p, q <= R."""
a, b, c = U
return [[bilinear(img, x + a * p + b * q, y + b * p + c * q) for p in range(-R, R + 1)]
for q in range(-R, R + 1)]
def smooth_box(P: List[List[float]], sigma: float, h: int) -> List[List[float]]:
"""The patch blurred by sigma, on the (2h + 1) x (2h + 1) box around its center."""
n = len(P)
c = n // 2
k = gaussian_kernel(sigma)
r = len(k) // 2
rows = range(c - h - r, c + h + r + 1)
tmp = {j: [sum(k[i] * P[min(max(j, 0), n - 1)][min(max(u + i - r, 0), n - 1)] for i in range(len(k)))
for u in range(c - h, c + h + 1)] for j in rows}
return [[sum(k[i] * tmp[v + i - r][u] for i in range(len(k))) for u in range(2 * h + 1)]
for v in range(c - h, c + h + 1)]
def center_laplacian(P: List[List[float]], sigma: float) -> float:
"""sigma^2 |Lxx + Lyy| at the center of the patch, with the 5-point Laplacian."""
L = smooth_box(P, sigma, 1)
return sigma * sigma * abs(L[1][2] + L[1][0] + L[2][1] + L[0][1] - 4 * L[1][1])
def moments(P: List[List[float]], si: float, sd: float, offsets=OFFSETS):
"""Second moment matrices and Hessian determinants at the given offsets (at most 1) from the center."""
ki = gaussian_kernel(si)
ri = len(ki) // 2
h = ri + 2
L = smooth_box(P, sd, h)
n = 2 * h + 1
lo, hi = 1, n - 1
xx, xy, yy = {}, {}, {}
for v in range(lo, hi):
for u in range(lo, hi):
gx = (L[v][u + 1] - L[v][u - 1]) / 2
gy = (L[v + 1][u] - L[v - 1][u]) / 2
xx[v, u], xy[v, u], yy[v, u] = gx * gx, gx * gy, gy * gy
out = {}
for p, q in offsets:
u, v = h + p, h + q
sums = []
for prod in (xx, xy, yy):
# Separable Gaussian sum: first along the rows, then down the column.
rows = [sum(ki[i] * prod[v + j - ri, u + i - ri] for i in range(len(ki))) for j in range(len(ki))]
sums.append(sum(ki[j] * rows[j] for j in range(len(ki))))
A, B, C = sums
dxx = L[v][u + 1] - 2 * L[v][u] + L[v][u - 1]
dyy = L[v + 1][u] - 2 * L[v][u] + L[v - 1][u]
dxy = (L[v + 1][u + 1] - L[v + 1][u - 1] - L[v - 1][u + 1] + L[v - 1][u - 1]) / 4
s2 = sd * sd
out[(p, q)] = ((s2 * A, s2 * B, s2 * C), s2 * s2 * (dxx * dyy - dxy * dxy))
return out
def _ratio(m: Sym) -> float:
lo, hi = sym_eig(m)
return lo / hi if hi > 0 else 0.0
def adapt_point(img: Sequence[Sequence[float]], x: float, y: float, sigma_i: float, alpha: float = 0.06,
eps_c: float = 0.05, eps_l: float = 6.0, max_iter: int = 10, measure: str = "harris",
t_values: Sequence[float] = T_VALUES, s_values: Sequence[float] = S_VALUES) -> Optional[Region]:
"""Adapt one point (x, y) with integration scale sigma_i; None if it is rejected."""
U = (1.0, 0.0, 1.0) # @line L3
for _ in range(max_iter): # @line L4
rl = int(math.ceil(3 * sigma_i * max(t_values)))
R = rl + int(math.ceil(3 * max(s_values) * sigma_i * max(t_values))) + 4
P = warp(img, x, y, U, R) # @line L5
sigma_i = max((sigma_i * t for t in t_values), key=lambda s: center_laplacian(P, s)) # @line L6
sigma_d = max((s * sigma_i for s in s_values),
key=lambda d: _ratio(moments(P, sigma_i, d, [(0, 0)])[(0, 0)][0])) # @line L7
mom = moments(P, sigma_i, sigma_d)
def score(o):
m, det_h = mom[o]
return det_h if measure == "hessian" else m[0] * m[2] - m[1] ** 2 - alpha * (m[0] + m[2]) ** 2
p, q = max(OFFSETS, key=lambda o: (score(o), o == (0, 0))) # @line L8
a, b, c = U
x, y = x + a * p + b * q, y + b * p + c * q
M = mom[(p, q)][0] # @line L9
lo, hi = sym_eig(M)
if lo <= 1e-12 * max(hi, 1e-300):
return None
Pm = sym_inv_sqrt(M)
e, f, g = Pm
v11, v12 = a * e + b * f, a * f + b * g # @line L10
v21, v22 = b * e + c * f, b * f + c * g
S = (v11 * v11 + v12 * v12, v11 * v21 + v12 * v22, v21 * v21 + v22 * v22)
U = sym_sqrt(S)
ulo, uhi = sym_eig(U)
U = (U[0] / uhi, U[1] / uhi, U[2] / uhi)
if uhi / ulo > eps_l: # @line L11
return None
if 1 - _ratio(Pm) < eps_c: # @line L12
return x, y, sigma_i, U
return None
def harris_affine(img: Sequence[Sequence[float]], points: Sequence[Tuple[float, float, float]], **options) -> List[Region]:
"""Adapt each point (x, y, sigma_i), for example from the Harris-Laplace detector.
Precondition: img is a rectangular list of rows of floats, at least 2 x 2,
and each sigma_i > 0. Options are passed to adapt_point.
"""
regions = [] # @line L1
for x, y, s in points: # @line L2
r = adapt_point(img, x, y, s, **options)
if r is not None:
regions.append(r)
return regions # @line L13
test_harris_affine_detector.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harris-affine-detector/. The authors are listed in prov/3SB3Q7.jsonl.
import math
import random
from harris_affine_detector import (
adapt_point,
gaussian_kernel,
harris_affine,
moments,
sym_eig,
sym_inv,
sym_inv_sqrt,
sym_sqrt,
warp,
)
def mul(m, n):
return [[sum(m[i][k] * n[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
def full(s):
return [[s[0], s[1]], [s[1], s[2]]]
def ablob(n, cx, cy, s1, s2, th):
c, s = math.cos(th), math.sin(th)
sig = (c * c * s1 * s1 + s * s * s2 * s2, c * s * (s1 * s1 - s2 * s2), s * s * s1 * s1 + c * c * s2 * s2)
ia, ib, ic = sym_inv(sig)
img = [[math.exp(-0.5 * (ia * (u - cx) ** 2 + 2 * ib * (u - cx) * (v - cy) + ic * (v - cy) ** 2))
for u in range(n)] for v in range(n)]
return img, sig
def shape(U):
a, b, c = U
s = (a * a + b * b, a * b + b * c, b * b + c * c)
return [x / (s[0] + s[2]) for x in s]
def test_two_by_two_algebra_against_definitions():
rng = random.Random(1997)
for _ in range(600):
a, c = rng.uniform(0.01, 5), rng.uniform(0.01, 5)
b = rng.uniform(-0.99, 0.99) * math.sqrt(a * c)
m = (a, b, c)
r = full(sym_sqrt(m))
rr = mul(r, r)
assert all(abs(rr[i][j] - full(m)[i][j]) < 1e-9 * (a + c) for i in range(2) for j in range(2))
assert min(sym_eig(sym_sqrt(m))) > 0
q = full(sym_inv_sqrt(m))
e = mul(mul(q, full(m)), q)
assert all(abs(e[i][j] - (i == j)) < 1e-7 for i in range(2) for j in range(2))
lo, hi = sym_eig(m)
for lam in (lo, hi):
assert abs((a - lam) * (c - lam) - b * b) < 1e-9 * (a + c) ** 2
assert lo <= hi
def test_warp_is_exact_on_linear_images():
rng = random.Random(7)
for _ in range(200):
g, k, o = rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-1, 1)
img = [[g * u + k * v + o for u in range(30)] for v in range(30)]
x, y = rng.uniform(12, 17), rng.uniform(12, 17)
U = (rng.uniform(0.5, 1), rng.uniform(-0.3, 0.3), rng.uniform(0.5, 1))
P = warp(img, x, y, U, 4)
for q in range(-4, 5):
for p in range(-4, 5):
want = g * (x + U[0] * p + U[1] * q) + k * (y + U[1] * p + U[2] * q) + o
assert abs(P[q + 4][p + 4] - want) < 1e-9
img = [[float(u * 31 + v) for u in range(9)] for v in range(9)]
assert warp(img, 4.0, 4.0, (1.0, 0.0, 1.0), 2) == [row[2:7] for row in img[2:7]]
def test_moments_match_direct_sums():
rng = random.Random(3)
P = [[rng.random() for _ in range(31)] for _ in range(31)]
si, sd = 1.5, 1.0
kd, ki = gaussian_kernel(sd), gaussian_kernel(si)
rd, ri = len(kd) // 2, len(ki) // 2
def L(u, v):
return sum(kd[i + rd] * kd[j + rd] * P[v + j][u + i] for i in range(-rd, rd + 1) for j in range(-rd, rd + 1))
mom = moments(P, si, sd)
for (p, q), (m, det_h) in mom.items():
A = B = C = 0.0
for j in range(-ri, ri + 1):
for i in range(-ri, ri + 1):
u, v, w = 15 + p + i, 15 + q + j, ki[i + ri] * ki[j + ri]
gx, gy = (L(u + 1, v) - L(u - 1, v)) / 2, (L(u, v + 1) - L(u, v - 1)) / 2
A, B, C = A + w * gx * gx, B + w * gx * gy, C + w * gy * gy
assert all(abs(x - sd * sd * y) < 1e-12 for x, y in zip(m, (A, B, C)))
u, v = 15 + p, 15 + q
dxx = L(u + 1, v) - 2 * L(u, v) + L(u - 1, v)
dyy = L(u, v + 1) - 2 * L(u, v) + L(u, v - 1)
dxy = (L(u + 1, v + 1) - L(u - 1, v + 1) - L(u + 1, v - 1) + L(u - 1, v - 1)) / 4
assert abs(det_h - sd ** 4 * (dxx * dyy - dxy * dxy)) < 1e-12
def test_worked_example_anisotropic_blob():
img, sig = ablob(41, 20, 20, 3.0, 1.5, math.pi / 6)
x, y, s, U = adapt_point(img, 20.0, 20.0, 2.0, measure="hessian")
assert (x, y) == (20.0, 20.0)
assert abs(s - 2.796) < 1e-3
lo, hi = sym_eig(U)
assert abs(hi - 1.0) < 1e-12
assert abs(lo - 0.5135) < 1e-3
a, b, c = U
assert abs(0.5 * math.degrees(math.atan2(2 * b, a - c)) - 30.0) < 0.1
want = [z / (sig[0] + sig[2]) for z in sig]
assert all(abs(g - w) < 0.01 for g, w in zip(shape(U), want))
assert adapt_point(img, 20.0, 20.0, 2.0, measure="hessian", max_iter=1) is None
def test_isotropic_blob_needs_one_step():
img, _ = ablob(31, 15, 15, 2.5, 2.5, 0.0)
x, y, s, U = adapt_point(img, 15.0, 15.0, 2.0, measure="hessian", max_iter=1)
assert (x, y) == (15.0, 15.0)
assert abs(U[0] - 1) < 1e-9 and abs(U[1]) < 1e-9 and abs(U[2] - 1) < 1e-9
def test_rotation_by_90_degrees():
img, _ = ablob(35, 17, 17, 2.5, 1.4, 0.4)
h = len(img)
rot = [[img[h - 1 - j][i] for j in range(h)] for i in range(h)]
x, y, s, U = adapt_point(img, 17.0, 17.0, 2.0, measure="hessian")
x2, y2, s2, U2 = adapt_point(rot, 17.0, 17.0, 2.0, measure="hessian")
assert (x2, y2) == (17.0, 17.0) and abs(s - s2) < 1e-9
# The rotated image has I'(u', v') = I(v', h - 1 - u'), so U' = A^T U A with A = [[0, 1], [-1, 0]].
assert abs(U2[0] - U[2]) < 1e-9 and abs(U2[1] + U[1]) < 1e-9 and abs(U2[2] - U[0]) < 1e-9
def test_edges_and_flat_regions_are_rejected():
edge = [[1.0 if u >= 15 else 0.0 for u in range(31)] for v in range(31)]
flat = [[0.3] * 31 for _ in range(31)]
img, _ = ablob(31, 15, 15, 2.5, 1.5, 0.3)
assert adapt_point(edge, 15.0, 15.0, 2.0) is None
assert adapt_point(flat, 15.0, 15.0, 2.0) is None
out = harris_affine(img, [(15.0, 15.0, 2.0)], measure="hessian")
assert len(out) == 1 and out[0][:2] == (15.0, 15.0)
History
Tony Lindeberg and Jonas Garding introduced affine shape adaptation in 1997, to estimate surface shape from the deformation of texture: they iterate a second moment matrix until it is the fixed point of the adaptation. Adam Baumberg used this iteration in 2000 to make windows for matching across widely separated views. Krystian Mikolajczyk and Cordelia Schmid joined it with their Harris-Laplace points, and in their 2004 journal paper they gave the full iterative algorithm, with the search for the integration scale, the differentiation scale and the position in each step. The 2005 comparison of affine region detectors by Mikolajczyk and others describes the Hessian-affine variant and compares both with MSER and other affine detectors.
References
- Krystian Mikolajczyk and Cordelia Schmid, Scale and affine invariant interest point detectors, International Journal of Computer Vision 60(1), 63-86, 2004, Section 3 (3.2, the affine normalization and the measure Q of Eq. 10; 3.3, the iterative detection algorithm)
- Tony Lindeberg and Jonas Garding, Shape-adapted smoothing in estimation of 3-D shape cues from affine deformations of local 2-D brightness structure, Image and Vision Computing 15(6), 415-434, 1997, the sections on the fixed point of affine shape adaptation
- Adam Baumberg, Reliable feature matching across widely separated views, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2000), 2000, the section on the affine adaptation of the window
- Krystian Mikolajczyk, Tinne Tuytelaars, Cordelia Schmid, Andrew Zisserman, Jiri Matas, Frederik Schaffalitzky, Timor Kadir and Luc Van Gool, A comparison of affine region detectors, International Journal of Computer Vision 65(1-2), 43-72, 2005, the sections on the Harris-affine and Hessian-affine detectors and on the evaluation
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 3SB3Q7 Edit this page History Report an error Markdown