Algorithm Search⌘K

Algorithmcore

Difference-of-Gaussians detector

Also called DoG detector, DoG keypoint detector.

Find blobs as extrema in space and scale of the difference of adjacent Gaussian smoothed images, a cheap approximation of the scale-normalized Laplacian.

Time
O(s W H) worst · average · best
Space
Θ(s W H) extra
Where
H = the image height in pixels; W = the image width in pixels; s = the number of scales per octave
Properties
approximately scale invariantdeterministicnot exactheuristicrotation invariant response
Origin
David G. Lowe, 2004

The Difference-of-Gaussians detector, or DoG detector, solves feature detection for blobs at all scales. It blurs the image with Gaussians of growing width σ\sigma, subtracts each blurred image from the next, and keeps the points that are larger or smaller than all 26 neighbours in space and in scale. Each kept point is refined to sub-pixel position and sub-level scale by a quadratic fit, and points with low contrast or on edges are dropped. The difference of two Gaussians of widths σ\sigma and kσk\sigma is close to (k−1)(k - 1) times the scale-normalized Laplacian of Gaussian, so the detector is a fast form of Lindeberg's automatic scale selection with the Laplacian. This page is the detector only. The SIFT page covers the whole pipeline, which adds an orientation and a descriptor to each DoG keypoint and matches them. The cost is O(sWH)O(sWH) for ss scales per octave.

In plain words

Blur the image a little, then a little more, and so on. Subtract each blurred copy from the next one. What is left is strong where the image has a spot about the size of the blur: a bright spot gives a deep valley, a dark spot a high peak. A spot of a given size gives its strongest answer at the blur that matches its size. So look for the points that are stronger than everything around them, both in the image and in the list of blurs. Each such point gives a position and a size. Then throw away the weak ones and the ones that lie along an edge, because their position along the edge is not well defined. To save time, halve the image each time the blur doubles.

The problem

The input is a gray digital image II with WW columns and HH rows and 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 its center is at the integer point (u,v)(u, v). The blur uses the clamp border rule. The parameters are the number ss of scales per octave, the base scale σ0\sigma_0, the number of octaves OO, the contrast threshold cc, and the edge ratio rr. Lowe uses s=3s = 3, σ0=1.6\sigma_0 = 1.6, c=0.03c = 0.03 and r=10r = 10, and he assumes that the input already has a blur of 0.50.5.

The Gaussian scale space is L(⋅,σ)=Gσ∗IL(\cdot, \sigma) = G_\sigma \ast I, and the difference of Gaussians is

D(u,v,σ)=L(u,v,kσ)−L(u,v,σ),k=21/s.D(u, v, \sigma) = L(u, v, k\sigma) - L(u, v, \sigma), \qquad k = 2^{1/s}.

Since the Gaussian solves the heat equation ∂G/∂σ=σ∇2G\partial G / \partial \sigma = \sigma \nabla^2 G, the difference quotient gives

Gkσ−Gσ≈(k−1) σ2∇2Gσ,G_{k\sigma} - G_\sigma \approx (k - 1)\, \sigma^2 \nabla^2 G_\sigma ,

so DD is the scale-normalized Laplacian σ2∇2L\sigma^2 \nabla^2 L times the constant k−1k - 1. The constant is the same at all scales and does not move the extrema. The output is a list of keypoints (x,y,σ)(x, y, \sigma) in the pixel units of the input, each with the value of DD at the point.

The algorithm

  1. DOG-DETECTOR(I, s, σ0, O, c, r) ▷ I is W × H with values in [0, 1]
  2. 1base ← I blurred from the assumed 0.5 to σ0
  3. 2for o ← 0 to O - 1 do
  4. 3G_i ← base blurred to σ0 k^i for i = 0, …, s + 2 ▷ k = 2^(1/s), in the pixels of octave o
  5. 4D_i ← G_(i+1) - G_i for i = 0, …, s + 1
  6. 5for each sample (u, v, i) with 1 ≤ i ≤ s, off the border, larger than all 26 neighbours or smaller than all of them do
  7. 6fit a quadratic to D at the sample; while an offset is above 0.5, move to the neighbour sample and fit again (at most 5 times)
  8. 7if |D(fitted point)| ≥ c and tr(H)² · r < (r + 1)² · det(H) with det(H) > 0 then
  9. 8add (2^o x̂, 2^o ŷ, σ0 2^(o + î/s)) to keypoints
  10. 9base ← G_s sampled at every second pixel
  11. 10return keypoints

Lines L3 and L4 build one octave: s+3s + 3 Gaussian images and s+2s + 2 DoG images. Line L5 looks for extrema only in the ss middle DoG images, because each needs a level above and below, and these ss levels cover one doubling of σ\sigma. A sample is compared with its 8 neighbours in its own level and the 9 neighbours in each of the two levels next to it.

