Algorithm Search⌘K

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.

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
Properties
deterministicnot exactnot iterativelocalonline
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 PP pixels there are PP samples, and solving the regression directly would cost a P×PP \times P 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 xx is an r×cr \times c real array with P=rcP = r c pixels and rr, cc powers of two, indexed modulo its size. The cyclic shift by dd is (Sdx)(t)=x(t−d)(S_d x)(t) = x(t - d). The training set is {Sdx:d}\{ S_d x : d \} with labels y(d)=exp⁡(−∣d∣2/(2s2))y(d) = \exp(-|d|^2 / (2 s^2)), where dd is taken in [−r/2,r/2)×[−c/2,c/2)[-r/2, r/2) \times [-c/2, c/2), so the label is 1 for d=0d = 0 and falls off with the size of the shift. Kernel ridge regression with a kernel κ\kappa and λ>0\lambda > 0 asks for

f(w)=∑eα(e) κ(w,Sex),α=(K+λI)−1y,Kde=κ(Sdx,Sex),f(w) = \sum_e \alpha(e)\, \kappa(w, S_e x), \qquad \alpha = (K + \lambda I)^{-1} y, \qquad K_{d e} = \kappa(S_d x, S_e x),

as given by the kernel trick. For a new patch zz, the response at dd is f(S−dz)f(S_{-d} z): if z=Sdxz = S_d x, the target moved by dd and the response at dd is f(x)f(x), close to the peak label.

