Algorithmadvanced
MOSSE filter
Also called minimum output sum of squared error filter.
A correlation filter fitted in closed form in the Fourier domain so that it gives a Gaussian peak on training patches, then updated online with running averages.
- Solves
- Visual object tracking
- Time
- Θ((T + 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; T = the number of training patches at the start
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativelocalonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David S. Bolme, J. Ross Beveridge, Bruce A. Draper, Yui Man Lui, 2010
The MOSSE filter (minimum output sum of squared error) is a correlation filter for tracking. It learns a small image , the filter, such that the cross-correlation of with each training patch of the target is as close as possible, in the sum of squared errors, to a desired output: a narrow Gaussian peak at the target center. In the Fourier domain this least squares problem splits into one scalar problem per frequency, so the filter has a closed form that costs a few fast Fourier transforms. In a new frame the tracker correlates the filter with the patch at the old position and moves to the peak of the response. It then updates the numerator and denominator of the filter with running averages. Bolme, Beveridge, Draper and Lui published it in 2010; they measured several hundred frames per second on their hardware, and the method started the line of correlation filter trackers that includes the kernelized correlation filter.
In plain words
We want a stencil that, when we slide it over the target, gives one bright spot exactly at the target center and darkness elsewhere. We do not guess the stencil; we compute it from examples of the target, so that sliding it over each example gives a picture as close as possible to the bright spot we want. Sliding a stencil over a picture is slow, but after a change to frequencies it is one multiplication per frequency, and then the best stencil is one division per frequency. In the next picture we slide the stencil over the area where the target was and move to the brightest spot. If the spot is not much brighter than its surroundings, the target is probably hidden, and we wait.
The problem
Patches are real arrays with a power of two, indexed by modulo , and . The center of the patch is the pixel , and pixel has its center at the point . Correlation is circular,
and by the correlation theorem its discrete Fourier transform is with , where is the entry-by-entry product and the bar is the complex conjugate. Given training patches and desired outputs (each a Gaussian of standard deviation pixels centered at ), the filter minimizes
which by Parseval's identity is a constant times the output sum of squared error in the image domain plus a small penalty on the size of . The minimizer is
with the division taken entry by entry. Each patch is preprocessed: take , subtract the mean and divide by the norm, and multiply by a cosine window that goes to 0 at the border, so that the circular wrap of the transform does not create strong edges.
The algorithm
INIT(F₀, p)- 1
for each of T patches: the patch at p in F₀ and T - 1 small random affine warps of it do - 2
f ← PREPROCESS(patch); A ← A + Ĝ ⊙ conj(f̂); B ← B + f̂ ⊙ conj(f̂) TRACK(F_t)- 3
f̂ ← FFT(PREPROCESS(patch of F_t at p)) - 4
g ← IFFT(f̂ ⊙ A / (B + ε)) ▷ the response - 5
(y, s) ← the peak of g and its peak to sidelobe ratio - 6
if s < s_min then return p, LOST ▷ keep p and the filter - 7
p ← p + (y - c) - 8
f̂ ← FFT(PREPROCESS(patch of F_t at p)) - 9
A ← η Ĝ ⊙ conj(f̂) + (1 - η) A; B ← η f̂ ⊙ conj(f̂) + (1 - η) B - 10
return p
Bolme and colleagues start with 8 random small affine perturbations of the first patch, use the learning rate , and add a small to the denominator. The peak to sidelobe ratio of line L5 is
where and are the mean and standard deviation of the response outside an window around the peak. They report values between 20 and 60 under normal tracking and values near 7 when the target is lost or occluded; the threshold is a heuristic, and it depends on the patch size.
Example
One dimension by hand. Take , the patch and the desired output , a peak at index 0. Then and . The filter is
The middle frequency of is 0, so the filter can do nothing there, and without it would divide 0 by 0. The response to is , whose inverse transform is : the peak is in the right place but the missing frequency spreads part of it. This is why one patch is not enough and the perturbed copies are added.
Tracking. The frames are , with a background of Gaussian blobs and a square target with another blob texture, which moves by per frame. The patch is (), , , , and the start uses the patch and 8 perturbations (rotations up to 0.15 radian and scales from 0.9 to 1.1). Over 6 frames the tracked centers are , , , , , , against the true up to . The errors are between 0.22 and 0.81 pixel, which is the rounding to the integer peak. The ratios are between 11.7 and 15.7. Then the target is replaced by a different texture: the ratio drops to 3.0, line L6 reports LOST, and the position and the filter stay as they were.
Correctness
The full proof is in proofs/correctness.md. It shows these facts.
- Theorem: correlation theorem. For real patches, the transform of the circular correlation of with is .
- Theorem: the closed form is optimal. is the unique minimizer of the regularized output error above, because the objective separates into one strictly convex quadratic per frequency.
- Theorem: the running update is optimal for a weighted objective. minimizes the same error with weights on frame , so old frames fade at a geometric rate.
- Theorem: shifts. A circular shift of the input by moves the response by , so a target that moved by gives a peak at if the new patch is a circular shift of the old one.
A real patch is not a circular shift of the old one, so line L7 is a heuristic that works when the motion is small compared to the patch. The peak to sidelobe test is a heuristic with no guarantee.
Proof: The MOSSE filter is the exact minimizer of the regularized output error, the running update minimizes an exponentially weighted error, and a circular shift of the input shifts the peakfull
Notation as on the page. Patches are real arrays indexed by (indices modulo ). The DFT is with no factor, so its inverse has the factor . Products and quotients of transforms are taken entry by entry, and is the complex conjugate.
Claim 1: correlation is a product with the conjugate
For real and let , the circular correlation. Then .
Proof. . Put ; as runs over so does , and . The double sum splits into , since is real.
So the filter can be stored as , and the response to a patch is the inverse DFT of .
Claim 2: the closed form is the exact minimizer
Given training patches with desired outputs and , consider
If , or if for every , the unique minimizer is
Proof. is a sum of terms that each depend on one , so we minimize each term separately. Fix , write , , and . Then
which is minimized exactly at .
By Parseval's identity , and by Claim 1, the data term is times , the sum of squared errors of the correlation outputs in the image domain. So the filter minimizes the output sum of squared error, which gives the method its name, plus the penalty .
One training image. With , the response to itself is . It equals at every frequency where as , and it is 0 where . So a single image is fit exactly up to its missing frequencies, which is why one image overfits and why several perturbed copies are used.
Claim 3: the running update minimizes an exponentially weighted error
Let be the sums of Claim 2 over the initial training set, and for let
with . Then is the minimizer of
where is the data term over the initial set.
Proof. By induction, , and the same for . The proof of Claim 2 works with positive weights on the terms: with weights the minimizer is . The weights here are for the initial terms and for frame , which give exactly and .
Claim 4: a circular shift of the input moves the peak by the same amount
If for all (indices modulo ), then the response to is , where is the response to .
Proof. .
So if the filter gives its peak at the patch center for the target, a target that moved by gives the peak at , and line L7 recovers . For a real frame the new patch is not a circular shift of the old one: new content enters at one side. The cosine window lowers the weight of the border, but the claim then holds only approximately. This is a heuristic step, and the example on the page measures how well it works.
What is not claimed
The peak to sidelobe ratio and its threshold are heuristics; nothing here says that a low ratio means failure or a high ratio means success. The filter is optimal only for the training patches and the stated objective. Whether it finds the target in a new frame depends on how much the appearance changed.
Complexity
A 2D FFT of points costs . A frame uses three transforms (lines L3, L4 and L8) and entry-by-entry work, so it costs . The start costs for the training patches, so frames cost in all. The extra space is for , and the target transform . The cost depends on the patch, not on the frame, which is why the method is fast.
Properties
- Closed form. No iterative training; the filter is a quotient of two running sums.
- Fast. A few FFTs of a small patch per frame.
- Integer shifts. The peak is on the pixel grid; subpixel accuracy needs interpolation of the peak.
- Fixed scale. The plain filter does not change its size; scale needs a separate search.
- Circular boundary. The training implicitly treats the patch as periodic, so shifted copies of the target wrap around at the border. The cosine window hides this, but it also limits the motion that can be found to a part of the patch.
- Single channel. The original works on gray values; multichannel features need a sum over channels.
Variants and improvements
- ASEF. The earlier average of synthetic exact filters by Bolme and colleagues averages the exact filter of each image instead of summing numerators and denominators; MOSSE is more stable when a frequency is weak.
- Kernelized correlation filter. Henriques and colleagues showed that the filter is ridge regression on all cyclic shifts of the patch, and used kernels and multichannel features such as HOG.
- Scale filters. A second 1D filter over a few scales of the patch estimates the size.
- Spatial regularization. Penalize filter values far from the center to reduce the boundary effect of the circular model.
- Subpixel peaks. Fit a parabola to the peak and its neighbors.
When to use it
Use MOSSE when you need a very fast single-target tracker with modest accuracy, for example on a small device or as a component that runs many times per frame. It needs only an FFT. For better accuracy at a similar cost, use the kernelized correlation filter with HOG features. For large changes of appearance or scale, use a learned tracker such as siamese tracking.
Pitfalls
- No regularization. A frequency where all training patches are near 0 gives a huge or undefined filter entry, as in the example. Always add .
- No window. Without the cosine window, the border of the patch is a strong edge after the circular wrap, and the filter learns it.
- Patch sizes. The radix-2 FFT needs a power of two; with other sizes, use a mixed-radix FFT or pad the patch.
- A threshold copied from the paper. The PSR values depend on the patch size, the exclusion window and the preprocessing. Calibrate the threshold on your own data, as the example shows with values near 15 instead of 20 to 60.
- Updating while lost. Training on an occluder teaches the filter the occluder. Skip the update when the ratio is low, as line L6 does.
- Sign of the shift. Whether the peak moves by or depends on which of and is conjugated. Check it with a known shift.
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/mosse-filter/. The authors are listed in prov/Q4156Y.jsonl.
"""The MOSSE correlation filter tracker of Bolme, Beveridge, Draper and Lui
(2010), with a radix-2 FFT in pure Python.
Images are lists of rows, indexed img[v][u]; the center of pixel (u, v) is the
point (u, v). Patches are n x n with n a power of two; the center of a patch
is its pixel (n // 2, n // 2). Correlation is circular: the response is
g[v][u] = sum over (i, j) of f[(j + v) % n][(i + u) % n] h[j][i], so that
G = F . conj(H) in the Fourier domain.
"""
import cmath
import math
import random
def fft(x, inverse=False):
"""Radix-2 FFT of a list of complex numbers whose length is a power of
two. The inverse transform 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 gaussian_target(n, sigma=2.0):
"""The desired output: a Gaussian peak at the patch center."""
c = n // 2
return [[math.exp(-((u - c) ** 2 + (v - c) ** 2) / (2 * sigma * sigma)) for u in range(n)]
for v in range(n)]
def preprocess(patch):
"""Log transform, zero mean and unit norm, then a cosine window."""
n = len(patch)
x = [[math.log(p + 1.0) for p in row] for row in patch]
mean = sum(map(sum, x)) / (n * n)
x = [[p - mean for p in row] for row in x]
norm = math.sqrt(sum(p * p for row in x for p in row)) or 1.0
win = [math.sin(math.pi * (i + 0.5) / n) for i in range(n)]
return [[x[v][u] / norm * win[u] * win[v] for u in range(n)] for v in range(n)]
def sample(img, u, v):
"""Bilinear sample at a real point, indices clamped."""
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)))
def crop(img, center, n, affine=None):
"""The n x n patch whose center pixel is at `center`. If `affine` is a
2 x 2 matrix, patch offsets are mapped through it first."""
c = n // 2
a = affine or [[1.0, 0.0], [0.0, 1.0]]
out = []
for v in range(n):
row = []
for u in range(n):
du, dv = u - c, v - c
row.append(sample(img, center[0] + a[0][0] * du + a[0][1] * dv,
center[1] + a[1][0] * du + a[1][1] * dv))
out.append(row)
return out
def response(f_hat, a_hat, b_hat, eps):
"""The spatial response g = IFFT(F . A / (B + eps))."""
n = len(f_hat)
g_hat = [[f_hat[v][u] * a_hat[v][u] / (b_hat[v][u] + eps) for u in range(n)] for v in range(n)]
return [[z.real for z in row] for row in fft2(g_hat, inverse=True)]
def psr(g, exclude=5):
"""Peak to sidelobe ratio: (peak - mean) / std of the response outside
the (2 exclude + 1)-square around the peak. Returns (psr, (pu, pv))."""
n = len(g)
pv, pu = max(((v, u) for v in range(n) for u in range(n)), key=lambda t: g[t[0]][t[1]])
side = [g[v][u] for v in range(n) for u in range(n)
if min(abs(u - pu), n - abs(u - pu)) > exclude or min(abs(v - pv), n - abs(v - pv)) > exclude]
mean = sum(side) / len(side)
std = math.sqrt(sum((s - mean) ** 2 for s in side) / len(side))
return (g[pv][pu] - mean) / std if std > 0 else math.inf, (pu, pv)
class Mosse:
def __init__(self, img, center, n=32, sigma=2.0, eta=0.125, eps=1e-5,
perturbations=8, seed=0, psr_min=7.0):
self.n, self.eta, self.eps, self.psr_min = n, eta, eps, psr_min
self.center = center
self.g_hat = fft2(gaussian_target(n, sigma))
rng = random.Random(seed)
affines = [None]
for _ in range(perturbations):
t = rng.uniform(-0.15, 0.15)
s = rng.uniform(0.9, 1.1)
affines.append([[s * math.cos(t), -s * math.sin(t)], [s * math.sin(t), s * math.cos(t)]])
self.a_hat = [[0j] * n for _ in range(n)]
self.b_hat = [[0j] * n for _ in range(n)]
for aff in affines: # @line L1
f_hat = fft2(preprocess(crop(img, center, n, aff)))
for v in range(n): # @line L2
for u in range(n):
self.a_hat[v][u] += self.g_hat[v][u] * f_hat[v][u].conjugate()
self.b_hat[v][u] += f_hat[v][u] * f_hat[v][u].conjugate()
def update(self, img):
"""Track into the next frame. Returns (center, psr, ok)."""
n = self.n
f_hat = fft2(preprocess(crop(img, self.center, n))) # @line L3
g = response(f_hat, self.a_hat, self.b_hat, self.eps) # @line L4
score, (pu, pv) = psr(g) # @line L5
if score < self.psr_min: # @line L6
return self.center, score, False
du, dv = pu - n // 2, pv - n // 2
self.center = (self.center[0] + du, self.center[1] + dv) # @line L7
f_hat = fft2(preprocess(crop(img, self.center, n))) # @line L8
for v in range(n): # @line L9
for u in range(n):
self.a_hat[v][u] = (self.eta * self.g_hat[v][u] * f_hat[v][u].conjugate()
+ (1 - self.eta) * self.a_hat[v][u])
self.b_hat[v][u] = (self.eta * f_hat[v][u] * f_hat[v][u].conjugate()
+ (1 - self.eta) * self.b_hat[v][u])
return self.center, score, True # @line L10
test_mosse_filter.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mosse-filter/. The authors are listed in prov/Q4156Y.jsonl.
import cmath
import math
import random
import pytest
from mosse_filter import Mosse, fft, fft2, gaussian_target, response
def dft(x):
n = len(x)
return [sum(x[j] * cmath.exp(-2j * math.pi * j * k / n) for j in range(n)) for k in range(n)]
def test_fft_matches_the_direct_transform():
rng = random.Random(1)
for n in [1, 2, 8, 16]:
x = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
for a, b in zip(fft(x), dft(x)):
assert abs(a - b) < 1e-9
for a, b in zip(fft(fft(x), inverse=True), x):
assert abs(a - b) < 1e-12
with pytest.raises(ValueError):
fft([1, 2, 3])
def test_fft2_matches_the_direct_transform():
rng = random.Random(2)
n = 4
img = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
got = fft2(img)
for k in range(n):
for l in range(n):
want = sum(img[v][u] * cmath.exp(-2j * math.pi * (u * l + v * k) / n)
for v in range(n) for u in range(n))
assert abs(got[k][l] - want) < 1e-9
def test_product_with_conjugate_is_circular_correlation():
rng = random.Random(3)
n = 8
f = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
h = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
ff, hh = fft2(f), fft2(h)
g = fft2([[ff[v][u] * hh[v][u].conjugate() for u in range(n)] for v in range(n)], inverse=True)
for v in range(n):
for u in range(n):
want = sum(f[(j + v) % n][(i + u) % n] * h[j][i] for j in range(n) for i in range(n))
assert abs(g[v][u] - want) < 1e-9
def test_single_image_filter_reproduces_the_target():
rng = random.Random(4)
n = 16
f_hat = fft2([[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)])
g = gaussian_target(n)
g_hat = fft2(g)
a = [[g_hat[v][u] * f_hat[v][u].conjugate() for u in range(n)] for v in range(n)]
b = [[f_hat[v][u] * f_hat[v][u].conjugate() for u in range(n)] for v in range(n)]
out = response(f_hat, a, b, 1e-12)
for v in range(n):
for u in range(n):
assert abs(out[v][u] - g[v][u]) < 1e-6
def test_a_missing_frequency_lowers_the_peak():
f = [1, 2, 0, -1]
f_hat = fft(f)
assert abs(f_hat[2]) < 1e-12
g_hat = fft([1, 0, 0, 0])
eps = 1e-9
h_conj = [gk * fk.conjugate() / (fk * fk.conjugate() + eps) for gk, fk in zip(g_hat, f_hat)]
out = fft([fk * hk for fk, hk in zip(f_hat, h_conj)], inverse=True)
for a, b in zip(out, [0.75, 0.25, -0.25, 0.25]):
assert abs(a - b) < 1e-6
def texture(seed, k, lo, hi):
rng = random.Random(seed)
blobs = [(rng.uniform(lo, hi), rng.uniform(lo, hi), rng.uniform(2, 4), 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
N, HALF = 64, 16
def make_scene():
back = texture(1, 40, -5, N + 5)
bg = [[back(u, v) for u in range(N)] for v in range(N)]
target = texture(2, 20, -3, 2 * HALF + 3)
other = texture(3, 20, -3, 2 * HALF + 3)
def frame(c, tex=target):
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] = tex(du + HALF, dv + HALF)
return img
return frame, other
def test_tracks_a_moving_target_and_stops_at_an_occlusion():
frame, other = make_scene()
truth = [(24 + 2.4 * t, 26 + 1.7 * t) for t in range(7)]
tracker = Mosse(frame(truth[0]), truth[0])
for c in truth[1:]:
p, score, ok = tracker.update(frame(c))
assert ok and score > 7
assert math.dist(p, c) < 1
before = tracker.center
p, score, ok = tracker.update(frame(truth[-1], other))
assert not ok and score < 7
assert p == before
History
Correlation filters for pattern recognition go back to the matched filter and to the synthetic discriminant functions and minimum average correlation energy filters of the optical pattern recognition literature of the 1980s. Bolme, Draper and Beveridge introduced the average of synthetic exact filters (ASEF) for eye localization in 2009. In 2010 Bolme, Beveridge, Draper and Lui gave MOSSE: a single filter fitted to all training outputs at once, with the running update and the peak to sidelobe ratio as a failure test. Their tracker ran at several hundred frames per second. Henriques, Caseiro, Martins and Batista explained the filter as ridge regression on cyclic shifts (2012, 2015), which led to the kernelized correlation filter and to many later correlation filter trackers.
References
- 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 closed-form filter, the preprocessing with log, normalization and cosine window, the Gaussian outputs, the random affine perturbations at the start, the running update with the learning rate, and the peak to sidelobe ratio)
- 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, the whole paper (the link between correlation filters and ridge regression on cyclic shifts)
- Richard Szeliski, Computer Vision, Algorithms and Applications, 2nd edition, Springer, 2022, Chapter 3 (Fourier transforms and the correlation theorem)
Where this leads
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 Q4156Y Edit this page History Report an error Markdown