Algorithm Search⌘K

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.

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
Properties
deterministicnot exactiterativelocalonline
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 I[v][u]I[v][u], with the center of pixel (u,v)(u, v) at the point (u,v)(u, v). Each pixel has a bin b(x)∈{1,…,B}b(x) \in \{1, \ldots, B\}, for example the gray value divided into BB equal ranges, or a quantized color. A window has a center yy and half axes h=(hu,hv)h = (h_u, h_v); for a pixel xx let

r(x;y)=(xu−yuhu)2+(xv−yvhv)2,k(r)=max⁡(1−r,0),r(x; y) = \Big( \frac{x_u - y_u}{h_u} \Big)^2 + \Big( \frac{x_v - y_v}{h_v} \Big)^2, \qquad k(r) = \max(1 - r, 0),

where kk is the profile of the Epanechnikov kernel. The candidate histogram at yy is

pu(y)=C∑x:r(x;y)<1k(r(x;y)) [b(x)=u],C=(∑x:r(x;y)<1k(r(x;y)))−1,p_u(y) = C \sum_{x : r(x; y) < 1} k(r(x; y)) \, [b(x) = u], \qquad C = \Big( \sum_{x : r(x; y) < 1} k(r(x; y)) \Big)^{-1},

so ∑upu(y)=1\sum_u p_u(y) = 1, and it is a kernel density estimate of the colors in the window. The target model qq is the same histogram computed in the first frame at the given window. The similarity is the Bhattacharyya coefficient

ρ(y)=∑u=1Bpu(y) qu,\rho(y) = \sum_{u=1}^B \sqrt{p_u(y)\, q_u},

which is 1 when p(y)=qp(y) = q and lies in [0,1][0, 1] by the Cauchy-Schwarz inequality. In each frame the task is to find a local maximum of ρ\rho near the previous center.

A first-order expansion of pu\sqrt{p_u} around pu(y0)p_u(y_0), with CC held fixed, gives

ρ(y)≈12ρ(y0)+C2∑iwi k(r(xi;y)),wi=qb(xi)pb(xi)(y0).\rho(y) \approx \tfrac12 \rho(y_0) + \tfrac{C}{2} \sum_i w_i\, k(r(x_i; y)), \qquad w_i = \sqrt{\frac{q_{b(x_i)}}{p_{b(x_i)}(y_0)}} .

The second term is a weighted kernel density of pixel positions, and the mean shift step climbs it.

The algorithm

  1. MEAN-SHIFT-STEP(I, q, y₀, h, ε, k_max, j_max)
  2. 1ρ₀ ← Σ_u √(p_u(y₀) q_u)
  3. 2repeat up to k_max times
  4. 3for each pixel xᵢ with r(xᵢ; y₀) < 1 do wᵢ ← √(q_{b(xᵢ)} / p_{b(xᵢ)}(y₀))
  5. 4y₁ ← Σᵢ wᵢ xᵢ / Σᵢ wᵢ ▷ the Epanechnikov mean shift step
  6. 5ρ₁ ← Σ_u √(p_u(y₁) q_u)
  7. 6while ρ₁ < ρ₀ and fewer than j_max halvings are done do
  8. 7y₁ ← (y₀ + y₁) / 2; ρ₁ ← Σ_u √(p_u(y₁) q_u)
  9. 8if ρ₁ < ρ₀ then return y₀
  10. 9if |y₁ - y₀| < ε then return y₁
  11. 10y₀ ← y₁
  12. 11return y₀

The tracker computes qq 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 −k′-k' 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 −k′(r)-k'(r). 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 jmax⁡j_{\max} 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 q=(0.75,0.25)q = (0.75, 0.25) and a window with p(y0)=(0.5,0.5)p(y_0) = (0.5, 0.5). Then ρ(y0)=0.375+0.125=0.9659\rho(y_0) = \sqrt{0.375} + \sqrt{0.125} = 0.9659. A bright pixel gets the weight 0.75/0.5=1.2247\sqrt{0.75 / 0.5} = 1.2247 and a dark pixel 0.25/0.5=0.7071\sqrt{0.25 / 0.5} = 0.7071, 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 64×6464 \times 64 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 h=(8,6)h = (8, 6), there are B=16B = 16 bins of width 16, and ε=0.1\varepsilon = 0.1. The model qq 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 (16,20)(16, 20) to (18.5,21.5)(18.5, 21.5). 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 y1y_1 ρ(y1)\rho(y_1) Move Distance to truth
start (16,20)(16, 20) 0.8926 2.915
1 (17.9872,20.5816)(17.9872, 20.5816) 0.9803 2.071 1.052
2 (18.4890,21.0929)(18.4890, 21.0929) 0.9949 0.716 0.407
3 (18.6726,21.3436)(18.6726, 21.3436) 0.9977 0.311 0.233
4 (18.6176,21.4553)(18.6176, 21.4553) 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 (2.5,1.5)(2.5, 1.5) 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 ρ=0\rho = 0.