Line L6 is the fit of Brown and Lowe. With the gradient gg and the 3×33 \times 3 Hessian H\mathcal H of DD in (u,v,i)(u, v, i), taken by central differences, the second order Taylor expansion D(x)≈D+gTx+12xTHxD(\mathbf x) \approx D + g^{\mathsf T} \mathbf x + \tfrac12 \mathbf x^{\mathsf T} \mathcal H \mathbf x has its vertex at x^=−H−1g\hat{\mathbf x} = -\mathcal H^{-1} g, with the value D+12gTx^D + \tfrac12 g^{\mathsf T} \hat{\mathbf x}. If any component of x^\hat{\mathbf x} is above 0.50.5, the vertex is nearer to another sample, and the fit moves there. Line L7 drops points with low contrast and points on edges. The edge test uses the 2×22 \times 2 spatial Hessian H=(DuuDuvDuvDvv)H = \begin{pmatrix} D_{uu} & D_{uv} \\ D_{uv} & D_{vv} \end{pmatrix}: its eigenvalues are the curvatures of DD across and along the point, and the ratio tr⁡(H)2/det⁡H=(α+β)2/(αβ)\operatorname{tr}(H)^2 / \det H = (\alpha + \beta)^2 / (\alpha\beta) grows with the ratio of the eigenvalues. The test keeps the point when the ratio of the curvatures is below rr, without an eigenvalue computation. Line L9 starts the next octave. Image ss of the octave has blur 2σ02\sigma_0, so every second pixel of it has blur σ0\sigma_0 in the new pixel units.

The implementation blurs each GiG_i directly from the base by σi2−σ02\sqrt{\sigma_i^2 - \sigma_0^2}. Lowe blurs each image from the previous one; the two agree because blurs add in squares, up to the cut of the kernels.

Example

Take a 32×3232 \times 32 image of a bright Gaussian blob of width σb=3\sigma_b = 3 and height 11, centered at (16,16)(16, 16), on a black background. Use s=3s = 3, σ0=1.6\sigma_0 = 1.6 and two octaves. The levels of the first octave have σi=1.6,2.016,2.540,3.2,4.032\sigma_i = 1.6, 2.016, 2.540, 3.2, 4.032. At the center the five DoG values are

−0.0933,  −0.1096,  −0.1186,  −0.1141,  −0.0993.-0.0933, \; -0.1096, \; -0.1186, \; -0.1141, \; -0.0993 .

The smallest is at i=2i = 2, and it is smaller than all 26 neighbours, so (16,16,2)(16, 16, 2) is a candidate. The fit stays at (16,16)(16, 16) by symmetry and moves the level to ı^=2.166\hat\imath = 2.166, so σ=1.6⋅22.166/3=2.639\sigma = 1.6 \cdot 2^{2.166/3} = 2.639, with D=−0.1188D = -0.1188. The contrast is above 0.030.03 and the blob is round, so the point passes. It is the only keypoint. An inverted image, a dark blob on white, gives the same point with D=+0.1188D = +0.1188.

The scale is not 33, and the reason is exact. The blurred blob has variance t0+tt_0 + t with t0=σb2−0.52=8.75t_0 = \sigma_b^2 - 0.5^2 = 8.75, since the detector assumes the input blur 0.50.5. At the center, DD is proportional to 1t0+t−1t0+k2t\frac{1}{t_0 + t} - \frac{1}{t_0 + k^2 t} with t=σ2t = \sigma^2, and the derivative in tt is zero at t=t0/kt = t_0 / k. So the DoG between σ\sigma and kσk\sigma peaks when the geometric mean σk\sigma \sqrt{k} of the two widths matches the blob: σ=8.75/21/3=2.635\sigma = \sqrt{8.75 / 2^{1/3}} = 2.635, close to the fitted 2.6392.639.

Three other inputs show the limits. A straight vertical edge gives candidates along the edge, and all fail the edge test. The same blob with height 0.20.2 gives ∣D∣<0.03|D| < 0.03 and no keypoint. A blob with σb=2\sigma_b = 2 peaks at σ=1.73\sigma = 1.73, below the first searched level σ0k=2.016\sigma_0 k = 2.016, and is not found; this is why Lowe doubles the input image before the first octave.

Correctness

The detector finds what it defines: the samples of DD that are strict extrema among their 26 neighbours, refined by the fit and filtered by the two tests. The proof in proofs/correctness.md shows that line L5 finds exactly those samples, that the fit of line L6 returns the exact vertex when DD is a quadratic near the point, and that the edge test keeps exactly the points with det⁡H>0\det H > 0 and a ratio of curvatures below rr.

Why the extrema are the right points is a result of scale-space theory. Lindeberg showed that the extrema over scale of the scale-normalized Laplacian select a scale proportional to the size of a blob, and the derivation above shows that DD is that operator up to a constant. For a Gaussian blob the selection is exact, as the example computes. That the points are repeatable on real images is measured, not proved; see detector repeatability.

