Algorithm Search⌘K

Algorithmadvanced

KAZE features

Also called KAZE, AKAZE, accelerated KAZE.

Detect and describe features in a nonlinear scale space built by anisotropic diffusion, which blurs within regions but keeps their boundaries.

Time
O(N W H + n) worst · average · best
Space
O(N W H + n) extra
Where
H = the image height in pixels; N = the number of levels; W = the image width in pixels; n = the number of keypoints
Properties
deterministicnot exactheuristicrotation invariantscale invariant
Origin
Pablo F. Alcantarilla, Adrien Bartoli, Andrew J. Davison, 2012

KAZE finds and describes keypoints in a nonlinear scale space. SIFT and SURF build their scales with a Gaussian blur, which smooths edges as much as noise, so the position of a large structure moves and its outline fades. KAZE builds the scales with anisotropic diffusion of the Perona and Malik type: the blur is strong inside flat regions and weak across strong edges. Each level comes from the one before by one step of an implicit scheme, the AOS scheme of Weickert, ter Haar Romeny and Viergever, which is stable for any step and needs only tridiagonal solves. On these levels KAZE finds the maxima of the scale-normalized determinant of the Hessian, gives each one an orientation as SURF does, and describes it with the 64 values of the M-SURF descriptor. AKAZE, by the same first author, is a different and faster method; see the variants below.

In plain words

Make many blurred copies of the image, each more blurred than the one before. The blur is not the same everywhere: it is strong where the image is flat and weak where the brightness jumps, so outlines stay sharp while small noise goes away. In each copy, look for round spots where the brightness curves strongly in two directions, and keep a spot when it is stronger than its neighbors in the same copy and in the copies before and after. Around each spot, find the direction in which the brightness changes most. Then lay a grid around the spot in that direction, and in each of its 16 cells add up how the brightness changes. These 64 sums are the description.

The problem

The input is a gray image with WW columns and HH rows, with values in [0,1][0, 1]; a pixel is (u,v)(u, v), with uu the column and vv the row, and angles grow from the uu axis toward the vv axis. The output is a set of keypoints (u,v,σ,θ)(u, v, \sigma, \theta) with a scale σ\sigma, an orientation θ\theta and 64 values each, for feature matching.

Diffusion. The levels LL evolve by the equation ∂L/∂t=div⁡(c∇L)\partial L / \partial t = \operatorname{div}(c \nabla L) with the conductivity c=g(∣∇Lσ∣)c = g(|\nabla L_\sigma|), where LσL_\sigma is LL blurred by a small Gaussian. KAZE uses

g2=11+∣∇Lσ∣2/k2,g_2 = \frac{1}{1 + |\nabla L_\sigma|^2 / k^2},

one of the two functions of Perona and Malik. The contrast kk is the 70 percent point of the gradient magnitudes of the smoothed image: about 30 percent of the pixels have a gradient above kk, and the diffusion across those edges is slow.

Levels. With OO octaves and SS sublevels, the level i=oS+si = o S + s has

σi=σ02o+s/S,ti=12σi2,\sigma_i = \sigma_0 2^{o + s / S}, \qquad t_i = \frac{1}{2} \sigma_i^2,

since a Gaussian blur of σ\sigma is a linear diffusion for the time σ2/2\sigma^2 / 2. All levels keep the full image size. The first level is the image blurred with a Gaussian of σ0\sigma_0, and each next level is one implicit step of time τ=ti+1−ti\tau = t_{i+1} - t_i:

Li+1=(I−τ∑l=1mAl(Li))−1Li,L^{i+1} = \left( I - \tau \sum_{l=1}^{m} A_l(L^i) \right)^{-1} L^i,

where AlA_l is the diffusion along the axis ll, with the weights (cj+cn)/2(c_j + c_n) / 2 between neighbors. The AOS scheme replaces the inverse by 1m∑l(I−mτAl)−1\frac{1}{m} \sum_l (I - m \tau A_l)^{-1}, with m=2m = 2, so that every system is tridiagonal and is solved by the Thomas algorithm.

Detection. The response is LHessian=σi2(LuuLvv−Luv2)L_\text{Hessian} = \sigma_i^2 (L_{uu} L_{vv} - L_{uv}^2), with the derivatives from 3×33 \times 3 Scharr filters whose step grows with σi\sigma_i. Keypoints are the maxima over space and the two neighboring levels, above a threshold.

Description. The orientation is found as in SURF: the gradients at the points of a disk of radius 6σ6 \sigma, sampled with the step σ\sigma and weighted by a Gaussian, are summed in a window of π/3\pi / 3 that slides around the circle, and the longest sum gives θ\theta. The descriptor is M-SURF: a grid of 24σ24 \sigma turned by θ\theta, cut into 4×44 \times 4 subregions of 9σ9 \sigma that overlap by 2σ2 \sigma. In each subregion, the turned gradients (du,dv)(d_u, d_v) are weighted by a Gaussian of 2.5σ2.5 \sigma around its center and summed into (∑du,∑dv,∑∣du∣,∑∣dv∣)(\sum d_u, \sum d_v, \sum |d_u|, \sum |d_v|); each of these four values is weighted by a Gaussian of 1.5 subregions around the keypoint, and the 64 values are scaled to unit length.

