Algorithm Search⌘K

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.

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
Properties
approximately affine invariantdeterministicnot exactheuristiciterative
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 2×22 \times 2 matrix UU, measures the second moment matrix MM of the warped patch, and multiplies UU by M−1/2M^{-1/2}, until MM 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 KK iterations, kernels of radius rr in the warped patch and PP start points, the cost is O(PKr3)O(PKr^3).

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 II with WW columns and HH rows of real values, and a list of points (x,σI)(\mathbf x, \sigma_I) with a position and an integration scale. A pixel has coordinates (u,v)(u, v): uu is the column and goes right, vv is the row and goes down. The image is read at real positions with bilinear interpolation.

A window shape is a symmetric positive definite 2×22 \times 2 matrix UU with largest eigenvalue 11. The normalized patch is W(p)=I(x+Up)W(\mathbf p) = I(\mathbf x + U\mathbf p), sampled at integer p\mathbf p. For a patch, μW(p;σI,σD)=σD2 g(σI)∗(∇L ∇LT)(p)\mu_W(\mathbf p; \sigma_I, \sigma_D) = \sigma_D^2\, g(\sigma_I) \ast \big(\nabla L\, \nabla L^{\mathsf T}\big)(\mathbf p) is the second moment matrix, where LL is WW smoothed with a Gaussian of standard deviation σD\sigma_D and g(σI)∗g(\sigma_I) \ast is a Gaussian sum with standard deviation σI\sigma_I. The isotropy of a matrix is λmin⁡/λmax⁡\lambda_{\min} / \lambda_{\max}, which is 11 for a multiple of the identity.

The output is a list of regions (x,σI,U)(\mathbf x, \sigma_I, U). Each region is the ellipse of the points x+σIUp\mathbf x + \sigma_I U \mathbf p with ∣p∣≤1\lvert \mathbf p \rvert \le 1, 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 εC\varepsilon_C, the bound εl\varepsilon_l on the axis ratio of UU, the number of iterations KK and the Harris constant α\alpha. Mikolajczyk and Schmid use εC=0.05\varepsilon_C = 0.05 and drop a point when the eigenvalue ratio of UU is above 6. They search the integration scale over tσIt\sigma_I with tt from 0.70.7 to 1.41.4 in steps of the factor 1.11.1, and the ratio s=σD/σIs = \sigma_D / \sigma_I in [0.5,0.75][0.5, 0.75]. This page uses these values, with ss in steps of 0.050.05, K=10K = 10 and α=0.06\alpha = 0.06.

The algorithm

  1. HARRIS-AFFINE(I, points, ε_C, ε_l, K)
  2. 1regions ← ∅
  3. 2for each (x, σ_I) in points do
  4. 3U ← the identity matrix
  5. 4repeat at most K times
  6. 5W(p) ← I(x + U p) for the integer p in a square around 0 ▷ bilinear
  7. 6σ_I ← t σ_I for the t in {0.7, 0.77, …, 1.36} with the largest (t σ_I)² |ΔW| at p = 0
  8. 7σ_D ← s σ_I for the s in {0.5, 0.55, …, 0.75} with the largest isotropy of μ_W(0)
  9. 8p ← the pixel among 0 and its 8 neighbours with the largest Harris measure, 0 on ties; x ← x + U p
  10. 9M ← μ_W(p); if M is singular then drop the point; P ← M^(-1/2)
  11. 10U ← the square root of (U P)(U P)^T, divided by its largest eigenvalue
  12. 11if λmax(U) / λmin(U) > ε_l then drop the point
  13. 12if 1 - λmin(P) / λmax(P) < ε_C then add (x, σ_I, U) to regions and go to the next point
  14. 13return 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 Q=λmin⁡(μ)/λmax⁡(μ)Q = \lambda_{\min}(\mu) / \lambda_{\max}(\mu) 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 UU. For Hessian-affine, line L8 uses σD4det⁡HL\sigma_D^4 \det \mathcal H L in place of the Harris measure det⁡μ−α(tr⁡μ)2\det\mu - \alpha (\operatorname{tr}\mu)^2.

Line L10 is the shape step. If the patch has matrix MM, the patch W′(p)=W(Pp)W'(\mathbf p) = W(P\mathbf p) with P=M−1/2P = M^{-1/2} has the matrix PMP=IdP M P = \mathrm{Id}, to first order. So the new window is UPUP. The product of two symmetric matrices is not symmetric in general, and UP=SQUP = S Q with S=(UP)(UP)TS = \sqrt{(UP)(UP)^{\mathsf T}} symmetric and QQ a rotation. A rotation of the patch does not change its isotropy, so line L10 keeps SS. The division by the largest eigenvalue keeps the long axis of the ellipse at σI\sigma_I; the scale is set by line L6.

Example