Proof: Correctness of the Difference-of-Gaussians detectorfull

We prove four facts: the extremum search of line L5 returns exactly the strict extrema among the 26 neighbours; the fit of line L6 returns the exact vertex of a quadratic; the edge test keeps exactly the points with a ratio of curvatures below rr; and for a Gaussian blob the DoG peaks at σ2=t0/k\sigma^2 = t_0 / k.

Lemma 1 (the extremum search). Line L5 returns exactly the samples (u,v,i)(u, v, i) with 1≤i≤s1 \le i \le s, 1≤u≤W′−21 \le u \le W' - 2 and 1≤v≤H′−21 \le v \le H' - 2, for an octave of size W′×H′W' \times H', such that Di(u,v)>Di′(u′,v′)D_i(u, v) > D_{i'}(u', v') for all 26 neighbours (u′,v′,i′)≠(u,v,i)(u', v', i') \ne (u, v, i) with ∣u′−u∣,∣v′−v∣,∣i′−i∣≤1|u' - u|, |v' - v|, |i' - i| \le 1, or Di(u,v)<Di′(u′,v′)D_i(u, v) < D_{i'}(u', v') for all of them.

Proof. The bounds on ii, uu and vv are the ranges of the loops, and they make every neighbour a valid sample. The implementation keeps two flags, "larger than all" and "smaller than all", both true at the start. A neighbour with a value ≥\ge the sample clears the first, and a neighbour with a value ≤\le the sample clears the second. So after all 26 neighbours the first flag is true exactly when every neighbour is strictly smaller, and the second exactly when every neighbour is strictly larger. The early exit happens only when both flags are false, and then neither can become true again, so it does not change the result. □\square

Lemma 2 (central differences are exact on quadratics). Let q(x)=a+bTx+12xTQxq(\mathbf x) = a + \mathbf b^{\mathsf T} \mathbf x + \tfrac12 \mathbf x^{\mathsf T} Q \mathbf x on Z3\mathbb Z^3 with QQ symmetric. At each point p\mathbf p, the central differences of line L6 give ∇q(p)=b+Qp\nabla q(\mathbf p) = \mathbf b + Q \mathbf p and the Hessian QQ exactly.

Proof. Write eje_j for the unit vectors. Then q(p+ej)−q(p−ej)=2ejT(b+Qp)q(\mathbf p + e_j) - q(\mathbf p - e_j) = 2 e_j^{\mathsf T}(\mathbf b + Q\mathbf p), because the terms of even order cancel; dividing by 22 gives the jj-th component of the gradient. Also q(p+ej)+q(p−ej)−2q(p)=ejTQej=Qjjq(\mathbf p + e_j) + q(\mathbf p - e_j) - 2q(\mathbf p) = e_j^{\mathsf T} Q e_j = Q_{jj}. For j≠lj \ne l, q(p+ej+el)−q(p−ej+el)−q(p+ej−el)+q(p−ej−el)q(\mathbf p + e_j + e_l) - q(\mathbf p - e_j + e_l) - q(\mathbf p + e_j - e_l) + q(\mathbf p - e_j - e_l) expands to 4ejTQel=4Qjl4 e_j^{\mathsf T} Q e_l = 4 Q_{jl}, since all other terms cancel in pairs; dividing by 44 gives QjlQ_{jl}. □\square

Lemma 3 (the fit). If DD equals a quadratic qq with an invertible QQ on all the samples read by the fit, then each step of line L6 computes the vertex x∗=−Q−1b\mathbf x^\ast = -Q^{-1}\mathbf b, and when the step does not move, it returns x∗\mathbf x^\ast and the value q(x∗)q(\mathbf x^\ast).

Proof. At the sample p\mathbf p, Lemma 2 gives g=b+Qpg = \mathbf b + Q\mathbf p and H=Q\mathcal H = Q. The offset is x^=−Q−1(b+Qp)=x∗−p\hat{\mathbf x} = -Q^{-1}(\mathbf b + Q\mathbf p) = \mathbf x^\ast - \mathbf p, so p+x^=x∗\mathbf p + \hat{\mathbf x} = \mathbf x^\ast at every step. The step returns when each component of x^\hat{\mathbf x} is at most 0.50.5 in absolute value; otherwise it moves to p+round⁡(x^)\mathbf p + \operatorname{round}(\hat{\mathbf x}), which is the nearest sample to x∗\mathbf x^\ast in each coordinate, and the next step returns, unless x∗\mathbf x^\ast is at a distance of exactly 0.50.5 from two samples. The value is q(p)+12gTx^q(\mathbf p) + \tfrac12 g^{\mathsf T}\hat{\mathbf x}. Since q(p+y)=q(p)+gTy+12yTQyq(\mathbf p + \mathbf y) = q(\mathbf p) + g^{\mathsf T}\mathbf y + \tfrac12 \mathbf y^{\mathsf T} Q \mathbf y and Qx^=−gQ\hat{\mathbf x} = -g, we get q(x∗)=q(p)+gTx^−12gTx^=q(p)+12gTx^q(\mathbf x^\ast) = q(\mathbf p) + g^{\mathsf T}\hat{\mathbf x} - \tfrac12 g^{\mathsf T}\hat{\mathbf x} = q(\mathbf p) + \tfrac12 g^{\mathsf T}\hat{\mathbf x}. □\square

