Algorithm Search⌘K

Algorithmadvanced

Harris-Laplace detector

Also called scale-adapted Harris detector.

Find Harris corners at each scale and keep those whose scale is a maximum of the normalized Laplacian, giving scale-covariant corner points.

Time
O(K W H r) worst · average · best
Space
Θ(K W H) extra
Where
H = the image height in pixels; K = the number of scales; W = the image width in pixels; r = the radius of the largest Gaussian kernel
Properties
approximately scale invariantdeterministicnot exactheuristicrotation invariant response
Origin
Krystian Mikolajczyk, Cordelia Schmid, 2001

The Harris-Laplace detector solves feature detection for corner points that come with a scale. At each scale of a scale space it computes the Harris measure from a second moment matrix built with derivatives at a differentiation scale and summed over an integration scale. It keeps the points that are spatial maxima of this measure. Then it keeps only the points where the scale-normalized Laplacian of Gaussian at the same pixel is larger than at the scale below and the scale above. The Harris measure places the point precisely on a corner, and the Laplacian picks the scale, by the rule of automatic scale selection. When the image is magnified, the points move with the pattern and their scales grow by the same factor. The cost is O(KWHr)O(KWHr) for KK scales and kernels of radius at most rr.

In plain words

Look at the image through several blurs, from fine to coarse. At each blur, find the corners with the Harris test: places where the brightness changes in two directions. A corner at one blur may also show up at the next blur, a little moved. To choose the right size for each corner, use a second measure that says how much the area around the point looks like a spot of that size. Keep a corner only at the blur where this second measure is larger than at the blur just below and just above it. Each kept corner then has a position and a size. If the same scene is photographed closer, the same corners come back, with sizes that grow in step with the zoom.

The problem

The input is a gray digital image II with WW columns and HH rows of real values in [0,1][0, 1]. A pixel has coordinates (u,v)(u, v): uu is the column and goes right, vv is the row and goes down, and xx and yy name the derivatives along uu and vv. L(⋅,σ)L(\cdot, \sigma) is II smoothed by a Gaussian of standard deviation σ\sigma; this page uses a sampled Gaussian cut at 3σ3\sigma, separable, with the clamp border rule.

The parameters are the first scale σ0\sigma_0, the ratio ξ>1\xi > 1 between scales, the number of scales K≥3K \ge 3, the factor s∈(0,1]s \in (0, 1] between the differentiation and the integration scale, the Harris constant α\alpha, and two thresholds τH\tau_H and τL\tau_L. Mikolajczyk and Schmid use ξ=1.4\xi = 1.4 and s=0.7s = 0.7. They do not fix α\alpha; this page uses α=0.06\alpha = 0.06, σ0=1\sigma_0 = 1, K=6K = 6, τH=10−5\tau_H = 10^{-5} and τL=0.05\tau_L = 0.05.

The scales are σn=σ0ξn\sigma_n = \sigma_0 \xi^n. At scale σn\sigma_n the integration scale is σI=σn\sigma_I = \sigma_n and the differentiation scale is σD=sσn\sigma_D = s\sigma_n. The scale-adapted second moment matrix is

μn=σD2 g(σI)∗(Lx2LxLyLxLyLy2),\mu_n = \sigma_D^2\, g(\sigma_I) \ast \begin{pmatrix} L_x^2 & L_x L_y \\ L_x L_y & L_y^2 \end{pmatrix},

where LxL_x and LyL_y are derivatives of L(⋅,σD)L(\cdot, \sigma_D) and g(σI)∗g(\sigma_I) \ast is a Gaussian sum with standard deviation σI\sigma_I. The factor σD2\sigma_D^2 makes the values at different scales comparable. The Harris measure is Rn=det⁡μn−α(tr⁡μn)2R_n = \det \mu_n - \alpha (\operatorname{tr} \mu_n)^2 and the normalized Laplacian is Fn=σn2∣Lxx+Lyy∣F_n = \sigma_n^2 \lvert L_{xx} + L_{yy} \rvert, both at scale σn\sigma_n. The output is the list of points (u,v,σn)(u, v, \sigma_n) that pass the two tests of line L7 below.