Take a 41×4141 \times 41 image of an elongated Gaussian blob centered at (20,20)(20, 20), I(x)=exp⁡ ⁣(−12(x−c)TΣ−1(x−c))I(\mathbf x) = \exp\!\big(-\frac12 (\mathbf x - \mathbf c)^{\mathsf T} \Sigma^{-1} (\mathbf x - \mathbf c)\big), with standard deviations 33 and 1.51.5 along axes turned by 30°30° from the uu axis. Start at (20,20)(20, 20) with σI=2\sigma_I = 2, and use Hessian-affine, since the pattern is a blob.

iteration 1 iteration 2
UU before the step identity (0.874,0.210;0.210,0.648)(0.874, 0.210; 0.210, 0.648)
σI\sigma_I from line L6 2.050 2.796
ss from line L7 0.75 0.75
isotropy of MM 0.2725 0.9498
isotropy of P=M−1/2P = M^{-1/2} 0.522 0.9746
UU after the step (0.874,0.210;0.210,0.648)(0.874, 0.210; 0.210, 0.648) (0.878,0.211;0.211,0.635)(0.878, 0.211; 0.211, 0.635)

In iteration 1 the round window sees a long blob. MM has eigenvalues 0.00700.0070 and 0.02570.0257, so the brightness changes almost four times faster across the blob than along it, and UU becomes an ellipse with eigenvalues 11 and 0.5220.522. In iteration 2 the warped patch is nearly round, the isotropy of PP is 0.97460.9746, and 1−0.9746=0.025<0.051 - 0.9746 = 0.025 < 0.05, so the loop stops. The region has axes σI⋅1=2.80\sigma_I \cdot 1 = 2.80 and σI⋅0.5135=1.44\sigma_I \cdot 0.5135 = 1.44, turned by 30.0°30.0°. The blob has the axis ratio 0.50.5 and the angle 30°30°, so the shape is found within 3 percent. The position stays at (20,20)(20, 20). A round blob gives U=IdU = \mathrm{Id} after one iteration, and a straight edge or a flat patch gives a singular MM and is dropped.

Correctness

The proof in proofs/correctness.md shows four things. The 2×22 \times 2 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 UU symmetric positive definite with largest eigenvalue 11. The loop is covariant: if I′(x)=I(A−1x)I'(\mathbf x) = I(A^{-1}\mathbf x) for an invertible AA, the second moment matrices satisfy ML=ATMRAM_L = A^{\mathsf T} M_R A, 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 Σ\Sigma in the continuous plane, a shape with UUT∝ΣU U^{\mathsf T} \propto \Sigma 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 2×22 \times 2 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 m=(abbc)m = \begin{pmatrix} a & b \\ b & c \end{pmatrix}.

Lemma 1 (eigenvalues). The eigenvalues of mm are a+c2±(a−c2)2+b2\frac{a + c}{2} \pm \sqrt{\big(\frac{a - c}{2}\big)^2 + b^2}.

Proof. They are the roots of λ2−(a+c)λ+(ac−b2)=0\lambda^2 - (a + c)\lambda + (ac - b^2) = 0. The discriminant is (a+c)2−4(ac−b2)=(a−c)2+4b2≥0(a + c)^2 - 4(ac - b^2) = (a - c)^2 + 4b^2 \ge 0, and the quadratic formula gives the stated values. □\square

Lemma 2 (square root). If mm is positive definite, let d=det⁡md = \sqrt{\det m} and τ=tr⁡m+2d\tau = \sqrt{\operatorname{tr} m + 2d}. Then r=(m+d Id)/τr = (m + d\,\mathrm{Id}) / \tau is symmetric positive definite and r2=mr^2 = m. So r−1=m−1/2r^{-1} = m^{-1/2}.

Proof. By the Cayley-Hamilton theorem m2=(tr⁡m) m−d2 Idm^2 = (\operatorname{tr} m)\, m - d^2\, \mathrm{Id}. Then (m+d Id)2=m2+2dm+d2Id=(tr⁡m+2d) m=τ2m(m + d\,\mathrm{Id})^2 = m^2 + 2dm + d^2\mathrm{Id} = (\operatorname{tr} m + 2d)\, m = \tau^2 m, so r2=mr^2 = m. The eigenvalues of rr are (λi+d)/τ(\lambda_i + d) / \tau with λi>0\lambda_i > 0 the eigenvalues of mm, so rr is positive definite, and it is symmetric because mm is. The positive definite square root is unique, so r=m1/2r = m^{1/2}. □\square

Lemma 3 (the shape step). Let UU and PP be symmetric positive definite. Then S=(UP)(UP)TS = \sqrt{(UP)(UP)^{\mathsf T}} is symmetric positive definite, UP=SQUP = SQ for a rotation QQ, and after line L10 UU is symmetric positive definite with largest eigenvalue 11.