Correctness

The full proof is in proofs/correctness.md. It shows four facts.

  • Theorem: one step raises the weighted density. For fixed weights wi≥0w_i \ge 0 and the Epanechnikov profile, the weighted mean y1y_1 of the points in the window at y0y_0 satisfies f(y1)−f(y0)≥W∣y1−y0∣h2f(y_1) - f(y_0) \ge W |y_1 - y_0|_h^2, where f(y)=∑iwik(r(xi;y))f(y) = \sum_i w_i k(r(x_i; y)) and WW is the weight inside the window. The proof uses only the convexity of kk.
  • 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 ff strictly increases.
  • Heuristic: the step climbs a surrogate. The tracker step climbs the linearization of ρ\rho shown above, not ρ\rho itself. The normalizer CC changes with yy on a pixel grid and the weights change at every iteration, so ρ\rho can go down. That is why line L6 exists.
  • Theorem: the accepted coefficients never decrease, and the procedure stops after at most kmax⁡(jmax⁡+1)k_{\max} (j_{\max} + 1) 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 yy has half axes h=(hu,hv)h = (h_u, h_v), and for a point xx we write ∣x∣h2=(xu/hu)2+(xv/hv)2|x|_h^2 = (x_u / h_u)^2 + (x_v / h_v)^2 and ri(y)=∣xi−y∣h2r_i(y) = |x_i - y|_h^2. The Epanechnikov profile is k(r)=max⁡(1−r,0)k(r) = \max(1 - r, 0).

Claim 1: one weighted step raises the weighted density

Let x1,…,xnx_1, \ldots, x_n be points with weights wi≥0w_i \ge 0, and let

f(y)=∑i=1nwi k(ri(y)).f(y) = \sum_{i=1}^n w_i\, k(r_i(y)).

Let S={i:ri(y0)≤1}S = \{ i : r_i(y_0) \le 1 \} and W=∑i∈SwiW = \sum_{i \in S} w_i. If W>0W > 0, the step is y1=∑i∈Swixi/Wy_1 = \sum_{i \in S} w_i x_i / W. Then

f(y1)−f(y0)≥W ∣y1−y0∣h2.f(y_1) - f(y_0) \ge W\, |y_1 - y_0|_h^2 .

Proof. kk is the maximum of the two affine functions 1−r1 - r and 00, so it is convex. For i∈Si \in S, the number −1-1 is a subgradient of kk at ri(y0)r_i(y_0): if ri(y0)<1r_i(y_0) < 1 it is the derivative, and at ri(y0)=1r_i(y_0) = 1 the subgradients are the interval [−1,0][-1, 0]. So k(r)≥k(ri(y0))−(r−ri(y0))k(r) \ge k(r_i(y_0)) - (r - r_i(y_0)) for every rr. For i∉Si \notin S, k(ri(y0))=0≤k(r)k(r_i(y_0)) = 0 \le k(r) for every rr. Summing with the weights,

f(y1)−f(y0)≥∑i∈Swi(ri(y0)−ri(y1)).f(y_1) - f(y_0) \ge \sum_{i \in S} w_i \big( r_i(y_0) - r_i(y_1) \big).

The map y↦∣x−y∣h2y \mapsto |x - y|_h^2 is the squared norm of the inner product ⟨a,b⟩h=aubu/hu2+avbv/hv2\langle a, b \rangle_h = a_u b_u / h_u^2 + a_v b_v / h_v^2. Expanding ∣xi−y0∣h2=∣xi−y1∣h2+2⟨xi−y1,y1−y0⟩h+∣y1−y0∣h2|x_i - y_0|_h^2 = |x_i - y_1|_h^2 + 2 \langle x_i - y_1, y_1 - y_0 \rangle_h + |y_1 - y_0|_h^2 and summing over SS with weights, the middle term is 2⟨∑i∈Swi(xi−y1),y1−y0⟩h=02 \langle \sum_{i \in S} w_i (x_i - y_1), y_1 - y_0 \rangle_h = 0 by the definition of y1y_1. So the right side equals W∣y1−y0∣h2W |y_1 - y_0|_h^2. □\square