Lemma 4 (the edge test). Let HH be a symmetric 2×22 \times 2 matrix with eigenvalues α\alpha and β\beta, and let r≥1r \ge 1. The test "det⁡H>0\det H > 0 and rtr⁡(H)2<(r+1)2det⁡Hr \operatorname{tr}(H)^2 < (r + 1)^2 \det H" holds exactly when α\alpha and β\beta have the same sign and max⁡(∣α∣,∣β∣)/min⁡(∣α∣,∣β∣)<r\max(|\alpha|, |\beta|) / \min(|\alpha|, |\beta|) < r.

Proof. det⁡H=αβ\det H = \alpha\beta and tr⁡H=α+β\operatorname{tr} H = \alpha + \beta. det⁡H>0\det H > 0 means that α\alpha and β\beta are nonzero with the same sign. Then let ρ=∣α∣/∣β∣≥1\rho = |\alpha| / |\beta| \ge 1, swapping the names if needed. The quotient tr⁡(H)2/det⁡H=(α+β)2/(αβ)=(ρ+1)2/ρ\operatorname{tr}(H)^2 / \det H = (\alpha + \beta)^2 / (\alpha\beta) = (\rho + 1)^2 / \rho. The function f(ρ)=(ρ+1)2/ρ=ρ+2+1/ρf(\rho) = (\rho + 1)^2 / \rho = \rho + 2 + 1/\rho is strictly increasing for ρ≥1\rho \ge 1, since f′(ρ)=1−1/ρ2>0f'(\rho) = 1 - 1/\rho^2 > 0 for ρ>1\rho > 1. So f(ρ)<f(r)f(\rho) < f(r), which after multiplication by det⁡H>0\det H > 0 is the test, holds exactly when ρ<r\rho < r. □\square

Proposition 5 (the scale of a Gaussian blob). Let the image be a Gaussian Gt0G_{t_0} of variance t0>0t_0 > 0, and let k>1k > 1. The value at the center of D=Gk2t∗Gt0−Gt∗Gt0D = G_{k^2 t} \ast G_{t_0} - G_t \ast G_{t_0}, as a function of t=σ2>0t = \sigma^2 > 0, has its single extremum at t=t0/kt = t_0 / k.

Proof. Gaussians add their variances under convolution, and a 2D Gaussian of variance τ\tau has the value 1/(2πτ)1/(2\pi\tau) at its center. So the central value is ϕ(t)=12π(1t0+k2t−1t0+t)\phi(t) = \frac{1}{2\pi}\big(\frac{1}{t_0 + k^2 t} - \frac{1}{t_0 + t}\big), which is negative for t>0t > 0 and tends to 00 at both ends. Its derivative is 12π(1(t0+t)2−k2(t0+k2t)2)\frac{1}{2\pi}\big(\frac{1}{(t_0 + t)^2} - \frac{k^2}{(t_0 + k^2 t)^2}\big). It is zero when t0+k2t=k(t0+t)t_0 + k^2 t = k(t_0 + t), that is t(k2−k)=t0(k−1)t(k^2 - k) = t_0(k - 1), so t=t0/kt = t_0 / k, and this is the only zero for t>0t > 0. □\square

Theorem. DOG-DETECTOR returns, for each octave, the samples of Lemma 1 whose fit converges within the move limit, whose fitted value has absolute value at least cc, and whose spatial Hessian passes the test of Lemma 4, each mapped to the input pixel units by the factor 2o2^o and to the scale σ02o+ı^/s\sigma_0 2^{o + \hat\imath / s}.

Proof. By Lemma 1, line L5 visits exactly the strict extrema. Line L6 discards a candidate when the fit does not converge or leaves the valid range; Lemma 3 shows what the fit returns when DD is locally quadratic. Line L7 applies the contrast test and, by Lemma 4, the edge test. Line L8 maps the point: pixel uu of octave oo is pixel 2ou2^o u of the input, since line L9 keeps every second pixel starting at 00, and level ı^\hat\imath of octave oo has blur σ0kı^\sigma_0 k^{\hat\imath} in octave pixels, which is σ02o+ı^/s\sigma_0 2^{o + \hat\imath/s} in input pixels. Line L9 is a valid start of the next octave because GsG_s has blur σ0ks=2σ0\sigma_0 k^s = 2\sigma_0, which is σ0\sigma_0 in units of the new pixels. ■\blacksquare