Proof. V=UPV = UP is invertible, so VVTVV^{\mathsf T} is symmetric positive definite and SS exists by Lemma 2. Let Q=S−1VQ = S^{-1}V. Then QQT=S−1VVTS−1=S−1S2S−1=IdQQ^{\mathsf T} = S^{-1}VV^{\mathsf T}S^{-1} = S^{-1}S^2S^{-1} = \mathrm{Id}, and det⁡Q=det⁡Udet⁡P/det⁡S>0\det Q = \det U \det P / \det S > 0, so QQ is a rotation. Dividing SS by its largest eigenvalue, which is positive, keeps it symmetric positive definite and makes its largest eigenvalue 11. □\square

Lemma 4 (affine covariance of the second moment matrix). In the continuous plane, let W(p)W(\mathbf p) be a patch, BB an invertible matrix and W′(p)=W(Bp)W'(\mathbf p) = W(B\mathbf p). Let μ\mu be the second moment matrix of WW with Gaussian derivative and integration windows of covariances ΣD\Sigma_D and ΣI\Sigma_I at BpB\mathbf p. Then the matrix of W′W' at p\mathbf p with the windows B−1ΣDB−TB^{-1}\Sigma_D B^{-\mathsf T} and B−1ΣIB−TB^{-1}\Sigma_I B^{-\mathsf T} is BTμBB^{\mathsf T}\mu B.

Proof. By the chain rule ∇W′(p)=BT∇W(Bp)\nabla W'(\mathbf p) = B^{\mathsf T} \nabla W(B\mathbf p), and smoothing commutes with the change of variables when the window is carried along: a Gaussian with covariance Σ\Sigma at BpB\mathbf p becomes, after the substitution y=By′\mathbf y = B\mathbf y', a Gaussian with covariance B−1ΣB−TB^{-1}\Sigma B^{-\mathsf T} in y′\mathbf y', with the same total weight. So ∇L′∇L′T=BT ∇L∇LT B\nabla L' \nabla L'^{\mathsf T} = B^{\mathsf T}\, \nabla L \nabla L^{\mathsf T}\, B pointwise, and the integration window carries over in the same way. □\square

This is the relation ML=ATMRAM_L = A^{\mathsf T} M_R A of Mikolajczyk and Schmid. Two consequences follow. First, take B=P=M−1/2B = P = M^{-1/2} with M=μM = \mu: then BTMB=M−1/2MM−1/2=IdB^{\mathsf T}MB = M^{-1/2}MM^{-1/2} = \mathrm{Id}. The windows also change by BB, 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 QQ changes μ\mu to QTμQQ^{\mathsf T}\mu Q, which has the same eigenvalues, so by Lemma 3 dropping QQ does not change the isotropy. Second, let I′(x)=I(A−1x)I'(\mathbf x) = I(A^{-1}\mathbf x) and x′=Ax\mathbf x' = A\mathbf x. The patch of I′I' with shape U′U' is W′(p)=I(x+A−1U′p)W'(\mathbf p) = I(\mathbf x + A^{-1}U'\mathbf p), the patch of II with the matrix A−1U′A^{-1}U'. If A−1U′=UQA^{-1}U' = UQ for a rotation QQ, the two patches differ by the rotation QQ, so every test of lines L6 to L12 has the same outcome on both, and the ellipse x′+σIU′p\mathbf x' + \sigma_I U'\mathbf p is the image under AA of the ellipse x+σIUQp\mathbf x + \sigma_I UQ\mathbf p, which is the same set as x+σIUp\mathbf x + \sigma_I U\mathbf p over the unit disk. So converged regions correspond under AA. The normalization of the largest eigenvalue to 11 changes only σI\sigma_I, which line L6 sets again.

Proposition 5 (the fixed point for a Gaussian blob). Let I(x)=exp⁡ ⁣(−12(x−c)TΣ−1(x−c))I(\mathbf x) = \exp\!\big(-\frac12 (\mathbf x - \mathbf c)^{\mathsf T}\Sigma^{-1}(\mathbf x - \mathbf c)\big) with Σ\Sigma positive definite, and let UU be symmetric positive definite with UUT=κΣUU^{\mathsf T} = \kappa\Sigma for some κ>0\kappa > 0. Then the patch W(p)=I(c+Up)W(\mathbf p) = I(\mathbf c + U\mathbf p) is the isotropic Gaussian exp⁡(−κ∣p∣2/2)\exp(-\kappa|\mathbf p|^2 / 2), and its second moment matrix at p=0\mathbf p = 0 with round windows is a multiple of the identity.