The algorithm

  1. HARRIS-LAPLACE(I, σ_0, ξ, K, s, α, τ_H, τ_L)
  2. 1for n ← 0 to K - 1 do σ_n ← σ_0 ξ^n
  3. 2μ_n ← σ_D² g(σ_n) ∗ [L_x², L_x L_y; L_x L_y, L_y²] with L = g(σ_D) ∗ I and σ_D = s σ_n
  4. 3R_n ← det μ_n - α (tr μ_n)²
  5. 4F_n ← σ_n² |L_xx + L_yy| with L = g(σ_n) ∗ I
  6. 5points ← ∅
  7. 6for each (u, v, n) with 1 ≤ n ≤ K - 2 and (u, v) off the border do
  8. 7if R_n(u, v) > τ_H, R_n(u, v) > R_n at the 8 neighbours, F_n(u, v) > τ_L, F_n(u, v) > F_(n-1)(u, v) and F_n(u, v) > F_(n+1)(u, v) then
  9. 8add (u, v, σ_n) to points
  10. 9return points

Line L2 uses central differences, Lx≈12(L(u+1,v)−L(u−1,v))L_x \approx \frac12\big(L(u + 1, v) - L(u - 1, v)\big) and the same in vv. Line L4 uses the five-point Laplacian L(u+1,v)+L(u−1,v)+L(u,v+1)+L(u,v−1)−4L(u,v)L(u + 1, v) + L(u - 1, v) + L(u, v + 1) + L(u, v - 1) - 4L(u, v). Line L7 joins the two parts of the detector: the Harris test is spatial, at one scale, and the Laplacian test is over scale, at one pixel. The point need not be a spatial maximum of FF, and it need not be a maximum of RR over scale.

This is the simplified form of the detector. The iterative form of the 2004 paper starts from the same points and, for each point, searches a finer range of scales around σn\sigma_n for the extremum of the Laplacian, then moves the point to the Harris maximum at the new scale, and repeats until the point and the scale stop changing.

Example

Take a 28×2828 \times 28 image that is 00 except for a white square of side 9, with 10≤u,v≤1810 \le u, v \le 18. The scales are σn=1.4n\sigma_n = 1.4^n for n=0,…,5n = 0, \dots, 5: 11, 1.41.4, 1.961.96, 2.7442.744, 3.8423.842 and 5.3785.378. At two pixels the values are:

σn\sigma_n 1 1.4 1.96 2.744 3.842 5.378
Rn(11,11)×104R_n(11, 11) \times 10^4 2.607 5.081 6.553 7.605 6.706 2.892
Fn(11,11)F_n(11, 11) 0.3541 0.3996 0.3468 0.2991 0.3259 0.3356
Rn(14,14)×104R_n(14, 14) \times 10^4 0.000 0.043 1.722 8.441 9.737 3.840
Fn(14,14)F_n(14, 14) 0.0000 0.0339 0.2639 0.6139 0.7135 0.5620

The pixel (11,11)(11, 11) is one step inside the top left corner. It is a spatial maximum of R1R_1, and F1=0.3996F_1 = 0.3996 is larger than F0F_0 and F2F_2, so it is kept with σ=1.4\sigma = 1.4. It is also a spatial maximum of RR at larger scales, but there FF is not a maximum over scale. The center (14,14)(14, 14) has R=0R = 0 at the smallest scale, where the square looks flat inside. At σ4=3.842\sigma_4 = 3.842 the whole square fits in the window, R4R_4 is a spatial maximum and F4=0.7135F_4 = 0.7135 is a maximum over scale. The detector returns five points: the four corners (11,11)(11, 11), (17,11)(17, 11), (11,17)(11, 17) and (17,17)(17, 17) at σ=1.4\sigma = 1.4, and the center (14,14)(14, 14) at σ=3.842\sigma = 3.842, which marks the square as a whole.

Correctness

The proof in proofs/correctness.md shows that lines L6 to L8 return exactly the points with the two properties of line L7. It shows that under a magnification of the image by ff, in the continuous setting, μ\mu, RR and FF at the corresponding point and the scale fσf\sigma are the same as before, so a selected point (x,σ)(\mathbf x, \sigma) becomes (fx,fσ)(f\mathbf x, f\sigma). It also shows that for a Gaussian blob of standard deviation σb\sigma_b the normalized Laplacian at the center has its single maximum over scale at σ=σb\sigma = \sigma_b. On the grid, a blob with σb=1.4n\sigma_b = 1.4^n for n=1,…,4n = 1, \dots, 4 gives one point, at its center, with exactly that scale.

That the points are repeatable on real images is measured, not proved. In the experiments of the 2004 paper, on 160 images, Harris-Laplace finds 68 percent of its points again at a scale factor of 1.4; see detector repeatability.