Complexity

The model is the real RAM. Let N=WHN = WH.

  • With σ0\sigma_0 fixed, each blur uses a kernel of constant size, so lines L3 and L4 cost O(sN)O(sN) in the first octave.
  • Line L5 makes at most 26 comparisons per DoG sample, O(sN)O(sN).
  • Lines L6 to L8 cost O(1)O(1) per candidate, at most 5 solves of a 3×33 \times 3 system.
  • Each octave has a quarter of the pixels of the one before, so the octaves together cost at most 43\frac{4}{3} times the first one.

The total time is O(sWH)O(sWH), and the space is Θ(sWH)\Theta(sWH) for the images of one octave. Doubling the input before the first octave, as Lowe does, multiplies the cost by about 4.

Properties

  • Approximately scale invariant. A change of scale of the image by 2j/s2^{j/s} moves the extrema jj levels, up to the sampling of space. Other factors fall between levels, where the fit finds them.
  • Rotation. The Gaussian and the Laplacian are isotropic, so the response does not change under rotation, up to the sampling grid.
  • Brightness. An offset does not change DD. A gain multiplies DD and so changes which points pass the contrast threshold.
  • Blobs, not corners. The response is large at the center of a spot of the matching size. Corners give a weaker response near the corner, and edges are removed by the edge test.
  • Both polarities. Bright blobs give minima and dark blobs give maxima, and both are kept.
  • Approximation. The DoG is close to the scale-normalized Laplacian only for kk near 11. For the Gaussian blob the peak is at σ2=t0/k\sigma^2 = t_0/k instead of t0t_0, a fixed factor that is the same for every blob and so does not hurt the invariance.

Variants and improvements

  • Laplacian of Gaussian. Compute σ2∇2L\sigma^2 \nabla^2 L directly, as in Lindeberg's blob detector. It is more costly and the extrema are almost the same.
  • Determinant of the Hessian. Use σ4det⁡HL\sigma^4 \det \mathcal H L, which does not respond to edges and needs no edge test. See the DoH detector, and SURF for a fast box-filter form.
  • Harris-Laplace. Choose the position by the Harris response and only the scale by the Laplacian. See the Harris-Laplace detector.
  • Affine shape. Adapt an ellipse to each point by the second moment matrix, as in the Harris-affine detector.
  • Nonlinear scale space. KAZE replaces the Gaussian by a nonlinear diffusion that keeps edges sharp.

When to use it

Use it to find keypoints for matching between images taken at different scales and rotations: panoramas, structure from motion, object recognition. It is the standard choice when the SIFT descriptor follows. For real-time work FAST or a box-filter Hessian is faster. For large viewpoint changes, add affine adaptation or use MSER.

Pitfalls

  • Missing small blobs. The first searched level is σ0k\sigma_0 k, so blobs smaller than that are lost. Double the image before the first octave, as Lowe does.
  • Wrong input range. The threshold 0.030.03 assumes values in [0,1][0, 1] and s=3s = 3. For 8-bit values, scale it by 255, and for other ss, by (k−1)(k - 1) relative to 21/3−12^{1/3} - 1.
  • Strict comparison. The test must be strict: on a flat area every sample equals its neighbours, and a test with ≥\ge would return every sample.
  • Skipping the move in the fit. If an offset is above 0.50.5 and the fit does not move, the refined point can be far from the sample and wrong.
  • Wrong blur of the next octave. The next octave starts from image ss, the one with blur 2σ02\sigma_0, not from the last image s+2s + 2.

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.

difference_of_gaussians_detector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/difference-of-gaussians-detector/. The authors are listed in prov/832KGB.jsonl.

"""Difference-of-Gaussians (DoG) keypoint detector, the detector part of SIFT.

An image is a list of H rows of W floats in [0, 1]; pixel (u, v) is img[v][u],
with u the column (to the right) and v the row (down). The blur is a sampled
Gaussian, cut at radius ceil(3 sigma) and normalized to sum 1, applied to rows
and then to columns with the clamp border rule.

Each octave has s + 3 Gaussian images with sigma_i = sigma0 k^i, k = 2^(1/s),
in the pixel units of the octave, and s + 2 DoG images D_i = G_(i+1) - G_i.
A sample (u, v, i) with 1 <= i <= s, not on the border of the octave, is a
candidate when it is larger than all 26 neighbours or smaller than all of
them. A candidate is refined by fitting a quadratic to D (a 3 x 3 solve). It
is kept when |D| at the fitted point is at least the contrast threshold and
the spatial Hessian passes the edge test tr^2 / det < (r + 1)^2 / r.
"""

