Algorithmcore
Mean shift tracking
Also called kernel-based object tracking, Comaniciu-Ramesh-Meer tracker.
Track a target by moving its window up the Bhattacharyya similarity of kernel-weighted color histograms with mean shift steps.
- Solves
- Visual object tracking
- Time
- Θ(k (j + 1) (m + B)) worst · averageΘ(m + B) best
- Space
- Θ(m + B) extra
- Where
- B = the number of histogram bins; j = the halving limit per iteration; k = the iteration limit per frame; m = the number of pixels in the window
- Model
- Real RAM
- Properties
- deterministicnot exactiterativelocalonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dorin Comaniciu, Visvanathan Ramesh, Peter Meer, 2000
Mean shift tracking follows a target through a video by its colors. The target is described by a histogram of the colors in an elliptical window, where pixels near the center count more than pixels near the border. In each new frame the tracker starts at the old position and moves the window to make the histogram under it as similar as possible to the target histogram, with the Bhattacharyya coefficient as the measure of similarity. Each move is one step of the mean shift procedure: the new center is a weighted mean of the pixel positions in the window, with large weights on pixels whose color is more frequent in the target than in the current window. The method was given by Comaniciu, Ramesh and Meer in 2000 and 2003. It is a local search for one visual object tracking problem, with no training and a few iterations per frame.
In plain words
We know what colors the target has, for example a red shirt with a bit of blue. In the next picture we put a window where the target was. The window shows some red, some blue and some background. Pixels with a color that the target has more of than the window has get a strong vote, and pixels with background colors get almost no vote. The new window center is the average position of the votes. Because the target has moved, the strong votes sit on the side where it went, so the window moves that way. We repeat until the window stops moving. The color mix does not care about the shape of the target, so it works for a person who bends or turns, but it cannot tell two things of the same colors apart.
The problem
Images are digital images indexed , with the center of pixel at the point . Each pixel has a bin , for example the gray value divided into equal ranges, or a quantized color. A window has a center and half axes ; for a pixel let
where is the profile of the Epanechnikov kernel. The candidate histogram at is
so , and it is a kernel density estimate of the colors in the window. The target model is the same histogram computed in the first frame at the given window. The similarity is the Bhattacharyya coefficient
which is 1 when and lies in by the Cauchy-Schwarz inequality. In each frame the task is to find a local maximum of near the previous center.
A first-order expansion of around , with held fixed, gives
The second term is a weighted kernel density of pixel positions, and the mean shift step climbs it.
The algorithm
MEAN-SHIFT-STEP(I, q, y₀, h, ε, k_max, j_max)- 1
ρ₀ ← Σ_u √(p_u(y₀) q_u) - 2
repeat up to k_max times - 3
for each pixel xᵢ with r(xᵢ; y₀) < 1 do wᵢ ← √(q_{b(xᵢ)} / p_{b(xᵢ)}(y₀)) - 4
y₁ ← Σᵢ wᵢ xᵢ / Σᵢ wᵢ ▷ the Epanechnikov mean shift step - 5
ρ₁ ← Σ_u √(p_u(y₁) q_u) - 6
while ρ₁ < ρ₀ and fewer than j_max halvings are done do - 7
y₁ ← (y₀ + y₁) / 2; ρ₁ ← Σ_u √(p_u(y₁) q_u) - 8
if ρ₁ < ρ₀ then return y₀ - 9
if |y₁ - y₀| < ε then return y₁ - 10
y₀ ← y₁ - 11
return y₀
The tracker computes once, at the given window in the first frame, and calls MEAN-SHIFT-STEP once per frame, starting from the center found in the frame before. With the Epanechnikov profile, the derivative is 1 inside the window, so the mean shift step of line L4 is a plain weighted mean of the pixel positions; other profiles weight each pixel also by . Line L6 is the test of Comaniciu, Ramesh and Meer: the step climbs the linearized coefficient, and if the true coefficient went down, the step is halved. The cap and the return at line L8 are added so that the procedure always stops.
Example
The weights. Take two bins, bright and dark, a target model and a window with . Then . A bright pixel gets the weight and a dark pixel , so the weighted mean of line L4 moves toward the bright pixels. A bin that the target does not have gets the weight 0.
One frame. The frames are with gray noise from 0 to 95. The target is an ellipse with half axes 8 and 6; its left half has values from 200 to 239, its right half values from 130 to 159, and the noise is drawn again in each frame (seed 4). The window has , there are bins of width 16, and . The model has five nonzero bins: 0.278 and 0.275 for the bins of 128 to 159, and 0.118, 0.174 and 0.155 for the bins of 192 to 239. In frame 1 the target has moved from to . At the old center the window still holds noise, and the background bins get weight 0, while the bins of 128 to 159 get the weights 1.447 and 1.570 because they are rarer in the window than in the model. The iterations are:
| Step | Center | Move | Distance to truth | |
|---|---|---|---|---|
| start | 0.8926 | 2.915 | ||
| 1 | 0.9803 | 2.071 | 1.052 | |
| 2 | 0.9949 | 0.716 | 0.407 | |
| 3 | 0.9977 | 0.311 | 0.233 | |
| 4 | 0.9980 | 0.125 | 0.126 |
The fifth step lands on the same point up to rounding, and the loop stops. The halving of line L6 was not needed here. Over 12 frames with a motion of per frame, the largest error is 0.162 pixel and the smallest coefficient is 0.990.
The reach. A step can only see pixels inside the window, so the target must overlap the window at the old position. With the target moved 6 or 14 pixels to the right, the tracker finds it within 0.08 pixel. Moved 18 pixels, the ellipse no longer overlaps the window of half width 8, every weight is 0, and the tracker stays at the old position with .
Correctness
The full proof is in proofs/correctness.md. It shows four facts.
- Theorem: one step raises the weighted density. For fixed weights and the Epanechnikov profile, the weighted mean of the points in the window at satisfies , where and is the weight inside the window. The proof uses only the convexity of .
- Theorem: finite stopping with fixed weights. Repeating the step with fixed weights reaches a fixed point after finitely many steps, because every iterate is the mean of a subset of the points and strictly increases.
- Heuristic: the step climbs a surrogate. The tracker step climbs the linearization of shown above, not itself. The normalizer changes with on a pixel grid and the weights change at every iteration, so can go down. That is why line L6 exists.
- Theorem: the accepted coefficients never decrease, and the procedure stops after at most histogram evaluations. This follows from lines L6 to L9.
The convergence of the general mean shift sequence of points is a different question. Comaniciu and Meer (2002) gave a proof, and Li, Hu and Wu (2007) showed that the proof has a gap. Nothing here claims that the tracker finds the true target; the coefficient is a similarity score, and a background patch with the same colors scores as well.
Proof: The Epanechnikov mean shift step raises the weighted density, the tracker never accepts a lower coefficient, and both loops stopfull
Notation as on the page. The window at has half axes , and for a point we write and . The Epanechnikov profile is .
Claim 1: one weighted step raises the weighted density
Let be points with weights , and let
Let and . If , the step is . Then
Proof. is the maximum of the two affine functions and , so it is convex. For , the number is a subgradient of at : if it is the derivative, and at the subgradients are the interval . So for every . For , for every . Summing with the weights,
The map is the squared norm of the inner product . Expanding and summing over with weights, the middle term is by the definition of . So the right side equals .
Claim 2: with fixed weights, the iteration stops at a fixed point after finitely many steps
Repeat the step of Claim 1 from with the same points and weights, and stop when or .
Proof. Every with is the weighted mean of a nonempty subset of the points, so it lies in a finite set of at most points. While the iteration runs, and , so Claim 1 gives . The values of strictly increase, so no point of the finite set occurs twice, and the iteration stops after at most steps. At the stop, : the point is the weighted mean of the points in its own window.
This is the reason the Epanechnikov profile is used: the step is a weighted mean, and the convergence argument needs only convexity and the finite set. For profiles with unbounded support the argument does not apply, and the convergence of the sequence of points (not only of the density values) needs more care: Li, Hu and Wu (2007) pointed out a gap in the convergence proof of Comaniciu and Meer (2002).
Claim 3: the tracker step increases a surrogate of the coefficient
In the tracker the weights are , and with . For every bin with , the concavity of the square root gives
Multiplying by and summing gives over the bins with (a bin with and adds a term that the bound does not cover). If , the last sum is with the weights , and both sides are equal at . So line L4 maximizes, by Claim 1, a function that agrees with to first order at . This is a statement about the surrogate only. changes with on a pixel grid, new bins can enter the window, and is possible. The tracker does not rely on the surrogate for correctness; Claim 4 does not use it.
Claim 4: the accepted coefficients never decrease, and the procedure stops
Proof. A location is accepted only at line L10 or returned at line L9, and both are reached only when the test of line L8 failed, that is, when . The returned value at line L8 is the last accepted location. So the sequence of coefficients of accepted locations is nondecreasing, and the returned coefficient is at least the coefficient at the start. The inner loop of lines L6 and L7 runs at most times, and the outer loop at most times, so the procedure stops after at most histogram evaluations after the first.
What is not claimed
Nothing here says that the returned location is the true target position, or even a local maximum of . The coefficient is a heuristic score of similarity; a background patch with the same colors can score as high as the target, and the search sees only locations whose window overlaps the region where the iterations go. The halving rule of lines L6 and L7 is from Comaniciu, Ramesh and Meer; the cap is added here so that the procedure provably stops.
Complexity
One iteration reads the pixels of the window for the weights and the step, and more pixels for the new histogram, plus for the coefficient. Each halving costs one more histogram. So one frame costs in the worst case and when the first step is already below . The extra space is for the histograms, plus if the window pixels are stored. The cost does not depend on the size of the image, only on the window, which is why the method ran in real time on the computers of 2000.
Properties
- Local. It finds a local maximum near the start. The target must overlap the window of the old position, as the reach example shows.
- Shape-free. The histogram ignores where the colors are inside the window, so bending, rotation and partial deformation change little.
- Sensitive to similar colors. A background region with the target's colors is a second maximum of .
- Fixed scale. The plain method keeps fixed; a target that grows or shrinks needs a scale rule (see the variants).
- Deterministic and training-free. There is nothing to learn beyond the first histogram.
Variants and improvements
- Scale search. Comaniciu, Ramesh and Meer run the search with a few window sizes around the current one and keep the size with the best coefficient, then smooth the size over time.
- Background-weighted histogram. Lower the model weight of colors that are frequent in a ring around the target, so that the background has less pull.
- CAMShift. Replace the coefficient by a back-projected probability image and adapt the window size and orientation from the moments of that image at each frame.
- Prediction. Start the search at the position that a Kalman filter predicts, so that faster targets stay inside the reach.
- Scale space. Collins (2003) ran mean shift in a joint space of position and scale.
- Other kernels and features. A Gaussian profile gives a weighted step with weights , and the histogram can be built from color, texture or gradient orientation.
When to use it
Use mean shift tracking when the target has a distinctive color distribution, the motion between frames is smaller than the window, and you need a very cheap tracker with no training, for example for faces, hands or colored objects in a fixed scene. Do not use it when the background has the same colors, the target is gray and textured (use correlation filters or KLT points), or the scale changes a lot.
Pitfalls
- Bins with . The weight is only needed for bins that occur in the window, and those have because every pixel inside the window has positive kernel weight. Compute from the same window as the weights, or the division fails.
- No overlap. If every weight in the window is 0, there is no step. Return the old position and report the low coefficient, as the reach example does.
- Too many bins. With many bins and a small window, each bin holds a few pixels and the histogram is noisy. With too few bins, target and background share bins.
- An endless halving loop. Without a cap, line L6 can halve forever when rounding keeps a little below . Cap it and keep the old point.
- Model drift. Updating at every frame lets the background into the model over time. Keep the first model, or update it slowly and only when the coefficient is high.
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/mean-shift-tracking/. The authors are listed in prov/85H8BD.jsonl.
"""Mean shift tracking (Comaniciu, Ramesh and Meer) with the Epanechnikov
profile and the Bhattacharyya coefficient.
Images are lists of rows of integer gray values 0..255, indexed img[v][u];
the center of pixel (u, v) is the point (u, v). A window is an ellipse with
center y = (yu, yv) and half axes (hu, hv). The normalized squared distance
of pixel x is r = ((u - yu) / hu)^2 + ((v - yv) / hv)^2, and the profile is
k(r) = 1 - r for r < 1 and 0 otherwise. Gray values fall into `bins` equal
bins.
"""
import math
def bin_of(value, bins):
return value * bins // 256
def window_pixels(img, y, h):
"""The pixels (u, v, r) with r < 1 for the window at y with half axes h."""
rows, cols = len(img), len(img[0])
out = []
for v in range(max(0, math.ceil(y[1] - h[1])), min(rows - 1, math.floor(y[1] + h[1])) + 1):
for u in range(max(0, math.ceil(y[0] - h[0])), min(cols - 1, math.floor(y[0] + h[0])) + 1):
r = ((u - y[0]) / h[0]) ** 2 + ((v - y[1]) / h[1]) ** 2
if r < 1:
out.append((u, v, r))
return out
def histogram(img, y, h, bins):
"""Kernel-weighted histogram p_u(y), normalized to sum 1."""
p = [0.0] * bins
for u, v, r in window_pixels(img, y, h):
p[bin_of(img[v][u], bins)] += 1 - r
s = sum(p)
if s == 0:
return p
return [x / s for x in p]
def bhattacharyya(p, q):
"""The Bhattacharyya coefficient sum_u sqrt(p_u q_u)."""
return sum(math.sqrt(a * b) for a, b in zip(p, q))
def weighted_mean_shift(points, weights, y, h):
"""One mean shift step of the weighted Epanechnikov density
f(y) = sum_i w_i k(|(x_i - y) / h|^2): the w-weighted mean of the points
inside the window at y (the profile g = -k' is 1 there). Returns y if
the window holds no point with positive weight."""
su = sv = sw = 0.0
for (u, v), w in zip(points, weights):
if ((u - y[0]) / h[0]) ** 2 + ((v - y[1]) / h[1]) ** 2 <= 1 and w > 0:
su += w * u
sv += w * v
sw += w
if sw == 0:
return y
return (su / sw, sv / sw)
def mean_shift_step(img, q, y0, p0, h, bins, eps=0.1, max_iter=20, max_halving=10):
"""Find the target near y0 in img. q is the target model and p0 the
histogram at y0. Returns (y, rho, history), where history lists the
Bhattacharyya coefficient of every accepted location."""
rho0 = bhattacharyya(p0, q) # @line L1
history = [rho0]
for _ in range(max_iter): # @line L2
su = sv = sw = 0.0
for u, v, r in window_pixels(img, y0, h): # @line L3
b = bin_of(img[v][u], bins)
w = math.sqrt(q[b] / p0[b])
su += w * u
sv += w * v
sw += w
if sw == 0:
return y0, rho0, history
y1 = (su / sw, sv / sw) # @line L4
p1 = histogram(img, y1, h, bins) # @line L5
rho1 = bhattacharyya(p1, q)
halving = 0
while rho1 < rho0 and halving < max_halving: # @line L6
y1 = ((y0[0] + y1[0]) / 2, (y0[1] + y1[1]) / 2) # @line L7
p1 = histogram(img, y1, h, bins)
rho1 = bhattacharyya(p1, q)
halving += 1
if rho1 < rho0: # @line L8
return y0, rho0, history
history.append(rho1)
if math.hypot(y1[0] - y0[0], y1[1] - y0[1]) < eps: # @line L9
return y1, rho1, history
y0, p0, rho0 = y1, p1, rho1 # @line L10
return y0, rho0, history # @line L11
def track(frames, y0, h, bins=16, eps=0.1, max_iter=20):
"""Track the target that frames[0] shows in the window at y0. The model q
is the histogram of that window. Returns the list of centers and the
list of Bhattacharyya coefficients, one per frame."""
q = histogram(frames[0], y0, h, bins)
centers, scores = [y0], [1.0]
y = y0
for img in frames[1:]:
p = histogram(img, y, h, bins)
y, rho, _ = mean_shift_step(img, q, y, p, h, bins, eps, max_iter)
centers.append(y)
scores.append(rho)
return centers, scores
test_mean_shift_tracking.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mean-shift-tracking/. The authors are listed in prov/85H8BD.jsonl.
import math
import random
from mean_shift_tracking import (
bhattacharyya,
histogram,
mean_shift_step,
track,
weighted_mean_shift,
)
N = 64
H = (8, 6)
def scene(rng, c):
"""Noise from 0 to 95, and an ellipse with half axes 8 and 6 at c whose
left half is bright (200 to 239) and right half is mid gray (130 to 159)."""
img = [[rng.randrange(0, 96) for _ in range(N)] for _ in range(N)]
for v in range(N):
for u in range(N):
du, dv = u - c[0], v - c[1]
if (du / 8) ** 2 + (dv / 6) ** 2 <= 1:
img[v][u] = 200 + rng.randrange(0, 40) if du < 0 else 130 + rng.randrange(0, 30)
return img
def test_histogram_and_coefficient():
rng = random.Random(1)
img = [[rng.randrange(256) for _ in range(N)] for _ in range(N)]
for y in [(20, 20), (31.4, 12.7), (3, 60)]:
p = histogram(img, y, H, 16)
assert abs(sum(p) - 1) < 1e-12
assert abs(bhattacharyya(p, p) - 1) < 1e-12
q = histogram(img, (40, 40), H, 16)
assert 0 <= bhattacharyya(p, q) <= 1 + 1e-12
def test_weighted_step_raises_the_density():
rng = random.Random(2)
h = (5.0, 3.0)
def density(pts, ws, y):
s = 0.0
for (u, v), w in zip(pts, ws):
r = ((u - y[0]) / h[0]) ** 2 + ((v - y[1]) / h[1]) ** 2
if r < 1:
s += w * (1 - r)
return s
for _ in range(200):
pts = [(rng.uniform(0, 20), rng.uniform(0, 20)) for _ in range(30)]
ws = [rng.uniform(0, 2) for _ in pts]
y0 = (rng.uniform(0, 20), rng.uniform(0, 20))
y1 = weighted_mean_shift(pts, ws, y0, h)
inside = sum(w for (u, v), w in zip(pts, ws)
if ((u - y0[0]) / h[0]) ** 2 + ((v - y0[1]) / h[1]) ** 2 <= 1)
gain = inside * (((y1[0] - y0[0]) / h[0]) ** 2 + ((y1[1] - y0[1]) / h[1]) ** 2)
assert density(pts, ws, y1) - density(pts, ws, y0) >= gain - 1e-9
def test_model_window_is_a_fixed_point():
img = scene(random.Random(3), (30, 30))
q = histogram(img, (30, 30), H, 16)
y, rho, history = mean_shift_step(img, q, (30, 30), q, H, 16)
assert math.dist(y, (30, 30)) < 1e-9
assert abs(rho - 1) < 1e-12
assert len(history) == 2
def test_coefficient_never_decreases():
rng = random.Random(4)
img = scene(rng, (30, 32))
q = histogram(scene(random.Random(5), (30, 32)), (30, 32), H, 16)
for _ in range(10):
y0 = (30 + rng.uniform(-12, 12), 32 + rng.uniform(-9, 9))
_, _, history = mean_shift_step(img, q, y0, histogram(img, y0, H, 16), H, 16)
for a, b in zip(history, history[1:]):
assert b >= a
def test_tracks_a_moving_target():
rng = random.Random(4)
truth = [(16 + 2.5 * t, 20 + 1.5 * t) for t in range(12)]
frames = [scene(rng, c) for c in truth]
centers, scores = track(frames, truth[0], H)
for c, t in zip(centers, truth):
assert math.dist(c, t) < 0.3
assert min(scores) > 0.98
def test_reach_is_set_by_the_overlap():
for jump, found in [(6, True), (14, True), (18, False)]:
rng = random.Random(4)
frames = [scene(rng, (20, 30)), scene(rng, (20 + jump, 30))]
centers, scores = track(frames, (20, 30), H)
if found:
assert math.dist(centers[1], (20 + jump, 30)) < 0.5
else:
assert centers[1] == (20, 30)
assert scores[1] == 0
History
The mean shift procedure goes back to Fukunaga and Hostetler (1975), who used it to find the modes of a density estimate, and Cheng (1995) generalized it. Comaniciu and Meer applied it to segmentation and clustering in image space, and Comaniciu, Ramesh and Meer (2000) used it for tracking: they wrote the Bhattacharyya coefficient between a target histogram and a candidate histogram, linearized it, and showed that the mean shift step on a weighted density climbs the linearization. Their 2003 paper "Kernel-based object tracking" gave the full framework, with the Epanechnikov kernel, the halving test, scale adaptation and the background-weighted histogram. Bradski (1998) had used mean shift on a color probability image for face tracking in CAMShift. Li, Hu and Wu (2007) pointed out a gap in the 2002 convergence proof of mean shift.
References
- Dorin Comaniciu, Visvanathan Ramesh and Peter Meer, Kernel-based object tracking, IEEE Transactions on Pattern Analysis and Machine Intelligence 25(5), 2003, 564 to 577, the whole paper (the kernel-weighted histograms, the Bhattacharyya coefficient, its linearization, the weights, the Epanechnikov step and the halving test)
- Dorin Comaniciu, Visvanathan Ramesh and Peter Meer, Real-time tracking of non-rigid objects using mean shift, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2000, volume 2, 142 to 149, the whole paper (the first form of the tracker)
- Dorin Comaniciu and Peter Meer, Mean shift, a robust approach toward feature space analysis, IEEE Transactions on Pattern Analysis and Machine Intelligence 24(5), 2002, 603 to 619, the whole paper (the mean shift procedure and its convergence argument)
- Xiangru Li, Zhanyi Hu and Fuchao Wu, A note on the convergence of the mean shift, Pattern Recognition 40(6), 2007, 1756 to 1762, the whole paper (the gap in the earlier convergence proof)
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 85H8BD Edit this page History Report an error Markdown