Proof: Correctness of the Harris-Laplace detectorfull

We prove that lines L6 to L8 return exactly the points that pass the tests of line L7, that the normalized measures do not change under a magnification, so the selected points follow the size of the pattern, and that for a Gaussian blob the Laplacian selects the scale of the blob.

Lemma 1 (the selection). Lines L6 to L8 return exactly the triples (u,v,σn)(u, v, \sigma_n) with 1≤n≤K−21 \le n \le K - 2, 1≤u≤W−21 \le u \le W - 2, 1≤v≤H−21 \le v \le H - 2, such that Rn(u,v)>τHR_n(u, v) > \tau_H, Rn(u,v)>Rn(u+a,v+b)R_n(u, v) > R_n(u + a, v + b) for the 8 offsets (a,b)≠(0,0)(a, b) \ne (0, 0) in {−1,0,1}2\{-1, 0, 1\}^2, Fn(u,v)>τLF_n(u, v) > \tau_L, Fn(u,v)>Fn−1(u,v)F_n(u, v) > F_{n-1}(u, v) and Fn(u,v)>Fn+1(u,v)F_n(u, v) > F_{n+1}(u, v). Each such triple is returned once.

Proof. Line L6 visits each triple of the stated ranges exactly once, so all the neighbours in space and scale that line L7 reads exist. Line L7 evaluates the conjunction of the five conditions, and line L8 adds the triple exactly when the conjunction holds. No other line adds to the list. □\square

For the next two results we work in the continuous plane, with exact Gaussians and exact derivatives. Write gσg_\sigma for the Gaussian of standard deviation σ\sigma in two variables and L(⋅,σ)=gσ∗IL(\cdot, \sigma) = g_\sigma \ast I.

Lemma 2 (magnification). Let f>0f > 0 and I′(x)=I(x/f)I'(\mathbf x) = I(\mathbf x / f). Then L′(fx,fσ)=L(x,σ)L'(f\mathbf x, f\sigma) = L(\mathbf x, \sigma), and with σI′=fσI\sigma_I' = f\sigma_I and σD′=fσD\sigma_D' = f\sigma_D:

μ′(fx)=μ(x),R′(fx)=R(x),F′(fx,fσ)=F(x,σ).\mu'(f\mathbf x) = \mu(\mathbf x), \qquad R'(f\mathbf x) = R(\mathbf x), \qquad F'(f\mathbf x, f\sigma) = F(\mathbf x, \sigma).

Proof. gfσ(fy)=f−2gσ(y)g_{f\sigma}(f\mathbf y) = f^{-2} g_\sigma(\mathbf y). Substituting y′=fy\mathbf y' = f\mathbf y in L′(fx,fσ)=∫gfσ(fx−y′) I(y′/f) dy′L'(f\mathbf x, f\sigma) = \int g_{f\sigma}(f\mathbf x - \mathbf y')\, I(\mathbf y' / f)\, d\mathbf y' gives dy′=f2dyd\mathbf y' = f^2 d\mathbf y, and the factors f−2f^{-2} and f2f^2 cancel, so L′(fx,fσ)=L(x,σ)L'(f\mathbf x, f\sigma) = L(\mathbf x, \sigma).