import math
from typing import List, Optional, Sequence, Tuple

Image = List[List[float]]


def gaussian_kernel(sigma: float) -> List[float]:
    """Sampled Gaussian on -R..R with R = ceil(3 sigma), normalized to sum 1."""
    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 the clamp border rule: rows, then columns."""
    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 octave_stack(base: Image, s: int, sigma0: float) -> Tuple[List[Image], List[Image]]:
    """Return the s + 3 Gaussian images and the s + 2 DoG images of one octave.

    base has blur sigma0. Image i is base blurred by sqrt(sigma_i^2 - sigma0^2).
    """
    k = 2.0 ** (1.0 / s)
    gauss = []
    for i in range(s + 3):
        si = sigma0 * k ** i
        gauss.append(blur(base, math.sqrt(max(si * si - sigma0 * sigma0, 0.0))) if i else [row[:] for row in base])
    dog = [[[a - b for a, b in zip(r1, r0)] for r1, r0 in zip(gauss[i + 1], gauss[i])] for i in range(s + 2)]
    return gauss, dog


def find_extrema(dog: List[Image]) -> List[Tuple[int, int, int]]:
    """Samples (i, u, v), 1 <= i <= len(dog) - 2, off the border, larger or smaller than all 26 neighbours."""
    out = []
    h, w = len(dog[0]), len(dog[0][0])
    for i in range(1, len(dog) - 1):
        for v in range(1, h - 1):
            for u in range(1, w - 1):
                x = dog[i][v][u]
                hi = lo = True
                for di in (-1, 0, 1):
                    plane = dog[i + di]
                    for dv in (-1, 0, 1):
                        row = plane[v + dv]
                        for du in (-1, 0, 1):
                            if di == 0 and dv == 0 and du == 0:
                                continue
                            y = row[u + du]
                            if y >= x:
                                hi = False
                            if y <= x:
                                lo = False
                    if not (hi or lo):
                        break
                if hi or lo:
                    out.append((i, u, v))
    return out


def _solve3(m: List[List[float]], b: List[float]) -> Optional[List[float]]:
    """Solve m x = b by Cramer's rule; None if m is singular."""
    def det(a):
        return (a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
                - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
                + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
    d = det(m)
    if abs(d) < 1e-15:
        return None
    out = []
    for c in range(3):
        a = [[b[r] if j == c else m[r][j] for j in range(3)] for r in range(3)]
        out.append(det(a) / d)
    return out


def refine(dog: List[Image], i: int, u: int, v: int, max_steps: int = 5):
    """Fit a quadratic to D around (u, v, i) and move to a neighbour while an offset exceeds 0.5.

    Return (u + du, v + dv, i + di, value, (dxx, dyy, dxy)) or None.
    """
    h, w = len(dog[0]), len(dog[0][0])
    for _ in range(max_steps):
        d = lambda a, b, c: dog[c][b][a]
        g = [(d(u + 1, v, i) - d(u - 1, v, i)) / 2,
             (d(u, v + 1, i) - d(u, v - 1, i)) / 2,
             (d(u, v, i + 1) - d(u, v, i - 1)) / 2]
        c0 = d(u, v, i)
        dxx = d(u + 1, v, i) + d(u - 1, v, i) - 2 * c0
        dyy = d(u, v + 1, i) + d(u, v - 1, i) - 2 * c0
        dss = d(u, v, i + 1) + d(u, v, i - 1) - 2 * c0
        dxy = (d(u + 1, v + 1, i) - d(u - 1, v + 1, i) - d(u + 1, v - 1, i) + d(u - 1, v - 1, i)) / 4
        dxs = (d(u + 1, v, i + 1) - d(u - 1, v, i + 1) - d(u + 1, v, i - 1) + d(u - 1, v, i - 1)) / 4
        dys = (d(u, v + 1, i + 1) - d(u, v - 1, i + 1) - d(u, v + 1, i - 1) + d(u, v - 1, i - 1)) / 4
        hess = [[dxx, dxy, dxs], [dxy, dyy, dys], [dxs, dys, dss]]
        off = _solve3(hess, [-x for x in g])
        if off is None:
            return None
        if all(abs(x) <= 0.5 for x in off):
            value = c0 + 0.5 * sum(a * b for a, b in zip(g, off))
            return (u + off[0], v + off[1], i + off[2], value, (dxx, dyy, dxy))
        u += int(round(off[0]))
        v += int(round(off[1]))
        i += int(round(off[2]))
        if not (1 <= i <= len(dog) - 2 and 1 <= u <= w - 2 and 1 <= v <= h - 2):
            return None
    return None


def passes_edge_test(dxx: float, dyy: float, dxy: float, r: float = 10.0) -> bool:
    """tr^2 / det < (r + 1)^2 / r with det > 0."""
    tr, det = dxx + dyy, dxx * dyy - dxy * dxy
    return det > 0 and tr * tr * r < (r + 1) ** 2 * det


def dog_keypoints(img: Sequence[Sequence[float]], s: int = 3, sigma0: float = 1.6, octaves: int = 2,
                  contrast: float = 0.03, edge_r: float = 10.0, sigma_in: float = 0.5):
    """Return keypoints (x, y, sigma, value) in the pixel units of the input image.

    Precondition: img is a rectangular list of rows of floats in [0, 1],
    s >= 1, 0 <= sigma_in < sigma0 and octaves >= 1. An octave smaller than
    3 x 3 pixels is not searched.
    """
    base = blur(img, math.sqrt(sigma0 * sigma0 - sigma_in * sigma_in))  # @line L1
    keys = []
    for o in range(octaves):  # @line L2
        if len(base) < 3 or len(base[0]) < 3:
            break
        gauss, dog = octave_stack(base, s, sigma0)  # @line L3 @line L4
        for i, u, v in find_extrema(dog):  # @line L5
            fit = refine(dog, i, u, v)  # @line L6
            if fit is None:
                continue
            x, y, si, value, (dxx, dyy, dxy) = fit
            if abs(value) >= contrast and passes_edge_test(dxx, dyy, dxy, edge_r):  # @line L7
                f = 2 ** o
                keys.append((x * f, y * f, sigma0 * 2 ** (o + si / s), value))  # @line L8
        base = [row[::2] for row in gauss[s][::2]]  # @line L9
    return keys  # @line L10
test_difference_of_gaussians_detector.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/difference-of-gaussians-detector/. The authors are listed in prov/832KGB.jsonl.

import math
import random

from difference_of_gaussians_detector import (
    blur,
    dog_keypoints,
    find_extrema,
    gaussian_kernel,
    octave_stack,
    passes_edge_test,
    refine,
)


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


def direct_blur(img, sigma):
    """2D convolution with the outer product of the kernel, clamp border."""
    k = gaussian_kernel(sigma)
    r = len(k) // 2
    h, w = len(img), len(img[0])
    out = []
    for v in range(h):
        row = []
        for u in range(w):
            acc = 0.0
            for j in range(-r, r + 1):
                for i in range(-r, r + 1):
                    acc += k[i + r] * k[j + r] * img[min(max(v + j, 0), h - 1)][min(max(u + i, 0), w - 1)]
            row.append(acc)
        out.append(row)
    return out


def oracle_extrema(dog):
    out = []
    levels, h, w = len(dog), len(dog[0]), len(dog[0][0])
    for i in range(1, levels - 1):
        for v in range(1, h - 1):
            for u in range(1, w - 1):
                x = dog[i][v][u]
                nb = [dog[i + a][v + b][u + c] for a in (-1, 0, 1) for b in (-1, 0, 1) for c in (-1, 0, 1)
                      if (a, b, c) != (0, 0, 0)]
                if all(y < x for y in nb) or all(y > x for y in nb):
                    out.append((i, u, v))
    return out


def test_kernel_is_normalized_and_symmetric():
    for sigma in (0.5, 1.0, 1.6, 2.7):
        k = gaussian_kernel(sigma)
        assert abs(sum(k) - 1) < 1e-12
        assert k == k[::-1]
        assert len(k) == 2 * math.ceil(3 * sigma) + 1


def test_separable_blur_matches_direct_convolution():
    rng = random.Random(4)
    for _ in range(15):
        w, h = rng.randint(3, 8), rng.randint(3, 8)
        img = [[rng.random() for _ in range(w)] for _ in range(h)]
        for sigma in (0.7, 1.3):
            a, b = blur(img, sigma), direct_blur(img, sigma)
            assert all(abs(x - y) < 1e-12 for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def test_extrema_against_oracle():
    rng = random.Random(2004)
    for _ in range(600):
        levels, h, w = rng.randint(3, 5), rng.randint(3, 6), rng.randint(3, 6)
        dog = [[[rng.randint(-3, 3) for _ in range(w)] for _ in range(h)] for _ in range(levels)]
        assert sorted(find_extrema(dog)) == sorted(oracle_extrema(dog))


def test_refine_recovers_the_vertex_of_a_quadratic():
    rng = random.Random(9)
    for _ in range(50):
        u0, v0, i0 = rng.uniform(3.6, 5.4), rng.uniform(3.6, 5.4), rng.uniform(1.6, 2.4)
        c = rng.uniform(0.1, 1)

        def q(u, v, i):
            du, dv, di = u - u0, v - v0, i - i0
            return c - (2 * du * du + 3 * dv * dv + di * di + du * dv + 0.5 * du * di)

        dog = [[[q(u, v, i) for u in range(9)] for v in range(9)] for i in range(5)]
        # The vertex can be more than 0.5 away from (4, 4, 2), so the fit may have to move.
        fit = refine(dog, 2, 4, 4, 5)
        assert fit is not None
        x, y, s, value, _ = fit
        assert abs(x - u0) < 1e-9 and abs(y - v0) < 1e-9 and abs(s - i0) < 1e-9
        assert abs(value - c) < 1e-9
        fit2 = refine(dog, 1 if i0 > 2 else 3, 3, 6, 5)
        assert fit2 is not None and abs(fit2[0] - u0) < 1e-9 and abs(fit2[2] - i0) < 1e-9


def test_edge_test():
    assert passes_edge_test(-1.0, -1.0, 0.0)
    assert passes_edge_test(-1.0, -9.0, 0.0)  # ratio 9 < 10
    assert not passes_edge_test(-1.0, -11.0, 0.0)  # ratio 11 > 10
    assert not passes_edge_test(-1.0, 1.0, 0.0)  # saddle
    assert not passes_edge_test(-1.0, -1.0, 1.0)  # det = 0


def test_worked_example_blob():
    img = blob(32, 16, 16, 3.0)
    base = blur(img, math.sqrt(1.6 ** 2 - 0.5 ** 2))
    _, dog = octave_stack(base, 3, 1.6)
    centre = [dog[i][16][16] for i in range(5)]
    assert [round(x, 4) for x in centre] == [-0.0933, -0.1096, -0.1186, -0.1141, -0.0993]
    keys = dog_keypoints(img)
    assert len(keys) == 1
    x, y, sigma, value = keys[0]
    assert abs(x - 16) < 1e-6 and abs(y - 16) < 1e-6
    assert abs(sigma - 2.639) < 1e-3 and abs(value + 0.1188) < 1e-4
    # The DoG between sigma and k sigma peaks at sigma^2 = t0 / k, with t0 the blob variance less 0.5^2.
    assert abs(sigma - math.sqrt((9 - 0.25) / 2 ** (1 / 3))) < 0.01


def test_blob_scale_follows_blob_size_and_polarity():
    for sb in (3.0, 4.0):
        (x, y, sigma, value), = dog_keypoints(blob(32, 16, 16, sb))
        assert abs(sigma - math.sqrt((sb * sb - 0.25) / 2 ** (1 / 3))) < 0.03 * sigma
        assert value < 0
    dark = [[1 - p for p in r] for r in blob(32, 16, 16, 3.0)]
    (x, y, sigma, value), = dog_keypoints(dark)
    assert value > 0 and abs(sigma - 2.639) < 1e-3


def test_small_blob_needs_a_finer_first_level():
    # sigma 1.73 is below the first searched level sigma0 k = 2.02.
    assert dog_keypoints(blob(32, 16, 16, 2.0)) == []


def test_edge_and_flat_and_low_contrast_give_nothing():
    edge = [[1.0 if u >= 16 else 0.0 for u in range(32)] for v in range(32)]
    assert dog_keypoints(edge) == []
    assert dog_keypoints([[0.5] * 20 for _ in range(20)]) == []
    assert dog_keypoints(blob(32, 16, 16, 3.0, 0.2)) == []


def test_offset_does_not_move_keypoints():
    img = blob(32, 15, 17, 3.5, 0.6)
    a = dog_keypoints(img)
    b = dog_keypoints([[p + 0.3 for p in r] for r in img])
    assert len(a) == len(b) == 1
    assert all(abs(p - q) < 1e-9 for p, q in zip(a[0], b[0]))

History

The difference of Gaussians was used as a model of center-surround receptive fields in the retina, and as a band-pass pyramid in early image analysis. Lindeberg's scale-space theory of the 1990s gave the scale-normalized Laplacian and the rule to select scales at its extrema. Lowe used the DoG as a fast approximation of that operator for the keypoints of SIFT, first at ICCV 1999 and in full in his 2004 journal paper, which also added the quadratic fit, after Brown and Lowe (2002), and the edge test. The DoG detector became the most used scale invariant keypoint detector of the next decade.

References

  1. David G. Lowe, Distinctive image features from scale-invariant keypoints, International Journal of Computer Vision 60(2), 91-110, 2004, Section 3 (the DoG and its relation to the scale-normalized Laplacian, the 26 neighbours, the choice of 3 scales per octave and sigma = 1.6), Section 4 (the quadratic fit and the contrast threshold 0.03), Section 4.1 (the edge test with r = 10)
  2. Tony Lindeberg, Feature detection with automatic scale selection, International Journal of Computer Vision 30(2), 79-116, 1998, the sections on blob detection with the scale-normalized Laplacian
  3. 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 blob detectors (the Laplacian, the DoG and the Hessian)
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 7, Section 7.1.1, Feature detectors (scale invariance and the DoG)

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