Algorithmadvanced
Kernelized correlation filter
Also called KCF tracker.
Ridge regression on all cyclic shifts of the target patch, made fast because for shift-invariant kernels the kernel matrix of the shifts is circulant and diagonal in the Fourier domain.
- Solves
- Visual object tracking
- Time
- Θ(N P log P) worst · average · best
- Space
- Θ(P) extra
- Where
- N = the number of frames tracked; P = the number of pixels in the patch
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativelocalonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- João F. Henriques, Rui Caseiro, Pedro Martins, Jorge Batista, 2015
The kernelized correlation filter (KCF) is a tracker that trains a ridge regression on every cyclic shift of the patch around the target. Each shifted patch is a training sample, with a label that is high for small shifts and low for large ones. With pixels there are samples, and solving the regression directly would cost a system per frame. Henriques, Caseiro, Martins and Batista showed that for a kernel that does not change when both of its arguments are shifted in the same way, the kernel matrix of all shifts is circulant. A circulant matrix is diagonal in the basis of the discrete Fourier transform, so the solution and the responses at all shifts of a new patch cost a few FFTs. With the linear kernel the method reduces to a MOSSE filter trained on one patch; with a Gaussian kernel it is a nonlinear regression at almost the same cost.
In plain words
To find the target in the next picture, we train a scorer that says how well a patch is centered on the target. Good examples are the target patch itself; bad examples are copies of it moved a little to the side. KCF uses every possible move as an example, with a score that drops the farther the move is. That many examples would normally make training slow. But all the examples are moves of the same patch, so the comparison between any two of them depends only on the difference of the two moves. That pattern lets the frequency transform do the whole training with one division per frequency, and lets it score every position of the next patch in one go.
The problem
A patch is an real array with pixels and , powers of two, indexed modulo its size. The cyclic shift by is . The training set is with labels , where is taken in , so the label is 1 for and falls off with the size of the shift. Kernel ridge regression with a kernel and asks for
as given by the kernel trick. For a new patch , the response at is : if , the target moved by and the response at is , close to the peak label.
The key condition is permutation invariance: . It holds for the linear kernel and for the Gaussian kernel (the division by follows the authors' code). Under it, with , so is circulant. With the entry-by-entry product and the DFT,
Both kernel arrays come from one correlation computed by FFT: for every is the inverse transform of , and .
The algorithm
KERNEL(z, x) ▷ k[s] = κ(z, S_s x) for every shift s- 1
c ← IFFT(ẑ ⊙ conj(x̂)) ▷ c[s] = ⟨z, S_s x⟩ - 2
return exp(-(|z|² + |x|² - 2c) / (σ² P)) ▷ or c / P for the linear kernel TRAIN(x, y)- 3
k ← KERNEL(x, x) - 4
return α̂ ← ŷ / (k̂ + λ) DETECT(α̂, x, z)- 5
k_z ← KERNEL(z, x) - 6
return IFFT(k̂_z ⊙ conj(α̂)) TRACK(F_t) ▷ model x, α̂; position p- 7
resp ← DETECT(α̂, x, features of F_t at p) - 8
p ← p + the shift d of the largest value of resp - 9
x′ ← features of F_t at p; α̂′ ← TRAIN(x′, y) - 10
x ← (1 - γ) x + γ x′; α̂ ← (1 - γ) α̂ + γ α̂′ - 11
return p
The features of a frame at are a patch centered at and larger than the target, so that it holds some background, multiplied by a cosine window. The paper uses raw gray values or HOG cells of 4 pixels. Its parameters are , the label width for a target of pixels (counted in cells for HOG), and for raw pixels, and and for HOG. For multichannel features, line L1 sums the correlation over the channels.
Example
The linear kernel by hand. Take one row, and , the patch , the labels , the linear kernel and . The kernel array is , the autocorrelation of divided by 4:
These are , since . With , , and . The response to itself is , with the peak at shift 0. For the response is : the peak has moved to shift 1. The frequency where gets the large coefficient , but in the response it is multiplied by , which is 0 there for every shift of .
Against brute force. For random patches (), the tests build the matrix from the definition and solve it directly. The from line L4 and the responses from line L6 agree with the direct solution to about for both the linear and the Gaussian kernel, and with the linear kernel the responses equal those of primal ridge regression on the 32 shifted patches.
Tracking. The frames are with a background of Gaussian blobs and a target with its own blob texture, which moves by per frame. The features are raw gray values scaled to on a patch with a cosine window, with , , and . Over 9 frames, every tracked center is within 1.2 pixels of the truth; the error comes from the integer peak, since the true centers are not on the pixel grid.
Correctness
The full proof is in proofs/correctness.md. These are theorems.
- Circulant Gram matrix. If is permutation invariant, depends only on . This is Theorem 1 of Henriques and colleagues. A kernel that weights pixel positions does not have this property, and the Fourier formulas then do not solve its regression.
- Diagonalization. A circulant matrix acts as a circular convolution, so the DFT turns into . Since is positive semidefinite, , and the division is always defined.
- Kernel arrays. Lines L1 and L2 compute for every exactly, by the correlation theorem.
- Detection. Line L6 gives for every .
- Linear case. With the linear kernel, the dual solution and primal ridge regression on the shifted patches give the same function.
These are exact for the training set of cyclic shifts. Real motion brings new content in at the border, so the claim that the response peak is the motion of the target is a heuristic, and the running averages of line L10 are a heuristic as well.
Proof: For a permutation-invariant kernel the Gram matrix of all cyclic shifts is circulant, so the Fourier formulas of the kernelized correlation filter give exactly the kernel ridge regression solution and its responsesfull
Notation as on the page. Patches are real arrays on the group of size , the shift is , and the DFT is with the characters ; the inverse has the factor . A kernel is symmetric and positive semidefinite, and it is permutation invariant for the shifts if for all , and .
Claim 1: the Gram matrix of the shifts is circulant
Let for . If is permutation invariant, then with .
Proof. and , so .
The Gaussian kernel and the linear kernel are permutation invariant, because a shift permutes the entries and does not change a norm or an inner product. A kernel that weights pixel positions differently is not, and its Gram matrix is not circulant; the tests check both cases.
Also by invariance and symmetry, so is even and is real.
Claim 2: the DFT diagonalizes a circulant matrix
For , the transform is when is even.
Proof. since is even, which is the circular convolution of and . By the convolution theorem, : substitute in and use .
So the eigenvalues of are the values , , with the characters as eigenvectors. Because is positive semidefinite (a Gram matrix of a positive semidefinite kernel), every .
Claim 3: the training formula gives the ridge regression coefficients
Kernel ridge regression on the samples with labels has the dual coefficients for . Then
Proof. By Claim 2, becomes after the DFT, which is one to one. Each , so the division is defined and the solution is unique.
Lines L3 and L4 compute exactly this, with from line L1 and line L2.
Claim 4: lines L1 and L2 compute the kernel at every shift
, the circular correlation of with at , has the transform (the correlation theorem, proved on the MOSSE filter page; is real). So line L1 gives for every . For the linear kernel . For the Gaussian kernel , which is line L2. The clamp at 0 only removes negative rounding errors.
Claim 5: the detection formula gives the regression value at every shift of the test patch
The regression function is . The response is . With and permutation invariance, , so
the circular correlation of with . Its transform is , which is line L6. Since and are even, is even and real, so is real and the conjugate changes nothing.
Consequence for tracking. If exactly, then , so , the fitted value at the unshifted training sample, which is near the label peak for small . This is why line L8 moves the target by the position of the peak.
Claim 6: with the linear kernel the dual solution equals primal ridge regression
Let be the matrix whose rows are . The primal solution and the dual satisfy , and so for every patch .
Proof. . Both matrices in parentheses are invertible for ; multiply on the left by and on the right by and apply to . Then .
What is not claimed
The claims are exact statements about the training set of all cyclic shifts. Real motion is not a cyclic shift: a moved target brings new background in at one side, and the cosine window and the padding around the target only reduce the effect. So the claim that the peak of the response is at the displacement of the target is a heuristic. The running averages of the model (line L10) are a heuristic too: unlike the MOSSE update, the average of two arrays is not the solution of a single regression problem.
Complexity
Each kernel array costs two forward FFTs and one inverse FFT, , plus for the exponentials. TRAIN and DETECT each cost , so a frame costs and frames cost , against per frame for solving the system directly. With feature channels the correlation of line L1 costs . The extra space is for the model.
Properties
- Dense sampling for free. All shifts are training samples, and all positions are scored, at the cost of a few FFTs.
- Kernel choice. The Gaussian kernel gives a nonlinear scorer; the linear kernel gives the faster dual correlation filter, which with one channel is a MOSSE filter of one patch.
- Multichannel. Features such as HOG enter only through the sum over channels in line L1, and the paper reports a large gain in accuracy over raw pixels.
- Fixed scale and integer peak. Like MOSSE, the plain method neither changes the patch size nor locates the peak between pixels.
- Boundary effect. The cyclic shifts are not real motions; shifted samples far from 0 wrap the target around the patch border.
Variants and improvements
- DCF. The linear kernel with multichannel features, which avoids the exponentials and is faster than the Gaussian kernel.
- Scale estimation. A separate filter over a few scales of the patch, or a search over scaled patches.
- Spatially regularized filters. Penalize filter values far from the center, which reduces the boundary effect at the cost of an iterative solver.
- Subpixel peak. Fit a parabola to the response near the peak.
- Learned features. Use feature maps of a network instead of HOG; siamese tracking takes this further and learns the comparison itself.
When to use it
Use KCF when you need a fast single-target tracker that runs on a CPU, the target changes slowly, and moves less than about half the patch between frames. It is a common baseline and a clear example of how structure in the data turns a large linear system into FFTs. For large changes of scale or appearance, or for recovery after the target leaves the view, use a re-detection scheme such as tracking-learning-detection or a learned tracker.
Pitfalls
- A kernel that is not permutation invariant. The Fourier formulas then compute something, but not the regression on the shifts. Check the condition before using a new kernel.
- The scale of . Without the division by , the squared distance grows with the patch size and the Gaussian kernel becomes nearly 0 everywhere. Follow one convention.
- Shift direction. Whether the response peak is at or depends on which side is conjugated. Check it with a known shift, as in the example.
- Labels with the peak in the middle. The formulas assume the label peak at shift 0, the corner of the array. A Gaussian centered in the middle of the array gives responses offset by half the patch.
- Too small a patch. The target must stay well inside the patch after the move, or the wrapped copies dominate.
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
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.
A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.
Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
1e-8.
This module holds no algorithm of a computer vision page.
"""
from __future__ import annotations
import cmath
import math
from typing import List, Sequence, Tuple
Matrix = List[List[float]]
Vector = List[float]
_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100
# ---------------------------------------------------------------- basics
def zeros(m: int, n: int) -> Matrix:
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n: int) -> Matrix:
"""The n x n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a) -> bool:
return len(a) > 0 and isinstance(a[0], (list, tuple))
def transpose(a: Sequence[Sequence[float]]) -> Matrix:
"""The transpose of a matrix."""
return [list(col) for col in zip(*a)]
def add(a, b):
"""a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, c):
"""c times a, for a vector or a matrix a and a number c."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
"""The matrix product a b."""
if len(a[0]) != len(b):
raise ValueError("mul: shapes do not match")
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
"""The product a x of a matrix and a vector."""
if len(a[0]) != len(x):
raise ValueError("matvec: shapes do not match")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x: Sequence[float], y: Sequence[float]) -> float:
"""The inner product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(a) -> float:
"""The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
if _is_matrix(a):
return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
return math.sqrt(sum(float(x) * float(x) for x in a))
def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
"""The cross product a x b of two 3-vectors."""
return [a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]]
def skew(a: Sequence[float]) -> Matrix:
"""The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
z = a[0] - a[0]
return [[z, -a[2], a[1]],
[a[2], z, -a[0]],
[-a[1], a[0], z]]
# ---------------------------------------------------- Gaussian elimination
def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
"""Reduce [a | b] to upper triangular form with partial pivoting.
Works in place on copies made by the caller. Returns a, b and the sign
of the row permutation.
"""
n = len(a)
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("singular matrix")
if p != k:
a[k], a[p] = a[p], a[k]
b[k], b[p] = b[p], b[k]
sign = -sign
piv = a[k][k]
for i in range(k + 1, n):
f = a[i][k] / piv
if f == 0:
continue
ai, ak = a[i], a[k]
for j in range(k, n):
ai[j] = ai[j] - f * ak[j]
bi, bk = b[i], b[k]
for j in range(len(bi)):
bi[j] = bi[j] - f * bk[j]
return a, b, sign
def solve(a: Sequence[Sequence[float]], b):
"""Solve a x = b for a square a, by Gaussian elimination with partial
pivoting. b is a vector or a matrix (several right-hand sides); the
result has the same form. Raises ValueError on an exact zero pivot."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("solve: matrix is not square")
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
if len(rhs) != n:
raise ValueError("solve: shapes do not match")
u, c, _ = _eliminate([list(row) for row in a], rhs)
m = len(c[0]) if n else 0
x = [[0.0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = c[i][j]
for k in range(i + 1, n):
s = s - u[i][k] * x[k][j]
x[i][j] = s / u[i][i]
return [row[0] for row in x] if vec else x
def inv(a: Sequence[Sequence[float]]) -> Matrix:
"""The inverse of a square matrix. Raises ValueError if it is singular."""
n = len(a)
one = a[0][0] - a[0][0] + 1 if n else 1.0
ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
return solve(a, ident)
def det(a: Sequence[Sequence[float]]) -> float:
"""The determinant of a square matrix, by Gaussian elimination."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("det: matrix is not square")
if n == 0:
return 1.0
try:
u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
except ValueError:
return a[0][0] - a[0][0]
d = u[0][0] - u[0][0] + sign
for i in range(n):
d = d * u[i][i]
return d
# ------------------------------------------------------- Jacobi methods
def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
"""Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
a is read (the lower triangle is taken as its mirror)."""
n = len(a)
s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
v = eye(n)
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
apq = s[p][q]
if apq == 0.0:
continue
app, aqq = s[p][p], s[q][q]
if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
abs(apq) < 1e-300:
s[p][q] = s[q][p] = 0.0
continue
rotated = True
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(n):
skp, skq = s[k][p], s[k][q]
s[k][p] = c * skp - sn * skq
s[k][q] = sn * skp + c * skq
for k in range(n):
spk, sqk = s[p][k], s[q][k]
s[p][k] = c * spk - sn * sqk
s[q][k] = sn * spk + c * sqk
s[p][q] = s[q][p] = 0.0
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
if not rotated:
break
order = sorted(range(n), key=lambda i: s[i][i])
w = [s[i][i] for i in order]
vs = [[v[k][i] for i in order] for k in range(n)]
return w, vs
def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
"""Replace the columns with index in need by unit vectors orthogonal to
all other columns (Gram-Schmidt on the standard basis)."""
keep = [c for i, c in enumerate(cols) if i not in need]
for i in need:
best, best_norm = None, -1.0
for e in range(m):
x = [0.0] * m
x[e] = 1.0
for _ in range(2):
for c in keep:
d = dot(c, x)
x = [xi - d * ci for xi, ci in zip(x, c)]
nx = norm(x)
if nx > best_norm:
best, best_norm = x, nx
u = [xi / best_norm for xi in best]
cols[i] = u
keep.append(u)
def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
m, n = len(a), len(a[0])
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
cp, cq = cols[p], cols[q]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cq)
gamma = sum(x * y for x, y in zip(cp, cq))
if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
continue
rotated = True
zeta = (beta - alpha) / (2.0 * gamma)
t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
c = 1.0 / math.sqrt(1.0 + t * t)
s = c * t
cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
vp, vq = vcols[p], vcols[q]
vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
if not rotated:
break
sv = [norm(c) for c in cols]
order = sorted(range(n), key=lambda i: -sv[i])
sv = [sv[i] for i in order]
cols = [cols[i] for i in order]
vcols = [vcols[i] for i in order]
smax = sv[0] if sv else 0.0
ucols: List[Vector] = []
need: List[int] = []
for i, c in enumerate(cols):
if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
ucols.append([x / sv[i] for x in c])
else:
ucols.append([0.0] * m)
need.append(i)
if need:
_complete_basis(ucols, m, need)
return transpose(ucols), sv, transpose(vcols)
def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
"""Thin singular value decomposition by the one-sided Jacobi method.
For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
size m x k, S a list of k values in descending order and V of size
n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
For m >= n, V is square (n x n)."""
m, n = len(a), len(a[0])
if m >= n:
return _svd_tall(a)
u, s, v = _svd_tall(transpose(a))
return v, s, u
def nullvec(a: Sequence[Sequence[float]]) -> Vector:
"""A unit vector x that minimizes ||a x||: the right singular vector of
the smallest singular value. If a has fewer rows than columns, zero rows
are added first, so the result is in the null space. The sign is not
fixed."""
m, n = len(a), len(a[0])
rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
_, _, v = _svd_tall(rows)
return [v[i][n - 1] for i in range(n)]
# ---------------------------------------------- orthogonal factorizations
def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""QR factorization by Householder reflections. For an m x n matrix a,
returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
m, n = len(a), len(a[0])
r = [[float(x) for x in row] for row in a]
q = eye(m)
for k in range(min(m - 1, n)):
x = [r[i][k] for i in range(k, m)]
nx = norm(x)
if nx == 0.0:
continue
alpha = -nx if x[0] >= 0 else nx
v = list(x)
v[0] -= alpha
nv = norm(v)
if nv == 0.0:
continue
v = [vi / nv for vi in v]
for j in range(n):
d = sum(v[i - k] * r[i][j] for i in range(k, m))
if d != 0.0:
for i in range(k, m):
r[i][j] -= 2.0 * v[i - k] * d
for i in range(m):
d = sum(q[i][l] * v[l - k] for l in range(k, m))
if d != 0.0:
for l in range(k, m):
q[i][l] -= 2.0 * d * v[l - k]
for k in range(min(m, n)):
if r[k][k] < 0:
r[k] = [-x for x in r[k]]
for i in range(m):
q[i][k] = -q[i][k]
for i in range(m):
for j in range(min(i, n)):
r[i][j] = 0.0
return q, r
def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""RQ factorization of a square matrix: returns R (upper triangular,
with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
from the QR factorization of the transpose of the row-reversed matrix."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("rq: matrix is not square")
flipped = transpose([list(row) for row in reversed(a)])
q1, r1 = qr(flipped)
rt = transpose(r1)
r = [list(reversed(row)) for row in reversed(rt)]
q = [list(row) for row in reversed(transpose(q1))]
return r, q
def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
"""The lower triangular L with a = L L^T, for a symmetric positive
definite a. Raises ValueError if a pivot is not positive."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
if d <= 0:
raise ValueError("cholesky: matrix is not positive definite")
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return low
# ---------------------------------------------------------- polynomials
def _horner(c: Sequence[complex], x):
p = 0.0
for ci in c:
p = p * x + ci
return p
def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
"""Real roots of the polynomial with the given coefficients, highest
power first. All complex roots are found by the Durand-Kerner method.
A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
part is then polished by Newton steps on the real polynomial. Returns
the real roots in ascending order, with repeats for multiple roots."""
c = [float(x) for x in coeffs]
while c and c[0] == 0.0:
c.pop(0)
n = len(c) - 1
if n < 1:
return []
c = [x / c[0] for x in c]
rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
if rho == 0.0:
return [0.0] * n
z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
for _ in range(2000):
moved = 0.0
for k in range(n):
den = 1.0 + 0j
for j in range(n):
if j != k:
den *= z[k] - z[j]
if den == 0:
den = 1e-12 * rho
step = _horner(c, z[k]) / den
z[k] -= step
moved = max(moved, abs(step) / max(1.0, abs(z[k])))
if moved <= 1e-15:
break
deriv = [c[i] * (n - i) for i in range(n)]
roots = []
for zk in z:
if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
continue
x = zk.real
px = _horner(c, x)
for _ in range(8):
dp = _horner(deriv, x)
if dp == 0.0 or px == 0.0:
break
xn = x - px / dp
pn = _horner(c, xn)
if abs(pn) >= abs(px):
break
x, px = xn, pn
roots.append(x)
return sorted(roots)
# ------------------------------------------------------------ self-test
def self_test() -> None:
"""Check svd, sym_eig and polyroots_real. Raises AssertionError."""
import random
rng = random.Random(7)
for _ in range(3):
a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
u, s, v = svd(a)
rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
assert norm(sub(rec, a)) <= 1e-10
assert all(s[i] >= s[i + 1] for i in range(4))
sym = add(a, transpose(a))
w, vv = sym_eig(sym)
rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
assert norm(sub(rec, sym)) <= 1e-10
assert all(w[i] <= w[i + 1] for i in range(4))
r = polyroots_real([1.0, -6.0, 11.0, -6.0])
assert len(r) == 3
assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))
if __name__ == "__main__":
self_test()
kernelized_correlation_filter.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernelized-correlation-filter/. The authors are listed in prov/D8MKGV.jsonl.
"""The kernelized correlation filter (Henriques, Caseiro, Martins and Batista,
2015) on single-channel patches, with a radix-2 FFT in pure Python.
A patch is an r x c array (r and c powers of two) indexed x[v][u], P = r c.
The cyclic shift by d = (du, dv) is (S_d x)[v][u] = x[(v - dv) % r][(u - du) % c].
The training set is every shift S_d x with the label y(d), a Gaussian of the
wrapped shift d. The response at d is the regression value of S_{-d} z, so a
patch z = S_d x gives the peak at d.
kernel(z, x)[s] is kappa(z, S_s x) for every shift s. For the Gaussian kernel
kappa(a, b) = exp(-|a - b|^2 / (sigma^2 P)) (the division by P follows the
authors' code); for the linear kernel kappa(a, b) = <a, b> / P.
"""
import cmath
import math
def fft(x, inverse=False):
"""Radix-2 FFT; the inverse includes the factor 1 / n."""
n = len(x)
if n & (n - 1):
raise ValueError("length must be a power of two")
a = list(x)
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
sign = 1 if inverse else -1
while size <= n:
w = cmath.exp(sign * 2j * math.pi / size)
for start in range(0, n, size):
t = 1
for k in range(size // 2):
e, o = a[start + k], a[start + k + size // 2] * t
a[start + k], a[start + k + size // 2] = e + o, e - o
t *= w
size *= 2
if inverse:
a = [z / n for z in a]
return a
def fft2(img, inverse=False):
rows = [fft(row, inverse) for row in img]
cols = [fft([rows[v][u] for v in range(len(rows))], inverse) for u in range(len(rows[0]))]
return [[cols[u][v] for u in range(len(cols))] for v in range(len(rows))]
def shift(x, d):
"""The cyclic shift S_d x."""
r, c = len(x), len(x[0])
return [[x[(v - d[1]) % r][(u - d[0]) % c] for u in range(c)] for v in range(r)]
def wrap(i, n):
"""The representative of i modulo n in [-n/2, n/2)."""
return (i + n // 2) % n - n // 2
def gaussian_labels(r, c, s):
"""y(d) = exp(-|d|^2 / (2 s^2)) with d wrapped, so the peak is at d = 0."""
return [[math.exp(-(wrap(u, c) ** 2 + wrap(v, r) ** 2) / (2 * s * s)) for u in range(c)]
for v in range(r)]
def kernel(z, x, sigma=None):
"""The array k[s] = kappa(z, S_s x) for every shift s, by the FFT. With
sigma None the kernel is linear, otherwise Gaussian."""
r, c = len(x), len(x[0])
p = r * c
zf, xf = fft2(z), fft2(x)
# cross[s] = sum_t z(t) x(t - s), whose transform is zf . conj(xf)
cross = fft2([[zf[v][u] * xf[v][u].conjugate() for u in range(c)] for v in range(r)], inverse=True) # @line L1
if sigma is None:
return [[cross[v][u].real / p for u in range(c)] for v in range(r)]
zz = sum(t * t for row in z for t in row)
xx = sum(t * t for row in x for t in row)
return [[math.exp(-max(zz + xx - 2 * cross[v][u].real, 0.0) / (sigma * sigma * p)) # @line L2
for u in range(c)] for v in range(r)]
def train(x, y, lam, sigma=None):
"""The transform of the dual coefficients: alpha_hat = y_hat / (k_hat + lam)."""
kf = fft2(kernel(x, x, sigma)) # @line L3
yf = fft2(y)
return [[yf[v][u] / (kf[v][u] + lam) for u in range(len(y[0]))] for v in range(len(y))] # @line L4
def detect(alpha_f, x, z, sigma=None):
"""The response r(d) = sum_e alpha(e) kappa(S_{-d} z, S_e x) for every d."""
kf = fft2(kernel(z, x, sigma)) # @line L5
rf = [[kf[v][u] * alpha_f[v][u].conjugate() for u in range(len(x[0]))] for v in range(len(x))]
return [[t.real for t in row] for row in fft2(rf, inverse=True)] # @line L6
def sample(img, u, v):
h, w = len(img), len(img[0])
u0, v0 = math.floor(u), math.floor(v)
fu, fv = u - u0, v - v0
def at(vv, uu):
return img[min(max(vv, 0), h - 1)][min(max(uu, 0), w - 1)]
return ((1 - fv) * ((1 - fu) * at(v0, u0) + fu * at(v0, u0 + 1))
+ fv * ((1 - fu) * at(v0 + 1, u0) + fu * at(v0 + 1, u0 + 1)))
class KCF:
"""A tracker on raw gray values scaled to [-0.5, 0.5] with a cosine window."""
def __init__(self, img, center, n=32, target=13, sigma=0.2, lam=1e-4, gamma=0.075):
self.n, self.sigma, self.lam, self.gamma = n, sigma, lam, gamma
self.center = center
self.win = [math.sin(math.pi * (i + 0.5) / n) for i in range(n)]
self.y = gaussian_labels(n, n, target / 10)
self.x = self.features(img, center)
self.alpha_f = train(self.x, self.y, lam, sigma)
def features(self, img, center):
n, c = self.n, self.n // 2
return [[(sample(img, center[0] + u - c, center[1] + v - c) / 255 - 0.5) * self.win[u] * self.win[v]
for u in range(n)] for v in range(n)]
def update(self, img):
"""Track into the next frame and update the model. Returns the center."""
n = self.n
z = self.features(img, self.center)
resp = detect(self.alpha_f, self.x, z, self.sigma) # @line L7
pv, pu = max(((v, u) for v in range(n) for u in range(n)), key=lambda t: resp[t[0]][t[1]])
self.center = (self.center[0] + wrap(pu, n), self.center[1] + wrap(pv, n)) # @line L8
x_new = self.features(img, self.center)
a_new = train(x_new, self.y, self.lam, self.sigma) # @line L9
g = self.gamma
self.x = [[(1 - g) * a + g * b for a, b in zip(r1, r2)] for r1, r2 in zip(self.x, x_new)] # @line L10
self.alpha_f = [[(1 - g) * a + g * b for a, b in zip(r1, r2)] for r1, r2 in zip(self.alpha_f, a_new)]
return self.center # @line L11
test_kernelized_correlation_filter.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernelized-correlation-filter/. The authors are listed in prov/D8MKGV.jsonl.
import math
import random
from cvla import solve
from kernelized_correlation_filter import (
KCF,
detect,
fft2,
gaussian_labels,
kernel,
shift,
train,
)
R, C = 4, 8
SHIFTS = [(du, dv) for dv in range(R) for du in range(C)]
def rand_patch(rng):
return [[rng.uniform(-1, 1) for _ in range(C)] for _ in range(R)]
def kappa(a, b, sigma):
p = R * C
if sigma is None:
return sum(s * t for ra, rb in zip(a, b) for s, t in zip(ra, rb)) / p
return math.exp(-sum((s - t) ** 2 for ra, rb in zip(a, b) for s, t in zip(ra, rb)) / (sigma * sigma * p))
def test_shifts_and_labels():
rng = random.Random(1)
x = rand_patch(rng)
assert shift(shift(x, (3, 1)), (-3, -1)) == x
assert shift(shift(x, (2, 3)), (5, 2)) == shift(x, (7, 5))
y = gaussian_labels(R, C, 1.0)
assert y[0][0] == 1.0
for v in range(R):
for u in range(C):
assert y[v][u] == y[(-v) % R][(-u) % C]
def test_kernel_by_fft_matches_the_definition():
rng = random.Random(2)
x, z = rand_patch(rng), rand_patch(rng)
for sigma in [None, 0.5, 2.0]:
k = kernel(z, x, sigma)
for du, dv in SHIFTS:
assert abs(k[dv][du] - kappa(z, shift(x, (du, dv)), sigma)) < 1e-12
def brute_force(x, y, z, lam, sigma):
"""Kernel ridge regression on all P shifts, solved as a P x P system."""
xs = [shift(x, d) for d in SHIFTS]
gram = [[kappa(a, b, sigma) + (lam if i == j else 0.0) for j, b in enumerate(xs)]
for i, a in enumerate(xs)]
alpha = solve(gram, [y[dv][du] for du, dv in SHIFTS])
resp = []
for du, dv in SHIFTS:
zd = shift(z, (-du, -dv))
resp.append(sum(a * kappa(zd, b, sigma) for a, b in zip(alpha, xs)))
return alpha, resp
def test_dual_coefficients_and_response_match_brute_force():
rng = random.Random(3)
y = gaussian_labels(R, C, 1.0)
for sigma in [None, 0.7]:
x, z = rand_patch(rng), rand_patch(rng)
alpha_f = train(x, y, 0.1, sigma)
alpha = fft2(alpha_f, inverse=True)
resp = detect(alpha_f, x, z, sigma)
want_alpha, want_resp = brute_force(x, y, z, 0.1, sigma)
for i, (du, dv) in enumerate(SHIFTS):
assert abs(alpha[dv][du] - want_alpha[i]) < 1e-9
assert abs(resp[dv][du] - want_resp[i]) < 1e-9
def test_linear_kernel_equals_primal_ridge_regression():
rng = random.Random(4)
x, z = rand_patch(rng), rand_patch(rng)
y = gaussian_labels(R, C, 1.0)
lam, p = 0.1, R * C
rows = [[t / math.sqrt(p) for row in shift(x, d) for t in row] for d in SHIFTS]
labels = [y[dv][du] for du, dv in SHIFTS]
gram = [[sum(r[i] * r[j] for r in rows) + (lam if i == j else 0.0) for j in range(p)] for i in range(p)]
rhs = [sum(r[i] * t for r, t in zip(rows, labels)) for i in range(p)]
w = solve(gram, rhs)
resp = detect(train(x, y, lam), x, z)
for du, dv in SHIFTS:
feat = [t / math.sqrt(p) for row in shift(z, (-du, -dv)) for t in row]
assert abs(sum(a * b for a, b in zip(w, feat)) - resp[dv][du]) < 1e-9
def test_a_position_weighted_kernel_is_not_circulant():
rng = random.Random(5)
x = rand_patch(rng)
weight = [[1.0 + u + v for u in range(C)] for v in range(R)]
def weighted(a, b):
return sum(weight[v][u] * a[v][u] * b[v][u] for v in range(R) for u in range(C))
xs = [shift(x, d) for d in SHIFTS]
# with a permutation-invariant kernel K[i][j] depends only on the shift between i and j
assert abs(kappa(xs[0], xs[1], 0.7) - kappa(xs[1], xs[2], 0.7)) < 1e-12
assert abs(weighted(xs[0], xs[1]) - weighted(xs[1], xs[2])) > 1e-3
def texture(seed, k, lo, hi):
rng = random.Random(seed)
blobs = [(rng.uniform(lo, hi), rng.uniform(lo, hi), rng.uniform(1.5, 3), rng.uniform(40, 160))
for _ in range(k)]
def f(u, v):
return 20 + sum(a * math.exp(-((u - x) ** 2 + (v - y) ** 2) / (2 * s * s)) for x, y, s, a in blobs)
return f
def test_tracks_a_moving_target():
n, half = 64, 6
back = texture(1, 40, -5, n + 5)
bg = [[back(u, v) for u in range(n)] for v in range(n)]
target = texture(2, 8, -2, 2 * half + 2)
def frame(c):
img = [row[:] for row in bg]
for v in range(n):
for u in range(n):
du, dv = u - c[0], v - c[1]
if abs(du) <= half and abs(dv) <= half:
img[v][u] = target(du + half, dv + half)
return img
truth = [(20 + 2.4 * t, 22 + 1.7 * t) for t in range(10)]
tracker = KCF(frame(truth[0]), truth[0])
for c in truth[1:]:
assert math.dist(tracker.update(frame(c)), c) < 1.5
History
Bolme and colleagues introduced the MOSSE filter in 2010. In 2012 Henriques, Caseiro, Martins and Batista showed at ECCV that training on all cyclic shifts of a patch gives a circulant data matrix, and used it with a Gaussian kernel on raw pixels (the CSK tracker). Their 2015 journal paper stated the general result for permutation-invariant kernels, added multichannel features such as HOG, and gave the KCF and DCF trackers, which became common baselines for fast tracking. The circulant structure itself is classical; see Gray's review of Toeplitz and circulant matrices.
References
- João F. Henriques, Rui Caseiro, Pedro Martins and Jorge Batista, High-speed tracking with kernelized correlation filters, IEEE Transactions on Pattern Analysis and Machine Intelligence 37(3), 2015, 583 to 596 (also arXiv 1404.7584), Theorem 1 (the circulant kernel matrix for permutation-invariant kernels), the formulas for training and detection, the Gaussian and linear kernel correlations, and the parameters of the experiments
- João F. Henriques, Rui Caseiro, Pedro Martins and Jorge Batista, Exploiting the circulant structure of tracking-by-detection with kernels, European Conference on Computer Vision (ECCV), 2012, the whole paper (the first form, with raw pixels)
- Robert M. Gray, Toeplitz and circulant matrices, a review, Foundations and Trends in Communications and Information Theory 2(3), 2006, 155 to 239, the chapter on circulant matrices (diagonalization by the discrete Fourier transform)
- David S. Bolme, J. Ross Beveridge, Bruce A. Draper and Yui Man Lui, Visual object tracking using adaptive correlation filters, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2010, 2544 to 2550, the whole paper (the MOSSE filter that the linear case reproduces)
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 D8MKGV Edit this page History Report an error Markdown