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.
- Solves
- Feature matching
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactheuristicrotation invariantscale invariant
- Evidence
- Proof sketchCode in 1 languages
- 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 columns and rows, with values in ; a pixel is , with the column and the row, and angles grow from the axis toward the axis. The output is a set of keypoints with a scale , an orientation and 64 values each, for feature matching.
Diffusion. The levels evolve by the equation with the conductivity , where is blurred by a small Gaussian. KAZE uses
one of the two functions of Perona and Malik. The contrast is the 70 percent point of the gradient magnitudes of the smoothed image: about 30 percent of the pixels have a gradient above , and the diffusion across those edges is slow.
Levels. With octaves and sublevels, the level has
since a Gaussian blur of is a linear diffusion for the time . All levels keep the full image size. The first level is the image blurred with a Gaussian of , and each next level is one implicit step of time :
where is the diffusion along the axis , with the weights between neighbors. The AOS scheme replaces the inverse by , with , so that every system is tridiagonal and is solved by the Thomas algorithm.
Detection. The response is , with the derivatives from Scharr filters whose step grows with . 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 , sampled with the step and weighted by a Gaussian, are summed in a window of that slides around the circle, and the longest sum gives . The descriptor is M-SURF: a grid of turned by , cut into subregions of that overlap by . In each subregion, the turned gradients are weighted by a Gaussian of around its center and summed into ; 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
KAZE(I, σ_0, O, S, threshold)- 1
L_0 ← I blurred with σ_0; k ← the 70 percent point of |∇L_0| - 2
for i = 1, ..., O S - 1: c ← g_2(|∇ (L_{i-1} blurred with σ = 1)|, k) - 3
L_i ← one AOS step of time t_i - t_{i-1} from L_{i-1} with the conductivity c - 4
for each level i: the response σ_i² (L_uu L_vv - L_uv²) and the derivatives L_u, L_v, by Scharr filters - 5
keypoints ← the strict maxima of the response over 3 × 3 × 3, above the threshold, on the levels 1 to O S - 2 - 6
for each keypoint (u, v, σ): θ ← the longest sum of the gradients in a window of π/3 over the disk of radius 6σ - 7
d ← the 64 values of M-SURF on the grid of 24σ turned by θ, scaled to unit length - 8
return 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 before the conductivity, and uses the step for the Scharr filters. The paper searches for maxima in a window of after a quick check and refines the position to subpixel accuracy; our code uses the window only and keeps the pixel. The Gaussian of the orientation has , which is our choice, and the threshold is our default for images in .
Example
One implicit step. On the row with everywhere and , the system gives . The sum stays 2, and every value stays in . The step is stable however large is: on the two pixels with , the result is , not an overshoot.
The levels. With and , the levels have and the times ; the octave starts at .
An edge. On an image with the values 40 and 200 on the two sides of a vertical edge, scaled to , and with and , the jump between the two middle pixels is on the first level and still on the last level, of . A Gaussian blur with the same leaves a jump of only . The total of the image does not change.
A blob. In a image with a bright disk of radius 3 centered at , with and , the detector finds the center on the levels of and .
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 .
- The keypoints are exactly the strict maxima of the response over 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 scales with the image.
- A quarter turn of the image turns the levels, adds to the orientation and does not change the descriptor.
Proof: Correctness of KAZE featuresfull
Pixels are with the column and the row. For one row or one column of pixels with the values and the conductivities , let for , and let be the matrix with , where runs over the neighbors and that exist and . For the implicit step solves with .
Lemma 1 (the Thomas algorithm). is tridiagonal with the diagonal and the off-diagonal entries , so . On such a matrix the Thomas algorithm never divides by 0 and returns the solution of .
Proof. The form of follows from the definition of . The forward pass computes and , where and are the entries left and right of the diagonal. Suppose , which holds for since . Then , so the division is safe and . 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 .
Lemma 2 (sum and range). Let solve . Then and for every . The same holds for the AOS step with on every row and every column.
Proof. is symmetric and its row sums are 1, so its column sums are 1, and . Let be an index with the largest . Then , since every term of the sum is nonnegative, so . In the same way, at an index with the smallest , . 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.
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 , the solution of satisfies . So the AOS step agrees with the explicit step of the diffusion up to a term of order .
Proof. From , , and putting this into itself gives . Each row of has at most two weights and the diagonal , so and . By Lemma 2, . For the AOS step each direction uses , so it gives up to , and the mean of the two directions is up to .
Lemma 4 (detection). The detector returns exactly the pixels of the levels , 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 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.
Lemma 5 (gain). If the image is multiplied by , every level is multiplied by , and the orientation and the descriptor of every point do not change.
Proof. The first blur is linear, so is multiplied by . The Scharr filters are linear, so every gradient magnitude is multiplied by ; the order of the sorted magnitudes and the set of the nonzero ones do not change, so is multiplied by . The blur with is linear, so 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 , and so are and . In the orientation all weighted gradients are multiplied by , so every window sum is multiplied by , the longest one is the same, and its angle is the same. In the descriptor every value is multiplied by , and the scaling to unit length removes .
The response is multiplied by , so the set of keypoints for a fixed threshold can change.
Lemma 6 (a quarter turn). Let on a square image of side , so that the pixel of is the pixel of . Then in exact arithmetic every level of is the level of turned the same way, the orientation at is the orientation at plus , and the descriptor of at with the orientation equals the descriptor of at with the orientation .
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 , the sum for on at is the sum for on at , term by term, and the sum for on is the sum for on . So the gradient of at is , the gradient of turned by , with the same magnitude; the sorted magnitudes, and the conductivities are the same at the matching pixels. The rows of are the columns of 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 with , a set that the turn maps onto itself, with weights that depend only on ; bilinear reads, with the clamp, commute with the turn. So the sampled gradients of are those of turned by , every angle grows by , the windows that start at the sample angles hold the same samples, and the longest sum is turned by . In the descriptor, the point of the grid is read at the offset in , which is the offset in . There the gradient of is , and turning it back by gives the same as turning back by . So every sum, and the descriptor, is the same.
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 (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 . 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.
Complexity
The model is the real RAM. Let .
- Line L1 takes time in our code, for the sort; a histogram, as in the paper, takes .
- Lines L2 and L3 take time per level: a blur with a fixed kernel, and one tridiagonal solve of length for each row and of length for each column, each in linear time.
- Line L4 takes time per level, with five Scharr filters, and line L5 takes 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 for the descriptor.
Apart from the sort, the total time is , and the space is for the levels and their derivatives and 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 , 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 , 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 .
- Rotation invariant. The grid and the gradients are turned by the orientation.
- Contrast. The descriptor is scaled to unit length and 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 , and the function of Weickert, and reports that 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 , 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 . It depends on the image. A that is too small stops the diffusion at weak edges and keeps noise; a that is too large makes the space close to the Gaussian one.
- The normalization. The paper writes the factor . In the terms of Lindeberg this is the normalization with : in the linear case, the response of a Gaussian blob of width peaks at , where the factor () gives . The keypoint scales are then smaller than the blob sizes.
- The size of the step. The AOS step is stable for any , but its accuracy falls for long steps, since the splitting has an error of order ; 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.
# 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
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VCC3TB Edit this page History Report an error Markdown