The algorithm

  1. KAZE(I, σ_0, O, S, threshold)
  2. 1L_0 ← I blurred with σ_0; k ← the 70 percent point of |∇L_0|
  3. 2for i = 1, ..., O S - 1: c ← g_2(|∇ (L_{i-1} blurred with σ = 1)|, k)
  4. 3L_i ← one AOS step of time t_i - t_{i-1} from L_{i-1} with the conductivity c
  5. 4for each level i: the response σ_i² (L_uu L_vv - L_uv²) and the derivatives L_u, L_v, by Scharr filters
  6. 5keypoints ← the strict maxima of the response over 3 × 3 × 3, above the threshold, on the levels 1 to O S - 2
  7. 6for each keypoint (u, v, σ): θ ← the longest sum of the gradients in a window of π/3 over the disk of radius 6σ
  8. 7d ← the 64 values of M-SURF on the grid of 24σ turned by θ, scaled to unit length
  9. 8return the keypoints with their descriptors

Our code takes the exact 70 percent point of the sorted nonzero gradient magnitudes in place of a histogram, blurs with σ=1\sigma = 1 before the conductivity, and uses the step round⁡(σi)\operatorname{round}(\sigma_i) for the Scharr filters. The paper searches for maxima in a window of σi×σi\sigma_i \times \sigma_i after a quick 3×33 \times 3 check and refines the position to subpixel accuracy; our code uses the 3×3×33 \times 3 \times 3 window only and keeps the pixel. The Gaussian of the orientation has 2.5σ2.5 \sigma, which is our choice, and the threshold 10−410^{-4} is our default for images in [0,1][0, 1].

Example

One implicit step. On the row (0,0,1,1)(0, 0, 1, 1) with c=1c = 1 everywhere and τ=0.5\tau = 0.5, the system (I−τA)x=f(I - \tau A) x = f gives x=(1/14,3/14,11/14,13/14)x = (1/14, 3/14, 11/14, 13/14). The sum stays 2, and every value stays in [0,1][0, 1]. The step is stable however large τ\tau is: on the two pixels (0,1)(0, 1) with τ=1\tau = 1, the result is (1/3,2/3)(1/3, 2/3), not an overshoot.

The levels. With σ0=1.6\sigma_0 = 1.6 and S=3S = 3, the levels have σ=1.6,2.02,2.54,3.2,4.03,5.08,6.4,…\sigma = 1.6, 2.02, 2.54, 3.2, 4.03, 5.08, 6.4, \dots and the times t=1.28,2.03,3.23,5.12,…t = 1.28, 2.03, 3.23, 5.12, \dots; the octave oo starts at σ=1.6⋅2o\sigma = 1.6 \cdot 2^o.

An edge. On an 8×248 \times 24 image with the values 40 and 200 on the two sides of a vertical edge, scaled to [0,1][0, 1], and with O=2O = 2 and S=2S = 2, the jump between the two middle pixels is 0.1570.157 on the first level and still 0.1110.111 on the last level, of σ≈4.53\sigma \approx 4.53. A Gaussian blur with the same σ\sigma leaves a jump of only 0.0550.055. The total of the image does not change.

A blob. In a 32×3232 \times 32 image with a bright disk of radius 3 centered at (15,16)(15, 16), with O=2O = 2 and S=3S = 3, the detector finds the center (15,16)(15, 16) on the levels of σ≈2.02\sigma \approx 2.02 and σ=3.2\sigma = 3.2.

Correctness

KAZE is a heuristic, and its repeatability and matching quality are benchmark results. The proof in proofs/correctness.md shows that:

  • The Thomas algorithm solves the tridiagonal systems of the implicit step, whose matrices are strictly diagonally dominant.
  • Each implicit step, and so each AOS step, keeps the sum of the image, and every new value is a weighted mean of the old values, so the values stay between the old minimum and maximum, for every step size.
  • For a small step, the implicit step agrees with the explicit step of the diffusion up to a term of order τ2\tau^2.
  • The keypoints are exactly the strict maxima of the response over 3×3×33 \times 3 \times 3 above the threshold.
  • A positive gain of the image does not change the levels apart from the same gain, nor the orientation, nor the descriptor, since kk scales with the image.
  • A quarter turn of the image turns the levels, adds π/2\pi / 2 to the orientation and does not change the descriptor.
Proof: Correctness of KAZE featuresfull

Pixels are (u,v)(u, v) with uu the column and vv the row. For one row or one column of nn pixels with the values ff and the conductivities cj>0c_j > 0, let wj=(cj+cj+1)/2w_j = (c_j + c_{j+1}) / 2 for j=0,…,n−2j = 0, \dots, n - 2, and let AA be the matrix with (Ax)j=∑lwjl(xl−xj)(A x)_j = \sum_{l} w_{jl} (x_l - x_j), where ll runs over the neighbors j−1j - 1 and j+1j + 1 that exist and wj,j+1=wj+1,j=wjw_{j, j+1} = w_{j+1, j} = w_j. For τ≥0\tau \ge 0 the implicit step solves Mx=fM x = f with M=I−τAM = I - \tau A.

Lemma 1 (the Thomas algorithm). MM is tridiagonal with the diagonal bj=1+τ∑lwjlb_j = 1 + \tau \sum_l w_{jl} and the off-diagonal entries −τwjl≤0-\tau w_{jl} \le 0, so bj−∑lτwjl=1b_j - \sum_l \tau w_{jl} = 1. On such a matrix the Thomas algorithm never divides by 0 and returns the solution of Mx=fM x = f.