Claim 2: with fixed weights, the iteration stops at a fixed point after finitely many steps

Repeat the step of Claim 1 from y0y_0 with the same points and weights, and stop when W=0W = 0 or yj+1=yjy_{j+1} = y_j.

Proof. Every yjy_j with j≥1j \ge 1 is the weighted mean of a nonempty subset of the nn points, so it lies in a finite set of at most 2n2^n points. While the iteration runs, yj+1≠yjy_{j+1} \ne y_j and W>0W > 0, so Claim 1 gives f(yj+1)>f(yj)f(y_{j+1}) > f(y_j). The values of ff strictly increase, so no point of the finite set occurs twice, and the iteration stops after at most 2n+12^n + 1 steps. At the stop, yj+1=yjy_{j+1} = y_j: the point is the weighted mean of the points in its own window. □\square

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 wi=qb(xi)/pb(xi)(y0)w_i = \sqrt{q_{b(x_i)} / p_{b(x_i)}(y_0)}, and pu(y)=C(y)∑ik(ri(y))[b(xi)=u]p_u(y) = C(y) \sum_i k(r_i(y)) [b(x_i) = u] with C(y)=1/∑ik(ri(y))C(y) = 1 / \sum_i k(r_i(y)). For every bin with pu(y0)>0p_u(y_0) > 0, the concavity of the square root gives

pu(y)≤pu(y0)+pu(y)−pu(y0)2pu(y0).\sqrt{p_u(y)} \le \sqrt{p_u(y_0)} + \frac{p_u(y) - p_u(y_0)}{2 \sqrt{p_u(y_0)}} .

Multiplying by qu\sqrt{q_u} and summing gives ρ(y)≤12ρ(y0)+12∑upu(y)qu/pu(y0)\rho(y) \le \frac12 \rho(y_0) + \frac12 \sum_u p_u(y) \sqrt{q_u / p_u(y_0)} over the bins with pu(y0)>0p_u(y_0) > 0 (a bin with pu(y0)=0p_u(y_0) = 0 and pu(y)>0p_u(y) > 0 adds a term that the bound does not cover). If C(y)=C(y0)=CC(y) = C(y_0) = C, the last sum is C f(y)C\, f(y) with the weights wiw_i, and both sides are equal at y=y0y = y_0. So line L4 maximizes, by Claim 1, a function that agrees with ρ\rho to first order at y0y_0. This is a statement about the surrogate only. C(y)C(y) changes with yy on a pixel grid, new bins can enter the window, and ρ(y1)<ρ(y0)\rho(y_1) < \rho(y_0) 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 ρ1≥ρ0\rho_1 \ge \rho_0. 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 jmax⁡j_{\max} times, and the outer loop at most kmax⁡k_{\max} times, so the procedure stops after at most kmax⁡(jmax⁡+1)k_{\max} (j_{\max} + 1) histogram evaluations after the first. □\square

What is not claimed

Nothing here says that the returned location is the true target position, or even a local maximum of ρ\rho. 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 jmax⁡j_{\max} is added here so that the procedure provably stops.

Complexity

One iteration reads the mm pixels of the window for the weights and the step, and mm more pixels for the new histogram, plus O(B)O(B) for the coefficient. Each halving costs one more histogram. So one frame costs Θ(k(j+1)(m+B))\Theta(k (j + 1)(m + B)) in the worst case and Θ(m+B)\Theta(m + B) when the first step is already below ε\varepsilon. The extra space is Θ(B)\Theta(B) for the histograms, plus Θ(m)\Theta(m) 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 qq little.
  • Sensitive to similar colors. A background region with the target's colors is a second maximum of ρ\rho.
  • Fixed scale. The plain method keeps hh 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 −k′(r)-k'(r), 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 pu(y0)=0p_u(y_0) = 0. The weight qu/pu(y0)\sqrt{q_u / p_u(y_0)} is only needed for bins that occur in the window, and those have pu(y0)>0p_u(y_0) > 0 because every pixel inside the window has positive kernel weight. Compute pp 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 ρ1\rho_1 a little below ρ0\rho_0. Cap it and keep the old point.
  • Model drift. Updating qq 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.

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

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

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