Proof. W(p)=exp⁡ ⁣(−12pTUTΣ−1Up)W(\mathbf p) = \exp\!\big(-\frac12 \mathbf p^{\mathsf T}U^{\mathsf T}\Sigma^{-1}U\mathbf p\big), and Σ−1=κ (UUT)−1=κ U−TU−1\Sigma^{-1} = \kappa\,(UU^{\mathsf T})^{-1} = \kappa\, U^{-\mathsf T}U^{-1}, so UTΣ−1U=κ IdU^{\mathsf T}\Sigma^{-1}U = \kappa\,\mathrm{Id} and W(p)=exp⁡(−κ∣p∣2/2)W(\mathbf p) = \exp(-\kappa|\mathbf p|^2/2), which is isotropic. A round Gaussian smoothing of an isotropic function is isotropic, so ∇L(p)=ϕ(∣p∣) p\nabla L(\mathbf p) = \phi(|\mathbf p|)\,\mathbf p for some function ϕ\phi. Then ∇L∇LT=ϕ2 ppT\nabla L \nabla L^{\mathsf T} = \phi^2\, \mathbf p\mathbf p^{\mathsf T}, and its round Gaussian sum at 00 is ∫g(p) ϕ(∣p∣)2 ppT dp\int g(\mathbf p)\, \phi(|\mathbf p|)^2\, \mathbf p\mathbf p^{\mathsf T}\, d\mathbf p. By symmetry under the swap of the two coordinates the diagonal entries are equal, and by symmetry under p1↦−p1p_1 \mapsto -p_1 the off-diagonal entry is 00. □\square

So at this shape P=M−1/2P = M^{-1/2} is a multiple of the identity, 1−λmin⁡(P)/λmax⁡(P)=0<εC1 - \lambda_{\min}(P)/\lambda_{\max}(P) = 0 < \varepsilon_C, and line L12 stops. For Hessian-affine, the center of the isotropic patch is the maximum of det⁡HL\det \mathcal H L, because LL is a round Gaussian there, so line L8 does not move the point.

Theorem. Every region that HARRIS-AFFINE returns is a triple (x,σI,U)(\mathbf x, \sigma_I, U) where UU is symmetric positive definite with largest eigenvalue 11 and axis ratio at most εl\varepsilon_l, and where the second moment matrix MM of the last patch satisfies λmin⁡(M)/λmax⁡(M)>1−εC\sqrt{\lambda_{\min}(M)/\lambda_{\max}(M)} > 1 - \varepsilon_C. 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 εl\varepsilon_l. Line L9 drops the point when MM is singular, so P=M−1/2P = M^{-1/2} exists by Lemma 2, and its eigenvalues are λ−1/2\lambda^{-1/2} for the eigenvalues λ\lambda of MM, so λmin⁡(P)/λmax⁡(P)=λmin⁡(M)/λmax⁡(M)\lambda_{\min}(P)/\lambda_{\max}(P) = \sqrt{\lambda_{\min}(M)/\lambda_{\max}(M)}. Line L12 adds a region only when 1−λmin⁡(P)/λmax⁡(P)<εC1 - \lambda_{\min}(P)/\lambda_{\max}(P) < \varepsilon_C, 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. ■\blacksquare

Complexity

The model is the real RAM. Let rr be the radius of the largest Gaussian kernel used in the normalized patch, so the patch has O(r2)O(r^2) pixels.

  • Line L5 samples O(r2)O(r^2) pixels.
  • Line L6 evaluates the Laplacian at the center for 8 scales, O(r2)O(r^2) each.
  • Line L7 smooths a square of side O(r)O(r) for 6 values of ss, each a separable blur of O(r3)O(r^3), and sums at the center.
  • Lines L8 and L9 compute μ\mu at 9 pixels with separable sums, O(r2)O(r^2).
  • Lines L10 to L12 are O(1)O(1).

So one iteration costs O(r3)O(r^3), and a point costs O(Kr3)O(Kr^3). The total time is O(PKr3)O(PKr^3); a point dropped in the first iteration costs O(r3)O(r^3). The extra space is the patch and its smoothed copies, O(r2)O(r^2). 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 εC\varepsilon_C. The final σI\sigma_I 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 MM 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 σI\sigma_I and σD\sigma_D 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 0.5220.522 instead of 0.51350.5135.
  • 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 UU times M−1/2M^{-1/2} when the patch is I(x+Up)I(\mathbf x + U\mathbf p). With the other convention, I(x+U−1p)I(\mathbf x + U^{-1}\mathbf p), the update changes; mixing the two gives a wrong shape.
  • Singular matrices. On an edge or a flat patch MM is singular, and M−1/2M^{-1/2} does not exist. Drop the point.
  • Long shapes. On edges the shape grows longer each iteration. The bound εl\varepsilon_l stops this.
  • Too small a patch. The normalized patch must hold the Gaussian sums at the largest scale tried, or the border rule distorts MM.
  • 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 σIU\sigma_I U falls below about one pixel, the bilinear samples cannot show the structure, and MM 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.

harris_affine_detector.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example