Proof. The form of MM follows from the definition of AA. The forward pass computes c0′=c0/b0c'_0 = c_0 / b_0 and cj′=cj/(bj−ajcj−1′)c'_j = c_j / (b_j - a_j c'_{j-1}), where aja_j and cjc_j are the entries left and right of the diagonal. Suppose ∣cj−1′∣≤1|c'_{j-1}| \le 1, which holds for j=1j = 1 since ∣c0∣≤b0−1<b0|c_0| \le b_0 - 1 < b_0. Then ∣bj−ajcj−1′∣≥bj−∣aj∣≥∣cj∣+1>0|b_j - a_j c'_{j-1}| \ge b_j - |a_j| \ge |c_j| + 1 > 0, so the division is safe and ∣cj′∣<1|c'_j| < 1. By induction every pivot is at least 1. The forward pass is Gaussian elimination without pivoting on a tridiagonal matrix, which keeps the zeros outside the band, and the backward pass is back substitution, so the result solves Mx=fM x = f. □\square

Lemma 2 (sum and range). Let xx solve Mx=fM x = f. Then ∑jxj=∑jfj\sum_j x_j = \sum_j f_j and min⁡jfj≤xi≤max⁡jfj\min_j f_j \le x_i \le \max_j f_j for every ii. The same holds for the AOS step 12(xrows+xcolumns)\frac{1}{2} (x_\text{rows} + x_\text{columns}) with M=I−2τAlM = I - 2 \tau A_l on every row and every column.

Proof. MM is symmetric and its row sums are 1, so its column sums are 1, and ∑jfj=∑j(Mx)j=∑jxj\sum_j f_j = \sum_j (M x)_j = \sum_j x_j. Let ii be an index with the largest xix_i. Then fi=xi+τ∑lwil(xi−xl)≥xif_i = x_i + \tau \sum_l w_{il} (x_i - x_l) \ge x_i, since every term of the sum is nonnegative, so xi≤fi≤max⁡fx_i \le f_i \le \max f. In the same way, at an index with the smallest xix_i, fi≤xif_i \le x_i. For the AOS step, the rows keep the sum of each row and the columns the sum of each column, so both keep the sum of the image, and so does their mean. Each value of both is in the range of the image, and so is their mean. □\square

So each level of the nonlinear scale space keeps the mean of the first level, and its values stay between the smallest and the largest value of the first level, for every step size.

Lemma 3 (small steps). For 0≤cj≤10 \le c_j \le 1, the solution of Mx=fM x = f satisfies ∥x−(f+τAf)∥∞≤4τ2∥f∥∞\lVert x - (f + \tau A f) \rVert_\infty \le 4 \tau^2 \lVert f \rVert_\infty. So the AOS step agrees with the explicit step L+τ(A1+A2)LL + \tau (A_1 + A_2) L of the diffusion up to a term of order τ2\tau^2.

Proof. From Mx=fM x = f, x=f+τAxx = f + \tau A x, and putting this into itself gives x=f+τAf+τ2A2xx = f + \tau A f + \tau^2 A^2 x. Each row of AA has at most two weights wjl≤1w_{jl} \le 1 and the diagonal −∑lwjl-\sum_l w_{jl}, so ∥A∥∞≤2\lVert A \rVert_\infty \le 2 and ∥A2∥∞≤4\lVert A^2 \rVert_\infty \le 4. By Lemma 2, ∥x∥∞≤∥f∥∞\lVert x \rVert_\infty \le \lVert f \rVert_\infty. For the AOS step each direction uses 2τ2 \tau, so it gives L+2τAlLL + 2 \tau A_l L up to O(τ2)O(\tau^2), and the mean of the two directions is L+τ(A1+A2)LL + \tau (A_1 + A_2) L up to O(τ2)O(\tau^2). □\square

Lemma 4 (detection). The detector returns exactly the pixels (u,v)(u, v) of the levels 1,…,N−21, \dots, N - 2, at least one pixel from the border, whose response is above the threshold and larger than the responses of the 26 other pixels of the 3×3×33 \times 3 \times 3 block around them.

Proof. The code visits these pixels, skips those with a response at most the threshold, and keeps a pixel exactly when every one of the 26 comparisons holds. □\square

Lemma 5 (gain). If the image is multiplied by a>0a > 0, every level is multiplied by aa, and the orientation and the descriptor of every point do not change.

Proof. The first blur is linear, so L0L_0 is multiplied by aa. The Scharr filters are linear, so every gradient magnitude is multiplied by aa; the order of the sorted magnitudes and the set of the nonzero ones do not change, so kk is multiplied by aa. The blur with σ=1\sigma = 1 is linear, so ∣∇Lσ∣2/k2|\nabla L_\sigma|^2 / k^2 and the conductivity do not change. For a fixed conductivity the AOS step is linear in the level, so by induction every level is multiplied by aa, and so are LuL_u and LvL_v. In the orientation all weighted gradients are multiplied by aa, so every window sum is multiplied by aa, the longest one is the same, and its angle is the same. In the descriptor every value is multiplied by aa, and the scaling to unit length removes aa. □\square

The response σ2(LuuLvv−Luv2)\sigma^2 (L_{uu} L_{vv} - L_{uv}^2) is multiplied by a2a^2, so the set of keypoints for a fixed threshold can change.

Lemma 6 (a quarter turn). Let J(u′,v′)=I(v′,n−1−u′)J(u', v') = I(v', n - 1 - u') on a square image of side nn, so that the pixel p=(u,v)p = (u, v) of II is the pixel p′=(n−1−v,u)p' = (n - 1 - v, u) of JJ. Then in exact arithmetic every level of JJ is the level of II turned the same way, the orientation at p′p' is the orientation at pp plus π/2\pi / 2, and the descriptor of JJ at p′p' with the orientation θ+π/2\theta + \pi / 2 equals the descriptor of II at pp with the orientation θ\theta.

Proof. The Gaussian kernels are symmetric and the borders repeat the pixels, so the separable blur commutes with the turn. For a Scharr filter with the step ss, the sum for ∂/∂u′\partial / \partial u' on JJ at p′p' is the sum for −∂/∂v-\partial / \partial v on II at pp, term by term, and the sum for ∂/∂v′\partial / \partial v' on JJ is the sum for ∂/∂u\partial / \partial u on II. So the gradient of JJ at p′p' is (−gv,gu)(-g_v, g_u), the gradient of II turned by +π/2+\pi / 2, with the same magnitude; the sorted magnitudes, kk and the conductivities are the same at the matching pixels. The rows of JJ are the columns of II in the reverse order, and a tridiagonal system read in the reverse order has the reversed solution, so the AOS step turns with the image. By induction this holds for every level. The orientation samples the disk at the offsets σ(i,j)\sigma (i, j) with i2+j2≤36i^2 + j^2 \le 36, a set that the turn maps onto itself, with weights that depend only on i2+j2i^2 + j^2; bilinear reads, with the clamp, commute with the turn. So the sampled gradients of JJ are those of II turned by π/2\pi / 2, every angle grows by π/2\pi / 2, the windows that start at the sample angles hold the same samples, and the longest sum is turned by π/2\pi / 2. In the descriptor, the point (x,y)(x, y) of the grid is read at the offset σR(θ+π/2)(x,y)\sigma R(\theta + \pi / 2) (x, y) in JJ, which is the offset σR(θ)(x,y)\sigma R(\theta)(x, y) in II. There the gradient of JJ is R(π/2)gR(\pi / 2) g, and turning it back by θ+π/2\theta + \pi / 2 gives the same (du,dv)(d_u, d_v) as turning gg back by θ\theta. So every sum, and the descriptor, is the same. □\square

Theorem. The code builds levels that each keep the sum and the range of the first level (Lemma 2), each the AOS step of the Perona and Malik diffusion with the conductivity g2g_2 (Lemmas 1 and 3). It returns the keypoints of Lemma 4, each with the orientation and the 64 values of M-SURF at its level. The orientation and the descriptor do not change under a positive gain (Lemma 5), and they turn with the image under a quarter turn (Lemma 6).

Proof. Line L1 computes the first level and kk. Lines L2 and L3 compute each next level by the AOS step, whose systems the Thomas algorithm solves by Lemma 1, and Lemmas 2 and 3 give its properties. Lines L4 and L5 compute the responses and keep the points of Lemma 4. Lines L6 and L7 compute the orientation and the descriptor as defined. Lemmas 5 and 6 give the two invariances. □\square

Complexity

The model is the real RAM. Let N=OSN = O S.

  • Line L1 takes O(WHlog⁡(WH))O(W H \log(W H)) time in our code, for the sort; a histogram, as in the paper, takes O(WH)O(W H).
  • Lines L2 and L3 take O(WH)O(W H) time per level: a blur with a fixed kernel, and one tridiagonal solve of length WW for each row and of length HH for each column, each in linear time.
  • Line L4 takes O(WH)O(W H) time per level, with five Scharr filters, and line L5 takes O(WH)O(W H) time per level with 26 comparisons per pixel.
  • Lines L6 and L7 read a fixed number of samples per keypoint: 113 points for the orientation and 16⋅8116 \cdot 81 for the descriptor.

Apart from the sort, the total time is O(NWH+n)O(N W H + n), and the space is O(NWH)O(N W H) for the levels and their derivatives and O(n)O(n) for the descriptors. All levels have the full size, while SIFT and SURF work on smaller octaves. The paper reports that KAZE takes more time than SURF and about the same time as SIFT, and that the nonlinear scale space is the most costly step.

Properties

  • Edge preserving. The diffusion is slow across edges with a gradient much larger than kk, so the keypoints of large structures stay at the boundaries of objects.
  • Stable for any step. The implicit AOS step keeps the range of the image for every τ\tau, so each level is one step, however long its time.
  • Scale invariant. The scale of a keypoint comes from the maximum of the response over the levels, and the grid of the descriptor scales with σ\sigma.
  • Rotation invariant. The grid and the gradients are turned by the orientation.
  • Contrast. The descriptor is scaled to unit length and kk scales with the image, so a positive gain does not change it; the threshold of the detector is not invariant.

Variants and improvements

  • Other conductivities. The paper tests g1=exp⁡(−∣∇Lσ∣2/k2)g_1 = \exp(-|\nabla L_\sigma|^2 / k^2), g2g_2 and the function g3g_3 of Weickert, and reports that g2g_2 is slightly better for repeatability.
  • Upright descriptor. Without the orientation step, the descriptor is faster, and the paper reports that it usually matches better when the images do not turn.
  • AKAZE. Accelerated KAZE (Alcantarilla, Nuevo and Bartoli, BMVC 2013) is a different method. It builds the nonlinear scale space with fast explicit diffusion in place of AOS, with a pyramid that downsamples the octaves, and it describes the points by a binary descriptor (M-LDB). It is much faster than KAZE.
  • Gaussian scale space. With g=1g = 1, the diffusion is linear and the levels approach the Gaussian scale space of SIFT and SURF.

When to use it

Use KAZE when the scenes have strong boundaries and much noise, or when the objects bend, and when time is not tight. On its benchmarks, the paper reports better repeatability than SIFT and SURF, with large gains under blur and noise. When speed matters, AKAZE, ORB or BRISK are better choices.

Pitfalls

  • AKAZE is not KAZE. The two names are often mixed; the schemes, the pyramids and the descriptors are different.
  • The contrast kk. It depends on the image. A kk that is too small stops the diffusion at weak edges and keeps noise; a kk that is too large makes the space close to the Gaussian one.
  • The normalization. The paper writes the factor σ2\sigma^2. In the terms of Lindeberg this is the normalization with γ=1/2\gamma = 1/2: in the linear case, the response of a Gaussian blob of width ss peaks at σ=s/3\sigma = s / \sqrt{3}, where the factor σ4\sigma^4 (γ=1\gamma = 1) gives σ=s\sigma = s. The keypoint scales are then smaller than the blob sizes.
  • The size of the step. The AOS step is stable for any τ\tau, but its accuracy falls for long steps, since the splitting has an error of order τ2\tau^2; the late levels of an octave are only rough approximations of the diffusion.
  • Cost. Every level has the full image size, so the memory and the time grow with the number of levels.

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.

kaze_features.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kaze-features/. The authors are listed in prov/VCC3TB.jsonl.

"""KAZE features (Alcantarilla, Bartoli and Davison): detection and description
in a nonlinear scale space.

An image is a list of H rows of W numbers; pixel (u, v) is img[v][u], with u
the column (to the right) and v the row (down). Angles grow from the u axis
toward the v axis.

1. The image, scaled to [0, 1], is blurred with a Gaussian of sigma_0. The
   contrast k is the 70 percent point of the gradient magnitudes of this image.
2. The levels have sigma_i = sigma_0 2^(o + s / S) and the times
   t_i = sigma_i^2 / 2. Each level comes from the one before by one AOS step
   of the Perona and Malik equation with the conductivity
   g2 = 1 / (1 + |grad L_sigma|^2 / k^2), where L_sigma is the level blurred
   with sigma = 1. There is no downsampling.
3. The response is sigma_i^2 (Lxx Lyy - Lxy^2), with 3 x 3 Scharr filters of
   step round(sigma_i). Keypoints are the strict maxima over 3 x 3 x 3 above a
   threshold, for the levels 1 to N - 2.
4. The orientation is the longest sum of the gradients in a window of pi / 3,
   over a disk of radius 6 sigma sampled with the step sigma.
5. The descriptor is M-SURF: a 24 sigma grid turned by the orientation, 4 x 4
   subregions of 9 sigma with the centers 5 sigma apart, a Gaussian of 2.5 sigma
   in each subregion and a Gaussian of 1.5 subregions over the grid; 64 values
   scaled to unit length.
"""

import math
from typing import List, Sequence, Tuple

Image = Sequence[Sequence[float]]
Map = List[List[float]]


def gaussian_kernel(sigma: float) -> List[float]:
    r = max(1, int(math.ceil(3 * sigma)))
    k = [math.exp(-(x * x) / (2 * sigma * sigma)) for x in range(-r, r + 1)]
    s = sum(k)
    return [x / s for x in k]


def convolve(m: Image, sigma: float) -> Map:
    """Separable Gaussian convolution with the border pixels repeated."""
    k = gaussian_kernel(sigma)
    r = len(k) // 2
    h, w = len(m), len(m[0])
    tmp = [[sum(k[i] * row[min(max(u + i - r, 0), w - 1)] for i in range(len(k))) for u in range(w)] for row in m]
    return [[sum(k[i] * tmp[min(max(v + i - r, 0), h - 1)][u] for i in range(len(k))) for u in range(w)]
            for v in range(h)]


def scharr(m: Image, step: int, axis: int) -> Map:
    """The 3 x 3 Scharr derivative with pixels `step` apart: axis 0 is d/du, axis 1 is d/dv."""
    h, w = len(m), len(m[0])

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

    s = step
    out = []
    for v in range(h):
        row = []
        for u in range(w):
            if axis == 0:
                d = sum(c * (at(u + s, v + t) - at(u - s, v + t)) for c, t in ((3, -s), (10, 0), (3, s)))
            else:
                d = sum(c * (at(u + t, v + s) - at(u + t, v - s)) for c, t in ((3, -s), (10, 0), (3, s)))
            row.append(d / (32.0 * s))
        out.append(row)
    return out


def contrast_factor(L: Image, percentile: float = 0.7) -> float:
    """The given fraction point of the nonzero gradient magnitudes of L."""
    gu, gv = scharr(L, 1, 0), scharr(L, 1, 1)
    mags = sorted(math.hypot(a, b) for ru, rv in zip(gu, gv) for a, b in zip(ru, rv))
    mags = [x for x in mags if x > 0]
    if not mags:
        return 1.0
    return mags[min(len(mags) - 1, int(percentile * len(mags)))]


def conductivity(L: Image, k: float) -> Map:
    Ls = convolve(L, 1.0)
    gu, gv = scharr(Ls, 1, 0), scharr(Ls, 1, 1)
    return [[1.0 / (1.0 + (a * a + b * b) / (k * k)) for a, b in zip(ru, rv)] for ru, rv in zip(gu, gv)]


def thomas(a: List[float], b: List[float], c: List[float], d: List[float]) -> List[float]:
    """Solve the tridiagonal system a_j x_{j-1} + b_j x_j + c_j x_{j+1} = d_j."""
    n = len(d)
    cp, dp = [0.0] * n, [0.0] * n
    cp[0], dp[0] = c[0] / b[0], d[0] / b[0]
    for j in range(1, n):
        den = b[j] - a[j] * cp[j - 1]
        cp[j] = c[j] / den
        dp[j] = (d[j] - a[j] * dp[j - 1]) / den
    x = [0.0] * n
    x[n - 1] = dp[n - 1]
    for j in range(n - 2, -1, -1):
        x[j] = dp[j] - cp[j] * x[j + 1]
    return x


def implicit_1d(f: List[float], g: List[float], tau: float) -> List[float]:
    """Solve (I - tau A) x = f, where (A x)_j = sum over the neighbors n of (g_j + g_n) / 2 (x_n - x_j)."""
    n = len(f)
    w = [(g[j] + g[j + 1]) / 2.0 for j in range(n - 1)]
    a = [0.0] + [-tau * w[j - 1] for j in range(1, n)]
    c = [-tau * w[j] for j in range(n - 1)] + [0.0]
    b = [1.0 + tau * ((w[j - 1] if j > 0 else 0.0) + (w[j] if j < n - 1 else 0.0)) for j in range(n)]
    return thomas(a, b, c, f)


def aos_step(L: Image, g: Image, tau: float) -> Map:
    """One AOS step: the mean of the implicit steps of time 2 tau along the rows and along the columns."""
    h, w = len(L), len(L[0])
    rows = [implicit_1d(list(L[v]), list(g[v]), 2 * tau) for v in range(h)]
    cols = [implicit_1d([L[v][u] for v in range(h)], [g[v][u] for v in range(h)], 2 * tau) for u in range(w)]
    return [[(rows[v][u] + cols[u][v]) / 2.0 for u in range(w)] for v in range(h)]


def level_sigmas(sigma0: float = 1.6, O: int = 4, S: int = 3) -> List[float]:
    return [sigma0 * 2 ** (o + s / S) for o in range(O) for s in range(S)]


def nonlinear_scale_space(img: Image, sigma0: float = 1.6, O: int = 4, S: int = 3) -> Tuple[List[Map], List[float], float]:
    """The levels L_i, their sigma_i and the contrast k."""
    L0 = convolve([[x / 255.0 for x in row] for row in img], sigma0)
    k = contrast_factor(L0)  # @line L1
    sig = level_sigmas(sigma0, O, S)
    levels = [L0]
    for i in range(1, len(sig)):
        g = conductivity(levels[-1], k)  # @line L2
        tau = (sig[i] ** 2 - sig[i - 1] ** 2) / 2.0
        levels.append(aos_step(levels[-1], g, tau))  # @line L3
    return levels, sig, k


def derivatives(L: Image, sigma: float):
    """Lu, Lv and the response sigma^2 (Luu Lvv - Luv^2)."""
    s = max(1, int(round(sigma)))
    lu, lv = scharr(L, s, 0), scharr(L, s, 1)
    luu, lvv, luv = scharr(lu, s, 0), scharr(lv, s, 1), scharr(lu, s, 1)
    det = [[sigma * sigma * (a * b - c * c) for a, b, c in zip(ra, rb, rc)] for ra, rb, rc in zip(luu, lvv, luv)]
    return lu, lv, det  # @line L4


def detect(dets: List[Map], sigmas: List[float], threshold: float = 1e-4):
    """Strict maxima over 3 x 3 x 3 with a response above the threshold: (u, v, i, sigma_i)."""
    out = []
    h, w = len(dets[0]), len(dets[0][0])
    for i in range(1, len(dets) - 1):
        for v in range(1, h - 1):
            for u in range(1, w - 1):
                x = dets[i][v][u]
                if x <= threshold:
                    continue
                if all(dets[j][v + dv][u + du] < x for j in (i - 1, i, i + 1)
                       for dv in (-1, 0, 1) for du in (-1, 0, 1) if (j, dv, du) != (i, 0, 0)):
                    out.append((u, v, i, sigmas[i]))  # @line L5
    return out


def bilinear(m: Image, x: float, y: float) -> float:
    h, w = len(m), len(m[0])
    x = min(max(x, 0.0), w - 1.0)
    y = min(max(y, 0.0), h - 1.0)
    x0, y0 = min(int(x), w - 2), min(int(y), h - 2)
    fx, fy = x - x0, y - y0
    return ((1 - fy) * ((1 - fx) * m[y0][x0] + fx * m[y0][x0 + 1])
            + fy * ((1 - fx) * m[y0 + 1][x0] + fx * m[y0 + 1][x0 + 1]))


def orientation(lu: Image, lv: Image, u: float, v: float, sigma: float) -> float:
    pts = []
    for j in range(-6, 7):
        for i in range(-6, 7):
            if i * i + j * j <= 36:
                wt = math.exp(-(i * i + j * j) / (2 * 2.5 ** 2))
                x, y = u + i * sigma, v + j * sigma
                pts.append((wt * bilinear(lu, x, y), wt * bilinear(lv, x, y)))
    angles = [math.atan2(b, a) for a, b in pts]
    best, best_n = 0.0, -1.0
    for a0 in angles:
        su = sv = 0.0
        for (a, b), t in zip(pts, angles):
            if (t - a0) % (2 * math.pi) < math.pi / 3:
                su, sv = su + a, sv + b
        n = su * su + sv * sv
        if n > best_n:
            best, best_n = math.atan2(sv, su), n
    return best  # @line L6


def describe(lu: Image, lv: Image, u: float, v: float, sigma: float, theta: float) -> List[float]:
    c, s = math.cos(theta), math.sin(theta)
    out = []
    for cy in (-1.5, -0.5, 0.5, 1.5):
        for cx in (-1.5, -0.5, 0.5, 1.5):
            sx = sy = ax = ay = 0.0
            for k in range(-4, 5):
                for l in range(-4, 5):
                    x, y = 5 * cx + l, 5 * cy + k
                    px, py = u + sigma * (c * x - s * y), v + sigma * (s * x + c * y)
                    gu, gv = bilinear(lu, px, py), bilinear(lv, px, py)
                    wt = math.exp(-(l * l + k * k) / (2 * 2.5 ** 2))
                    du, dv = wt * (c * gu + s * gv), wt * (-s * gu + c * gv)
                    sx, sy, ax, ay = sx + du, sy + dv, ax + abs(du), ay + abs(dv)
            g2 = math.exp(-(cx * cx + cy * cy) / (2 * 1.5 ** 2))
            out.extend([g2 * sx, g2 * sy, g2 * ax, g2 * ay])
    n = math.sqrt(sum(x * x for x in out))
    return [x / n for x in out] if n > 0 else out  # @line L7


def kaze(img: Image, sigma0: float = 1.6, O: int = 4, S: int = 3, threshold: float = 1e-4):
    """Keypoints (u, v, sigma, theta) with their 64 values."""
    levels, sig, _ = nonlinear_scale_space(img, sigma0, O, S)
    ders = [derivatives(L, s) for L, s in zip(levels, sig)]
    out = []
    for u, v, i, s in detect([d[2] for d in ders], sig, threshold):
        lu, lv, _ = ders[i]
        theta = orientation(lu, lv, u, v, s)
        out.append(((u, v, s, theta), describe(lu, lv, u, v, s, theta)))
    return out  # @line L8
test_kaze_features.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kaze-features/. The authors are listed in prov/VCC3TB.jsonl.

import math
import random

from kaze_features import (aos_step, conductivity, contrast_factor, convolve, derivatives, describe, detect,
                           implicit_1d, kaze, level_sigmas, nonlinear_scale_space, orientation, scharr, thomas)


def random_image(seed, w, h):
    rng = random.Random(seed)
    return [[rng.randint(0, 255) for _ in range(w)] for _ in range(h)]


def dense_solve(m, d):
    """Gaussian elimination with partial pivoting, the reference for the Thomas algorithm."""
    n = len(d)
    a = [row[:] + [d[i]] for i, row in enumerate(m)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(a[r][c]))
        a[c], a[p] = a[p], a[c]
        for r in range(c + 1, n):
            f = a[r][c] / a[c][c]
            for j in range(c, n + 1):
                a[r][j] -= f * a[c][j]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (a[r][n] - sum(a[r][j] * x[j] for j in range(r + 1, n))) / a[r][r]
    return x


def test_thomas_matches_dense_elimination():
    rng = random.Random(1)
    for n in (1, 2, 5, 17):
        a = [0.0] + [rng.uniform(-1, 1) for _ in range(n - 1)]
        c = [rng.uniform(-1, 1) for _ in range(n - 1)] + [0.0]
        b = [abs(a[j]) + abs(c[j]) + rng.uniform(0.5, 2) for j in range(n)]
        d = [rng.uniform(-5, 5) for _ in range(n)]
        m = [[b[i] if i == j else a[i] if j == i - 1 else c[i] if j == i + 1 else 0.0 for j in range(n)]
             for i in range(n)]
        x, y = thomas(a, b, c, d), dense_solve(m, d)
        assert all(abs(p - q) < 1e-9 for p, q in zip(x, y))


def test_aos_keeps_the_mean_and_the_range():
    rng = random.Random(2)
    L = [[rng.random() for _ in range(12)] for _ in range(10)]
    g = [[rng.uniform(0.05, 1) for _ in range(12)] for _ in range(10)]
    for tau in (0.1, 3.0, 50.0):
        out = aos_step(L, g, tau)
        assert abs(sum(map(sum, out)) - sum(map(sum, L))) < 1e-9
        lo, hi = min(map(min, L)), max(map(max, L))
        assert all(lo - 1e-12 <= x <= hi + 1e-12 for row in out for x in row)
    flat = [[0.3] * 7 for _ in range(6)]
    assert all(abs(x - 0.3) < 1e-12 for row in aos_step(flat, g, 5.0) for x in row)


def test_small_steps_agree_with_the_explicit_scheme():
    rng = random.Random(3)
    f = [rng.random() for _ in range(9)]
    g = [rng.uniform(0.2, 1) for _ in range(9)]
    tau = 1e-4
    w = [(g[j] + g[j + 1]) / 2 for j in range(8)]
    af = [(w[j - 1] * (f[j - 1] - f[j]) if j > 0 else 0) + (w[j] * (f[j + 1] - f[j]) if j < 8 else 0)
          for j in range(9)]
    x = implicit_1d(f, g, tau)
    assert all(abs(x[j] - (f[j] + tau * af[j])) < 10 * tau * tau for j in range(9))


def test_contrast_and_conductivity():
    img = random_image(4, 16, 16)
    L = convolve([[x / 255 for x in row] for row in img], 1.6)
    k = contrast_factor(L)
    gu, gv = scharr(L, 1, 0), scharr(L, 1, 1)
    mags = [math.hypot(a, b) for ru, rv in zip(gu, gv) for a, b in zip(ru, rv)]
    below = sum(1 for m in mags if m < k) / len(mags)
    assert 0.65 <= below <= 0.75
    g = conductivity(L, k)
    assert all(0 < x <= 1 for row in g for x in row)
    assert all(x == 1.0 for row in conductivity([[0.5] * 6 for _ in range(6)], k) for x in row)


def test_the_nonlinear_space_keeps_an_edge():
    img = [[200 if u >= 12 else 40 for u in range(24)] for _ in range(8)]
    levels, sig, _ = nonlinear_scale_space(img, O=2, S=2)
    assert len(levels) == 4 and abs(sig[-1] - 1.6 * 2 ** 1.5) < 1e-12
    gauss = convolve([[x / 255 for x in row] for row in img], sig[-1])
    step = lambda L: L[4][12] - L[4][11]
    assert step(levels[-1]) > step(gauss)
    assert abs(sum(map(sum, levels[-1])) - sum(map(sum, levels[0]))) < 1e-9


def test_a_blob_is_detected_at_its_center():
    img = [[230 if (u - 15) ** 2 + (v - 16) ** 2 <= 9 else 20 for u in range(32)] for v in range(32)]
    feats = kaze(img, O=2, S=3)
    assert any((u, v) == (15, 16) for (u, v, s, t), _ in feats)
    for _, d in feats:
        assert len(d) == 64 and abs(math.sqrt(sum(x * x for x in d)) - 1) < 1e-12


def test_detect_returns_strict_maxima_above_the_threshold():
    rng = random.Random(5)
    dets = [[[rng.random() for _ in range(8)] for _ in range(7)] for _ in range(4)]
    found = detect(dets, [1, 2, 3, 4], threshold=0.2)
    brute = [(u, v, i, i + 1) for i in (1, 2) for v in range(1, 6) for u in range(1, 7)
             if dets[i][v][u] > 0.2 and dets[i][v][u] == max(dets[j][v + b][u + a] for j in (i - 1, i, i + 1)
                                                             for b in (-1, 0, 1) for a in (-1, 0, 1))]
    assert found == brute


def test_orientation_on_a_ramp():
    ramp = [[3.0 * u + 2.0 * v for u in range(40)] for v in range(40)]
    lu, lv, _ = derivatives(ramp, 1.0)
    assert abs(orientation(lu, lv, 20, 20, 1.5) - math.atan2(2, 3)) < 1e-12


def test_a_quarter_turn():
    n = 24
    img = random_image(6, n, n)
    rot = [[img[n - 1 - u][v] for u in range(n)] for v in range(n)]
    la, sa, ka = nonlinear_scale_space(img, O=1, S=3)
    lb, _, kb = nonlinear_scale_space(rot, O=1, S=3)
    assert abs(ka - kb) < 1e-12
    for A, B in zip(la, lb):
        assert all(abs(A[v][u] - B[u][n - 1 - v]) < 1e-9 for v in range(n) for u in range(n))
    s = sa[2]
    ua, va, _ = derivatives(la[2], s)
    ub, vb, _ = derivatives(lb[2], s)
    for u, v in [(12, 9), (8, 14)]:
        ta, tb = orientation(ua, va, u, v, s), orientation(ub, vb, n - 1 - v, u, s)
        assert abs(math.remainder(tb - ta - math.pi / 2, 2 * math.pi)) < 1e-9
        da, db = describe(ua, va, u, v, s, ta), describe(ub, vb, n - 1 - v, u, s, ta + math.pi / 2)
        assert all(abs(x - y) < 1e-9 for x, y in zip(da, db))


def test_gain_does_not_change_the_descriptor():
    img = random_image(7, 20, 20)
    a, _, _ = nonlinear_scale_space(img, O=1, S=2)
    b, _, _ = nonlinear_scale_space([[0.5 * x for x in row] for row in img], O=1, S=2)
    s = level_sigmas(O=1, S=2)[1]
    da = describe(*derivatives(a[1], s)[:2], 10, 9, s, 0.4)
    db = describe(*derivatives(b[1], s)[:2], 10, 9, s, 0.4)
    assert all(abs(x - y) < 1e-12 for x, y in zip(da, db))

History

Perona and Malik introduced nonlinear diffusion with an edge-stopping conductivity in 1990. Weickert, ter Haar Romeny and Viergever gave the AOS scheme in 1998, which makes implicit steps cheap and stable. Alcantarilla, Bartoli and Davison joined the two with a detector and a descriptor in the style of SURF and presented KAZE at ECCV 2012. The name is the Japanese word for wind, in tribute to Iijima, the father of scale space. AKAZE followed at BMVC 2013 with fast explicit diffusion. OpenCV has both.

References

  1. Pablo F. Alcantarilla, Adrien Bartoli and Andrew J. Davison, KAZE features, European Conference on Computer Vision (ECCV), Lecture Notes in Computer Science 7577, 214-227, 2012, Section 3 (the conductivities g1, g2 and g3, the contrast k as the 70 percent point, the semi-implicit scheme), Section 4.1 (Equations 7 to 9), Section 4.2 (Equation 10 and the Scharr filters), Section 4.3 (the orientation and the M-SURF descriptor), Section 5 (O = 4 and S = 3 in the experiments, the repeatability of g2, Table 1 for the times)
  2. Joachim Weickert, Bart M. ter Haar Romeny and Max A. Viergever, Efficient and reliable schemes for nonlinear diffusion filtering, IEEE Transactions on Image Processing 7(3), 398-410, 1998, the whole paper (the AOS scheme and its properties)
  3. Herbert Bay, Andreas Ess, Tinne Tuytelaars and Luc Van Gool, Speeded-up robust features (SURF), Computer Vision and Image Understanding 110(3), 346-359, 2008, the section on orientation assignment (the sliding window of pi/3)
  4. Pablo F. Alcantarilla, Jesus Nuevo and Adrien Bartoli, Fast explicit diffusion for accelerated features in nonlinear scale spaces, British Machine Vision Conference (BMVC), 13.1-13.11, 2013, the whole paper (AKAZE, a different method that follows KAZE)

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