The key condition is permutation invariance: κ(Sda,Sdb)=κ(a,b)\kappa(S_d a, S_d b) = \kappa(a, b). It holds for the linear kernel ⟨a,b⟩/P\langle a, b \rangle / P and for the Gaussian kernel exp⁡(−∣a−b∣2/(σ2P))\exp(-|a - b|^2 / (\sigma^2 P)) (the division by PP follows the authors' code). Under it, Kde=k(e−d)K_{d e} = k(e - d) with k(s)=κ(x,Ssx)k(s) = \kappa(x, S_s x), so KK is circulant. With ⊙\odot the entry-by-entry product and a^\hat a the DFT,

α^=y^k^+λ,resp^=k^z⊙α^‾,kz(s)=κ(z,Ssx).\hat \alpha = \frac{\hat y}{\hat k + \lambda}, \qquad \widehat{\text{resp}} = \hat k_z \odot \overline{\hat \alpha}, \qquad k_z(s) = \kappa(z, S_s x).

Both kernel arrays come from one correlation computed by FFT: ⟨z,Ssx⟩\langle z, S_s x \rangle for every ss is the inverse transform of z^⊙x^‾\hat z \odot \overline{\hat x}, and ∣z−Ssx∣2=∣z∣2+∣x∣2−2⟨z,Ssx⟩|z - S_s x|^2 = |z|^2 + |x|^2 - 2 \langle z, S_s x \rangle.

The algorithm

  1. KERNEL(z, x) ▷ k[s] = κ(z, S_s x) for every shift s
  2. 1c ← IFFT(ẑ ⊙ conj(x̂)) ▷ c[s] = ⟨z, S_s x⟩
  3. 2return exp(-(|z|² + |x|² - 2c) / (σ² P)) ▷ or c / P for the linear kernel
  4. TRAIN(x, y)
  5. 3k ← KERNEL(x, x)
  6. 4return α̂ ← ŷ / (k̂ + λ)
  7. DETECT(α̂, x, z)
  8. 5k_z ← KERNEL(z, x)
  9. 6return IFFT(k̂_z ⊙ conj(α̂))
  10. TRACK(F_t) ▷ model x, α̂; position p
  11. 7resp ← DETECT(α̂, x, features of F_t at p)
  12. 8p ← p + the shift d of the largest value of resp
  13. 9x′ ← features of F_t at p; α̂′ ← TRAIN(x′, y)
  14. 10x ← (1 - γ) x + γ x′; α̂ ← (1 - γ) α̂ + γ α̂′
  15. 11return p

The features of a frame at pp are a patch centered at pp 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 λ=10−4\lambda = 10^{-4}, the label width s=wh/10s = \sqrt{w h} / 10 for a target of w×hw \times h pixels (counted in cells for HOG), σ=0.2\sigma = 0.2 and γ=0.075\gamma = 0.075 for raw pixels, and σ=0.5\sigma = 0.5 and γ=0.02\gamma = 0.02 for HOG. For multichannel features, line L1 sums the correlation over the channels.

Example

The linear kernel by hand. Take one row, r=1r = 1 and c=P=4c = P = 4, the patch x=(1,2,0,−1)x = (1, 2, 0, -1), the labels y=(1,0,0,0)y = (1, 0, 0, 0), the linear kernel and λ=0.1\lambda = 0.1. The kernel array is k(s)=⟨x,Ssx⟩/4k(s) = \langle x, S_s x \rangle / 4, the autocorrelation of xx divided by 4:

k=(6,1,−4,1)/4=(1.5,0.25,−1,0.25),k^=(1,2.5,0,2.5).k = (6, 1, -4, 1) / 4 = (1.5, 0.25, -1, 0.25), \qquad \hat k = (1, 2.5, 0, 2.5) .

These are ∣x^∣2/4|\hat x|^2 / 4, since x^=(2,1−3i,0,1+3i)\hat x = (2, 1 - 3i, 0, 1 + 3i). With y^=(1,1,1,1)\hat y = (1, 1, 1, 1), α^=(1/1.1,1/2.6,1/0.1,1/2.6)=(0.909,0.385,10,0.385)\hat \alpha = (1/1.1, 1/2.6, 1/0.1, 1/2.6) = (0.909, 0.385, 10, 0.385), and α=(2.920,−2.273,2.535,−2.273)\alpha = (2.920, -2.273, 2.535, -2.273). The response to xx itself is (0.708,0.227,−0.253,0.227)(0.708, 0.227, -0.253, 0.227), with the peak at shift 0. For z=S1x=(−1,1,2,0)z = S_1 x = (-1, 1, 2, 0) the response is (0.227,0.708,0.227,−0.253)(0.227, 0.708, 0.227, -0.253): the peak has moved to shift 1. The frequency where x^=0\hat x = 0 gets the large coefficient 1/λ1/\lambda, but in the response it is multiplied by k^z\hat k_z, which is 0 there for every shift of xx.

Against brute force. For random 4×84 \times 8 patches (P=32P = 32), the tests build the 32×3232 \times 32 matrix K+λIK + \lambda I from the definition and solve it directly. The α\alpha from line L4 and the responses from line L6 agree with the direct solution to about 10−1510^{-15} 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 64×6464 \times 64 with a background of Gaussian blobs and a 13×1313 \times 13 target with its own blob texture, which moves by (2.4,1.7)(2.4, 1.7) per frame. The features are raw gray values scaled to [−0.5,0.5][-0.5, 0.5] on a 32×3232 \times 32 patch with a cosine window, with σ=0.2\sigma = 0.2, λ=10−4\lambda = 10^{-4}, s=1.3s = 1.3 and γ=0.075\gamma = 0.075. 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 κ\kappa is permutation invariant, KdeK_{d e} depends only on e−de - d. 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 (K+λI)α=y(K + \lambda I)\alpha = y into (k^+λ)⊙α^=y^(\hat k + \lambda) \odot \hat \alpha = \hat y. Since KK is positive semidefinite, k^≥0\hat k \ge 0, and the division is always defined.
  • Kernel arrays. Lines L1 and L2 compute κ(z,Ssx)\kappa(z, S_s x) for every ss exactly, by the correlation theorem.
  • Detection. Line L6 gives f(S−dz)f(S_{-d} z) for every dd.
  • 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 G=Zr×ZcG = \mathbb{Z}_r \times \mathbb{Z}_c of size P=rcP = r c, the shift is (Sdx)(t)=x(t−d)(S_d x)(t) = x(t - d), and the DFT is a^(k)=∑s∈Ga(s)ωk(s)\hat a(k) = \sum_{s \in G} a(s) \omega_k(s) with the characters ωk(s)=e−2πi(k1s1/r+k2s2/c)\omega_k(s) = e^{-2\pi i (k_1 s_1 / r + k_2 s_2 / c)}; the inverse has the factor 1/P1/P. A kernel κ\kappa is symmetric and positive semidefinite, and it is permutation invariant for the shifts if κ(Sda,Sdb)=κ(a,b)\kappa(S_d a, S_d b) = \kappa(a, b) for all aa, bb and dd.

Claim 1: the Gram matrix of the shifts is circulant

Let Kde=κ(Sdx,Sex)K_{d e} = \kappa(S_d x, S_e x) for d,e∈Gd, e \in G. If κ\kappa is permutation invariant, then Kde=k(e−d)K_{d e} = k(e - d) with k(s)=κ(x,Ssx)k(s) = \kappa(x, S_s x).

Proof. S−dSd=IdS_{-d} S_d = \mathrm{Id} and S−dSe=Se−dS_{-d} S_e = S_{e - d}, so κ(Sdx,Sex)=κ(S−dSdx,S−dSex)=κ(x,Se−dx)\kappa(S_d x, S_e x) = \kappa(S_{-d} S_d x, S_{-d} S_e x) = \kappa(x, S_{e-d} x). □\square

The Gaussian kernel exp⁡(−∣a−b∣2/(σ2P))\exp(-|a - b|^2 / (\sigma^2 P)) and the linear kernel ⟨a,b⟩/P\langle a, b \rangle / P 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 k(−s)=κ(x,S−sx)=κ(Ssx,x)=κ(x,Ssx)=k(s)k(-s) = \kappa(x, S_{-s} x) = \kappa(S_s x, x) = \kappa(x, S_s x) = k(s) by invariance and symmetry, so kk is even and k^\hat k is real.

Claim 2: the DFT diagonalizes a circulant matrix

For (Ka)(d)=∑ek(e−d) a(e)(K a)(d) = \sum_e k(e - d)\, a(e), the transform is Ka^=k^⊙a^\widehat{K a} = \hat k \odot \hat a when kk is even.

Proof. (Ka)(d)=∑ek(d−e)a(e)(K a)(d) = \sum_e k(d - e) a(e) since kk is even, which is the circular convolution of kk and aa. By the convolution theorem, k∗a^=k^⊙a^\widehat{k * a} = \hat k \odot \hat a: substitute s=d−es = d - e in ∑d∑ek(d−e)a(e)ωk(d)\sum_d \sum_e k(d - e) a(e) \omega_k(d) and use ωk(s+e)=ωk(s)ωk(e)\omega_k(s + e) = \omega_k(s) \omega_k(e). □\square

So the eigenvalues of KK are the values k^(ℓ)\hat k(\ell), ℓ∈G\ell \in G, with the characters as eigenvectors. Because KK is positive semidefinite (a Gram matrix of a positive semidefinite kernel), every k^(ℓ)≥0\hat k(\ell) \ge 0.

Claim 3: the training formula gives the ridge regression coefficients

Kernel ridge regression on the samples SdxS_d x with labels y(d)y(d) has the dual coefficients α=(K+λI)−1y\alpha = (K + \lambda I)^{-1} y for λ>0\lambda > 0. Then

α^=y^k^+λ.\hat \alpha = \frac{\hat y}{\hat k + \lambda} .

Proof. By Claim 2, (K+λI)α=y(K + \lambda I) \alpha = y becomes (k^+λ)⊙α^=y^(\hat k + \lambda) \odot \hat \alpha = \hat y after the DFT, which is one to one. Each k^(ℓ)+λ≥λ>0\hat k(\ell) + \lambda \ge \lambda > 0, so the division is defined and the solution is unique. □\square

Lines L3 and L4 compute exactly this, with kk from line L1 and line L2.

Claim 4: lines L1 and L2 compute the kernel at every shift

∑tz(t)x(t−s)=∑t′z(t′+s)x(t′)\sum_t z(t) x(t - s) = \sum_{t'} z(t' + s) x(t'), the circular correlation of zz with xx at ss, has the transform z^⊙x^‾\hat z \odot \overline{\hat x} (the correlation theorem, proved on the MOSSE filter page; xx is real). So line L1 gives c(s)=⟨z,Ssx⟩c(s) = \langle z, S_s x \rangle for every ss. For the linear kernel κ(z,Ssx)=c(s)/P\kappa(z, S_s x) = c(s) / P. For the Gaussian kernel ∣z−Ssx∣2=∣z∣2+∣Ssx∣2−2c(s)=∣z∣2+∣x∣2−2c(s)|z - S_s x|^2 = |z|^2 + |S_s x|^2 - 2 c(s) = |z|^2 + |x|^2 - 2 c(s), which is line L2. The clamp at 0 only removes negative rounding errors. □\square

Claim 5: the detection formula gives the regression value at every shift of the test patch

The regression function is f(w)=∑eα(e)κ(w,Sex)f(w) = \sum_e \alpha(e) \kappa(w, S_e x). The response is resp(d)=f(S−dz)\text{resp}(d) = f(S_{-d} z). With kz(s)=κ(z,Ssx)k_z(s) = \kappa(z, S_s x) and permutation invariance, κ(S−dz,Sex)=κ(z,Sd+ex)=kz(d+e)\kappa(S_{-d} z, S_e x) = \kappa(z, S_{d + e} x) = k_z(d + e), so

resp(d)=∑eα(e) kz(d+e),\text{resp}(d) = \sum_e \alpha(e)\, k_z(d + e),

the circular correlation of kzk_z with α\alpha. Its transform is k^z⊙α^‾\hat k_z \odot \overline{\hat \alpha}, which is line L6. Since yy and kk are even, α\alpha is even and real, so α^\hat \alpha is real and the conjugate changes nothing. □\square

Consequence for tracking. If z=Sdxz = S_d x exactly, then S−dz=xS_{-d} z = x, so resp(d)=f(x)\text{resp}(d) = f(x), the fitted value at the unshifted training sample, which is near the label peak y(0)=1y(0) = 1 for small λ\lambda. 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 Φ\Phi be the P×PP \times P matrix whose rows are ϕ(Sdx)=Sdx/P\phi(S_d x) = S_d x / \sqrt P. The primal solution w=(ΦTΦ+λI)−1ΦTyw = (\Phi^{\mathsf T} \Phi + \lambda I)^{-1} \Phi^{\mathsf T} y and the dual α=(ΦΦT+λI)−1y\alpha = (\Phi \Phi^{\mathsf T} + \lambda I)^{-1} y satisfy w=ΦTαw = \Phi^{\mathsf T} \alpha, and so wTϕ(u)=∑eα(e)κ(u,Sex)w^{\mathsf T} \phi(u) = \sum_e \alpha(e) \kappa(u, S_e x) for every patch uu.

Proof. ΦT(ΦΦT+λI)=(ΦTΦ+λI)ΦT\Phi^{\mathsf T} (\Phi \Phi^{\mathsf T} + \lambda I) = (\Phi^{\mathsf T} \Phi + \lambda I) \Phi^{\mathsf T}. Both matrices in parentheses are invertible for λ>0\lambda > 0; multiply on the left by (ΦTΦ+λI)−1(\Phi^{\mathsf T} \Phi + \lambda I)^{-1} and on the right by (ΦΦT+λI)−1(\Phi \Phi^{\mathsf T} + \lambda I)^{-1} and apply to yy. Then wTϕ(u)=αTΦϕ(u)=∑eα(e)⟨ϕ(Sex),ϕ(u)⟩w^{\mathsf T} \phi(u) = \alpha^{\mathsf T} \Phi \phi(u) = \sum_e \alpha(e) \langle \phi(S_e x), \phi(u) \rangle. □\square

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 α^\hat \alpha arrays is not the solution of a single regression problem.

Complexity

Each kernel array costs two forward FFTs and one inverse FFT, Θ(Plog⁡P)\Theta(P \log P), plus Θ(P)\Theta(P) for the exponentials. TRAIN and DETECT each cost Θ(Plog⁡P)\Theta(P \log P), so a frame costs Θ(Plog⁡P)\Theta(P \log P) and NN frames cost Θ(NPlog⁡P)\Theta(N P \log P), against Θ(P3)\Theta(P^3) per frame for solving the P×PP \times P system directly. With CC feature channels the correlation of line L1 costs Θ(CPlog⁡P)\Theta(C P \log P). The extra space is Θ(P)\Theta(P) for the model.

Properties

  • Dense sampling for free. All PP shifts are training samples, and all PP 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 σ\sigma. Without the division by PP, 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 +d+d or −d-d 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.

cvla.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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)
  4. 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.

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