Each derivative in the new coordinates is 1/f1/f times the derivative in the old ones, so Lx′(fx,fσD)=f−1Lx(x,σD)L'_x(f\mathbf x, f\sigma_D) = f^{-1} L_x(\mathbf x, \sigma_D), and in the same way for LyL_y. Each product of two first derivatives gains the factor f−2f^{-2}, and σD′2=f2σD2\sigma_D'^2 = f^2 \sigma_D^2 removes it. The Gaussian sum with gfσIg_{f\sigma_I} of a function h′(y′)=h(y′/f)h'(\mathbf y') = h(\mathbf y' / f) at fxf\mathbf x is, by the same substitution, the Gaussian sum with gσIg_{\sigma_I} of hh at x\mathbf x. So each entry of μ′\mu' at fxf\mathbf x equals the entry of μ\mu at x\mathbf x. Then det⁡\det and tr⁡\operatorname{tr} agree, and so does RR.

For FF, each second derivative gains f−2f^{-2}, and (fσ)2=f2σ2(f\sigma)^2 = f^2\sigma^2 removes it. □\square

So if (x,σn)(\mathbf x, \sigma_n) passes the tests of line L7 for II, with the conditions read in the continuous plane and the neighbours taken at the scaled positions, then (fx,fσn)(f\mathbf x, f\sigma_n) passes them for I′I' with the scales fσ0ξnf\sigma_0 \xi^n, and the reverse holds with 1/f1/f. The thresholds compare values that are equal on both sides. On the grid and with a fixed list of scales this holds only up to sampling.

Proposition 3 (the scale of a Gaussian blob). Let I(x)=exp⁡(−∣x∣2/(2σb2))I(\mathbf x) = \exp(-|\mathbf x|^2 / (2\sigma_b^2)). Then F(0,σ)=2tt0/(t0+t)2F(\mathbf 0, \sigma) = 2 t t_0 / (t_0 + t)^2 with t=σ2t = \sigma^2 and t0=σb2t_0 = \sigma_b^2, and as a function of σ>0\sigma > 0 it has a single maximum, at σ=σb\sigma = \sigma_b, with the value 12\frac12.

Proof. I=2πt0 gI = 2\pi t_0\, g where gg is the Gaussian of variance t0t_0, and Gaussians add their variances, so L(x,σ)=t0t0+texp⁡ ⁣(−∣x∣2/(2(t0+t)))L(\mathbf x, \sigma) = \frac{t_0}{t_0 + t} \exp\!\big(-|\mathbf x|^2 / (2(t_0 + t))\big). For cexp⁡(−∣x∣2/(2T))c\exp(-|\mathbf x|^2 / (2T)) the Laplacian at 0\mathbf 0 is −2c/T-2c/T. So Lxx+Lyy=−2t0/(t0+t)2L_{xx} + L_{yy} = -2t_0 / (t_0 + t)^2 at 0\mathbf 0, and F(0,σ)=t⋅2t0/(t0+t)2F(\mathbf 0, \sigma) = t \cdot 2t_0 / (t_0 + t)^2. Let ψ(t)=log⁡t−2log⁡(t0+t)\psi(t) = \log t - 2\log(t_0 + t). Then ψ′(t)=1/t−2/(t0+t)=(t0−t)/(t(t0+t))\psi'(t) = 1/t - 2/(t_0 + t) = (t_0 - t) / (t (t_0 + t)), which is positive for t<t0t < t_0, zero at t=t0t = t_0 and negative for t>t0t > t_0. Since σ↦σ2\sigma \mapsto \sigma^2 is increasing, the single maximum over σ\sigma is at σ=σb\sigma = \sigma_b, where F=2t02/(2t0)2=12F = 2t_0^2 / (2t_0)^2 = \frac12. □\square

So if σb=σn\sigma_b = \sigma_n for some 1≤n≤K−21 \le n \le K - 2, then Fn(0)>Fn−1(0)F_n(\mathbf 0) > F_{n-1}(\mathbf 0) and Fn(0)>Fn+1(0)F_n(\mathbf 0) > F_{n+1}(\mathbf 0), and the Laplacian test of line L7 at the center selects exactly the scale σn\sigma_n of the blob.

Theorem. HARRIS-LAPLACE returns exactly the points (u,v,σn)(u, v, \sigma_n) that are strict spatial maxima of the scale-adapted Harris measure above τH\tau_H and strict maxima over scale of the normalized Laplacian above τL\tau_L, and in the continuous setting the set of these points is covariant with a magnification of the image.

Proof. Line L1 sets the scales σn=σ0ξn\sigma_n = \sigma_0 \xi^n. Lines L2 and L3 compute μn\mu_n and RnR_n from their definitions with σI=σn\sigma_I = \sigma_n and σD=sσn\sigma_D = s\sigma_n, and line L4 computes FnF_n. Line L5 starts with an empty list. By Lemma 1, lines L6 to L8 add exactly the points with the stated properties, each once, and line L9 returns them. By Lemma 2, under a magnification by ff the values RR and FF at (fx,fσ)(f\mathbf x, f\sigma) equal those at (x,σ)(\mathbf x, \sigma), so each test of line L7 has the same outcome at the two points, and the returned sets correspond by (x,σ)↦(fx,fσ)(\mathbf x, \sigma) \mapsto (f\mathbf x, f\sigma). ■\blacksquare

Complexity

The model is the real RAM. Let r=⌈3σK−1⌉r = \lceil 3\sigma_{K-1} \rceil be the radius of the largest kernel.

  • Lines L2 and L4 are four blurs for μn\mu_n and one for FnF_n, each separable, O(WHr)O(WHr) per scale.
  • Line L3 is O(WH)O(WH) per scale.
  • Lines L6 to L8 make at most 10 comparisons per sample, O(KWH)O(KWH).

The total time is O(KWHr)O(KWHr), and the stacks of RR and FF take Θ(KWH)\Theta(KWH) space. A pyramid that halves the image when the scale doubles makes the large kernels run on small images. The iterative form adds a small search in scale for each point.

Properties

  • Scale. Under a magnification by ff the points move to ff times their position, with ff times their scale, up to the sampling of scales by ξ\xi.
  • Rotation. det⁡μ\det \mu, tr⁡μ\operatorname{tr}\mu and the Laplacian do not change under a rotation of the coordinates, so neither do RR and FF. On the grid this is exact for rotations by 90°90°.
  • Brightness. An offset changes neither RR nor FF. A gain gg multiplies RR by g4g^4 and FF by gg, so it changes only which points pass the thresholds.
  • Localization. The point is a Harris maximum, so it sits near the corner. A blob detector such as the DoG puts its point at the center of a region instead.
  • Fewer points per corner. A corner is a Harris maximum at many scales, but usually the Laplacian has a maximum over scale at only one or two of them.
  • Not affine invariant. The window is a circle. Under a change of viewpoint it covers different parts of the scene; the Harris-affine detector adapts the window to an ellipse.

Variants and improvements

  • Iterative form. Search a finer set of scales around each point, from 0.7σn0.7\sigma_n to 1.4σn1.4\sigma_n in the paper, and move the point to the Harris maximum at the new scale until it is stable. This gives more accurate scales at a higher cost.
  • Hessian-Laplace. Use the determinant of the Hessian for the position and the Laplacian for the scale. It finds blobs, not corners.
  • Harris-affine. Start from Harris-Laplace points and adapt the shape of the window to the local structure.
  • Scale-space maxima of the Harris measure. Take maxima of RR in space and scale together. At the square corner of the example RR has its maximum over scale at σ=2.744\sigma = 2.744, two levels away from the scale the Laplacian picks; Mikolajczyk and Schmid chose the Laplacian for the scale.

When to use it

Use it when points must be found again after a change of scale and should sit on corners rather than at the centers of blobs, for example on images of buildings and objects with straight edges. For large changes of viewpoint use the Harris-affine or MSER detector. When speed matters more than localization on corners, the DoG detector of SIFT is a common choice.

Pitfalls

  • Sharp corners have no scale of their own. A straight corner looks the same at every magnification, so in the continuous case the Laplacian at its apex has no maximum over scale. On the grid the only size left is the pixel: a lone corner of a quarter plane gives a point one pixel inside the corner, at σ=1.4\sigma = 1.4, the same as each corner of the square in the example. The selected scale of such a corner depends on the sampling, not on the scene.
  • Missing normalization. Without the factors σD2\sigma_D^2 and σn2\sigma_n^2 the values fall with the scale and the selection always takes the finest scale.
  • Equal neighbours. The spatial test is strict. A symmetric pattern of even width can give two equal neighbours, and then neither is kept. Break ties by a fixed order if this matters.
  • Too few scales. The finest and coarsest scales cannot hold a point, because the test needs a scale on each side.
  • Thresholds depend on the range. τH\tau_H scales with the fourth power of the contrast and τL\tau_L with the contrast. Set them for the range of the image values.
  • Small ss. A differentiation scale much smaller than the integration scale makes the derivatives noisy; a value near 1 smooths the corner away. Values from 0.5 to 0.75 are usual.

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_laplace_detector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harris-laplace-detector/. The authors are listed in prov/B4GHVB.jsonl.

"""Harris-Laplace detector, the simplified form of 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). Gaussian blurs are sampled,
cut at radius ceil(3 sigma), normalized, separable, with the clamp border rule.

For each scale sigma_n = sigma0 xi^n (n = 0, ..., K - 1), with the integration
scale sigma_I = sigma_n and the differentiation scale sigma_D = s sigma_n:

    mu_n = sigma_D^2 g(sigma_I) * [[Lx^2, Lx Ly], [Lx Ly, Ly^2]],
    R_n  = det mu_n - alpha (trace mu_n)^2,
    F_n  = sigma_n^2 |Lxx + Lyy|    (the scale-normalized Laplacian at sigma_n).

Lx and Ly are central differences (divided by 2) of the image blurred with
sigma_D. A point (u, v, n) with 1 <= n <= K - 2, off the border, is kept when
R_n > tau_h, R_n is larger than at the 8 spatial neighbours, F_n > tau_l and
F_n is larger than F_(n-1) and F_(n+1) at the same pixel.
"""

import math
from typing import List, Sequence, Tuple

Image = List[List[float]]


def gaussian_kernel(sigma: float) -> List[float]:
    if sigma <= 0:
        return [1.0]
    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 blur(img: Sequence[Sequence[float]], sigma: float) -> Image:
    """Separable Gaussian blur with standard deviation sigma, clamp border."""
    h, w = len(img), len(img[0])
    k = gaussian_kernel(sigma)
    r = len(k) // 2
    tmp = [[sum(k[j] * row[min(max(u + j - r, 0), w - 1)] for j in range(len(k))) for u in range(w)]
           for row in img]
    return [[sum(k[j] * tmp[min(max(v + j - r, 0), h - 1)][u] for j in range(len(k))) for u in range(w)]
            for v in range(h)]


def _clamp(x: int, lo: int, hi: int) -> int:
    return lo if x < lo else hi if x > hi else x


def harris_measure(img: Sequence[Sequence[float]], sigma_i: float, sigma_d: float, alpha: float) -> Image:
    """R = det mu - alpha trace(mu)^2 with the scale-adapted second moment matrix mu."""
    L = blur(img, sigma_d)
    h, w = len(L), len(L[0])
    lx = [[(L[v][_clamp(u + 1, 0, w - 1)] - L[v][_clamp(u - 1, 0, w - 1)]) / 2 for u in range(w)] for v in range(h)]
    ly = [[(L[_clamp(v + 1, 0, h - 1)][u] - L[_clamp(v - 1, 0, h - 1)][u]) / 2 for u in range(w)] for v in range(h)]
    c = sigma_d * sigma_d
    a = blur([[c * x * x for x in r] for r in lx], sigma_i)
    b = blur([[c * y * y for y in r] for r in ly], sigma_i)
    m = blur([[c * x * y for x, y in zip(rx, ry)] for rx, ry in zip(lx, ly)], sigma_i)
    return [[a[v][u] * b[v][u] - m[v][u] ** 2 - alpha * (a[v][u] + b[v][u]) ** 2 for u in range(w)]
            for v in range(h)]


def normalized_laplacian(img: Sequence[Sequence[float]], sigma: float) -> Image:
    """sigma^2 |Lxx + Lyy| with the 5-point Laplacian; 0 on the one-pixel border."""
    L = blur(img, sigma)
    h, w = len(L), len(L[0])
    out = [[0.0] * w for _ in range(h)]
    for v in range(1, h - 1):
        for u in range(1, w - 1):
            out[v][u] = sigma * sigma * abs(L[v][u + 1] + L[v][u - 1] + L[v + 1][u] + L[v - 1][u] - 4 * L[v][u])
    return out


def select_points(R: List[Image], F: List[Image], tau_h: float, tau_l: float) -> List[Tuple[int, int, int]]:
    """Points (n, u, v): spatial Harris maxima that are Laplacian maxima over scale."""
    out = []
    k, h, w = len(R), len(R[0]), len(R[0][0])
    for n in range(1, k - 1):  # @line L6
        for v in range(1, h - 1):
            for u in range(1, w - 1):
                r = R[n][v][u]
                f = F[n][v][u]
                if r <= tau_h or f <= tau_l or not (f > F[n - 1][v][u] and f > F[n + 1][v][u]):  # @line L7
                    continue
                if all(R[n][v + b][u + a] < r for a in (-1, 0, 1) for b in (-1, 0, 1) if a or b):
                    out.append((n, u, v))  # @line L8
    return out


def harris_laplace(img: Sequence[Sequence[float]], sigma0: float = 1.0, xi: float = 1.4, levels: int = 6,
                   s: float = 0.7, alpha: float = 0.06, tau_h: float = 1e-5, tau_l: float = 0.05):
    """Return points (u, v, sigma_I) sorted by v, u and sigma.

    Precondition: img is a rectangular list of rows of floats, at least 3 x 3,
    sigma0 > 0, xi > 1, levels >= 3 and 0 < s <= 1.
    """
    R, F, sig = [], [], []
    for n in range(levels):
        sn = sigma0 * xi ** n  # @line L1
        R.append(harris_measure(img, sn, s * sn, alpha))  # @line L2 @line L3
        F.append(normalized_laplacian(img, sn))  # @line L4
        sig.append(sn)
    pts = [(u, v, sig[n]) for n, u, v in select_points(R, F, tau_h, tau_l)]  # @line L5
    return sorted(pts, key=lambda p: (p[1], p[0], p[2]))  # @line L9
test_harris_laplace_detector.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harris-laplace-detector/. The authors are listed in prov/B4GHVB.jsonl.

import math
import random

from harris_laplace_detector import (
    gaussian_kernel,
    harris_laplace,
    harris_measure,
    normalized_laplacian,
    select_points,
)


def rect(n, u0, u1, v0, v1):
    return [[1.0 if u0 <= u <= u1 and v0 <= v <= v1 else 0.0 for u in range(n)] for v in range(n)]


def blob(n, cx, cy, sb):
    return [[math.exp(-((u - cx) ** 2 + (v - cy) ** 2) / (2 * sb * sb)) for u in range(n)] for v in range(n)]


def at(img, u, v):
    h, w = len(img), len(img[0])
    return img[min(max(v, 0), h - 1)][min(max(u, 0), w - 1)]


def direct_blur(img, sigma):
    k = gaussian_kernel(sigma)
    r = len(k) // 2
    h, w = len(img), len(img[0])
    return [[sum(k[i + r] * k[j + r] * at(img, u + i, v + j) for i in range(-r, r + 1) for j in range(-r, r + 1))
             for u in range(w)] for v in range(h)]


def direct_harris(img, si, sd, alpha):
    L = direct_blur(img, sd)
    h, w = len(img), len(img[0])
    lx = [[(at(L, u + 1, v) - at(L, u - 1, v)) / 2 for u in range(w)] for v in range(h)]
    ly = [[(at(L, u, v + 1) - at(L, u, v - 1)) / 2 for u in range(w)] for v in range(h)]
    a = direct_blur([[sd * sd * lx[v][u] ** 2 for u in range(w)] for v in range(h)], si)
    b = direct_blur([[sd * sd * ly[v][u] ** 2 for u in range(w)] for v in range(h)], si)
    c = direct_blur([[sd * sd * lx[v][u] * ly[v][u] for u in range(w)] for v in range(h)], si)
    out = []
    for v in range(h):
        row = []
        for u in range(w):
            # det and trace of [[a, c], [c, b]] written out from the eigenvalues
            tr = a[v][u] + b[v][u]
            disc = math.sqrt(max((a[v][u] - b[v][u]) ** 2 + 4 * c[v][u] ** 2, 0.0))
            l1, l2 = (tr + disc) / 2, (tr - disc) / 2
            row.append(l1 * l2 - alpha * (l1 + l2) ** 2)
        out.append(row)
    return out


def oracle_select(R, F, th, tl):
    out = []
    for n in range(1, len(R) - 1):
        for v in range(1, len(R[0]) - 1):
            for u in range(1, len(R[0][0]) - 1):
                nb = [R[n][v + b][u + a] for a in (-1, 0, 1) for b in (-1, 0, 1) if (a, b) != (0, 0)]
                if (R[n][v][u] > th and max(nb) < R[n][v][u] and F[n][v][u] > tl
                        and F[n][v][u] > max(F[n - 1][v][u], F[n + 1][v][u])):
                    out.append((n, u, v))
    return out


def test_measures_match_direct_computation():
    rng = random.Random(21)
    for _ in range(4):
        img = [[rng.random() for _ in range(6)] for _ in range(5)]
        for si in (1.0, 1.4):
            a, b = harris_measure(img, si, 0.7 * si, 0.06), direct_harris(img, si, 0.7 * si, 0.06)
            assert all(abs(x - y) < 1e-12 for ra, rb in zip(a, b) for x, y in zip(ra, rb))
            L = direct_blur(img, si)
            f = normalized_laplacian(img, si)
            for v in range(1, 4):
                for u in range(1, 5):
                    lap = L[v][u + 1] + L[v][u - 1] + L[v + 1][u] + L[v - 1][u] - 4 * L[v][u]
                    assert abs(f[v][u] - si * si * abs(lap)) < 1e-12


def test_selection_against_oracle():
    rng = random.Random(2004)
    for _ in range(600):
        k, h, w = rng.randint(3, 5), rng.randint(3, 6), rng.randint(3, 6)
        R = [[[rng.randint(-2, 3) for _ in range(w)] for _ in range(h)] for _ in range(k)]
        F = [[[rng.randint(0, 3) for _ in range(w)] for _ in range(h)] for _ in range(k)]
        th, tl = rng.choice([-5, 0, 1]), rng.choice([-1, 0, 1])
        assert sorted(select_points(R, F, th, tl)) == sorted(oracle_select(R, F, th, tl))


def test_worked_example_square():
    img = rect(28, 10, 18, 10, 18)
    pts = harris_laplace(img)
    assert [(u, v) for u, v, _ in pts] == [(11, 11), (17, 11), (14, 14), (11, 17), (17, 17)]
    assert all(abs(s - 1.4) < 1e-12 for u, v, s in pts if (u, v) != (14, 14))
    assert abs(pts[2][2] - 1.4 ** 4) < 1e-12
    F = [normalized_laplacian(img, 1.4 ** n)[11][11] for n in range(6)]
    assert [round(x, 4) for x in F] == [0.3541, 0.3996, 0.3468, 0.2991, 0.3259, 0.3356]


def test_blob_scale_is_the_level_of_the_blob():
    for n in (1, 2, 3, 4):
        sn = 1.4 ** n
        assert harris_laplace(blob(28, 14, 14, sn)) == [(14, 14, sn)]


def test_sharp_corner_scale_comes_from_the_pixel_grid():
    # A quarter plane has no size of its own; the only scale left is the pixel,
    # so its corner gets the same point and scale as the corner of the square.
    img = [[1.0 if u >= 14 and v >= 14 else 0.0 for u in range(28)] for v in range(28)]
    assert harris_laplace(img) == [(15, 15, 1.4)]
    F = [normalized_laplacian(img, 1.4 ** n)[14][14] for n in range(6)]
    assert all(F[n] > F[n + 1] for n in range(5))


def test_flat_and_offset():
    assert harris_laplace([[0.4] * 12 for _ in range(12)]) == []
    img = rect(28, 10, 18, 10, 18)
    assert harris_laplace([[p + 0.5 for p in r] for r in img]) == harris_laplace(img)


def test_rotation_by_90_degrees_of_the_measures():
    rng = random.Random(5)
    h, w = 7, 8
    img = [[rng.random() for _ in range(w)] for _ in range(h)]
    rot = [[img[h - 1 - j][i] for j in range(h)] for i in range(w)]
    a, b = harris_measure(img, 1.2, 0.84, 0.06), harris_measure(rot, 1.2, 0.84, 0.06)
    fa, fb = normalized_laplacian(img, 1.2), normalized_laplacian(rot, 1.2)
    for v in range(h):
        for u in range(w):
            assert abs(a[v][u] - b[u][h - 1 - v]) < 1e-12
            assert abs(fa[v][u] - fb[u][h - 1 - v]) < 1e-12

History

Krystian Mikolajczyk and Cordelia Schmid presented the detector at ICCV 2001, for indexing images under changes of scale. It joins two older ideas: the corner measure of Harris and Stephens from 1988, and the scale selection by maxima of normalized derivatives that Tony Lindeberg developed in the 1990s. Their 2004 journal paper gave the iterative and the simplified forms, the parameters ξ=1.4\xi = 1.4 and s=0.7s = 0.7, and the extension to affine shapes, the Harris-affine detector. The Harris-affine detector was one of the detectors in the comparison of affine region detectors of 2005.

References

  1. Krystian Mikolajczyk and Cordelia Schmid, Indexing based on scale invariant interest points, Proceedings of the Eighth IEEE International Conference on Computer Vision (ICCV 2001), 525-531, 2001, the sections on the scale-adapted Harris measure and the selection of the characteristic scale by the Laplacian
  2. Krystian Mikolajczyk and Cordelia Schmid, Scale and affine invariant interest point detectors, International Journal of Computer Vision 60(1), 63-86, 2004, Section 2 (Eq. 1 to 3 and Section 2.2, the Harris-Laplace detector)
  3. Tony Lindeberg, Feature detection with automatic scale selection, International Journal of Computer Vision 30(2), 79-116, 1998, the sections on scale-normalized derivatives and the selection of scales
  4. Tinne Tuytelaars and Krystian Mikolajczyk, Local invariant feature detectors, a survey, Foundations and Trends in Computer Graphics and Vision 3(3), 177-280, 2008, the part on corner detectors (Harris-Laplace)

Where this leads

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