Algorithm Search⌘K

Algorithmcore

CAMShift

Also called continuously adaptive mean shift.

Mean shift on a color probability image whose window size and orientation adapt from the moments of the distribution at each frame.

Time
Θ(W H + k m) worst · averageΘ(W H + m) best
Space
Θ(W H + B) extra
Where
B = the number of histogram bins; H = image height; W = image width; k = the iteration limit per frame; m = the number of pixels in the window
Properties
deterministicnot exactiterativelocalonline
Origin
Gary R. Bradski, 1998

CAMShift (continuously adaptive mean shift) tracks a colored target by running mean shift on a probability image. A histogram of the target colors becomes a lookup table, and every pixel of a new frame is replaced by the table value of its color, so bright pixels in the probability image are pixels that look like the target. The tracker moves a window to the centroid of the probability inside it until the window stops moving. Then it reads the size of the window for the next frame from the total probability inside it, and the orientation, length and width of the target from the second moments. Gary Bradski described it in 1998 for face tracking in a user interface. It is a simpler cousin of mean shift tracking, with an adaptive window in place of a fixed one.

In plain words

Suppose the target is a face, and faces have a skin color. We make a gray picture in which each pixel is bright if its color is a common skin color and dark if not. We put a box where the face was and move the box to the center of brightness inside it. We repeat until the box stays still. Then we count how much brightness is in the box. A large face gives a lot, so we make the box larger for the next picture, and a small face gives less, so we make it smaller. The way the brightness spreads inside the box also tells us whether the face is tilted, and by how much.

The problem

The frames 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), uu to the right and vv down. Each pixel has a bin b(x)∈{1,…,B}b(x) \in \{1, \ldots, B\}; Bradski uses the hue of a color pixel and ignores pixels with low saturation, where hue is not reliable. On this page the bin is a gray value divided into BB equal ranges. The target is given as a window in the first frame. The histogram h1,…,hBh_1, \ldots, h_B of that window, scaled so that the largest entry is 255, is the lookup table, and the probability image of a frame is P(x)=hb(x)P(x) = h_{b(x)}.

For a window RR, the moments of PP are

Mij=∑(u,v)∈RuivjP(u,v),xc=M10M00,yc=M01M00.M_{ij} = \sum_{(u, v) \in R} u^i v^j P(u, v), \qquad x_c = \frac{M_{10}}{M_{00}}, \quad y_c = \frac{M_{01}}{M_{00}} .

The task in each frame is to find a window centered on the centroid of the probability inside it, and to report its size and the orientation and spread of the mass. A window here is a center (cu,cv)(c_u, c_v) with half sizes (au,av)(a_u, a_v), that is the pixels with ∣u−cu∣≤au|u - c_u| \le a_u and ∣v−cv∣≤av|v - c_v| \le a_v.

The algorithm

  1. CAMSHIFT(F₀, ..., F_N, window, k_max, ε)
  2. 1h ← histogram of the window in F₀, scaled so that max h = 255
  3. 2for t ← 1 to N do P(x) ← h_{b(x)} for every pixel x of F_t
  4. 3repeat up to k_max times
  5. 4compute M₀₀, M₁₀, M₀₁ of P in the window
  6. 5if M₀₀ = 0 then report LOST and keep the window
  7. 6move the window center to (M₁₀/M₀₀, M₀₁/M₀₀)
  8. 7if the center moved less than ε then leave the loop
  9. 8s ← 2 √(M₀₀ / 256), rounded up to an odd integer, at least 3
  10. 9(θ, l, w) ← the axis angle and the two spreads from M₂₀, M₁₁, M₀₂ ▷ formulas below
  11. 10the window for frame t + 1 has the new center and side s; report (x_c, y_c, θ, l, w)
  12. 11return the reports

Lines L3 to L7 are mean shift with a flat kernel on the probability image: the step is the centroid of PP in the window. Line L8 is Bradski's size rule; the number 256 is the largest value of PP plus one, so for a solid target of probability near 255, M00/256M_{00} / 256 is close to its area in pixels. Bradski makes the next window ss wide and 1.2s1.2 s long for faces, which are longer than they are wide; the code has a factor for that, set to 1 by default. Line L9 uses

a=M20M00−xc2,b=2(M11M00−xcyc),c=M02M00−yc2,θ=12atan2⁡(b,a−c),a = \frac{M_{20}}{M_{00}} - x_c^2, \quad b = 2 \Big( \frac{M_{11}}{M_{00}} - x_c y_c \Big), \quad c = \frac{M_{02}}{M_{00}} - y_c^2, \quad \theta = \tfrac12 \operatorname{atan2}(b, a - c),
l=a+c+b2+(a−c)22,w=a+c−b2+(a−c)22.l = \sqrt{\frac{a + c + \sqrt{b^2 + (a - c)^2}}{2}}, \qquad w = \sqrt{\frac{a + c - \sqrt{b^2 + (a - c)^2}}{2}} .

Here θ\theta is the orientation of the major axis, measured from the uu axis toward the vv axis (clockwise on the screen, since vv points down), and ll and ww are the standard deviations of the mass along the two axes. Bradski writes the angle with the arctangent of b/(a−c)b / (a - c); atan2 picks the right quadrant. Bradski also computes the probability image only in a region a little larger than the window, not the whole frame.

Example

The size rule. A 10×1010 \times 10 square of probability 255 inside the window gives M00=25500M_{00} = 25500 and s=225500/256=19.96s = 2\sqrt{25500 / 256} = 19.96, which rounds up to 20 and then to the odd 21. So the next window is about twice the side of the target. The centroid is the center of the square, and a=c=99/12a = c = 99/12 (the variance of 10 consecutive integers) and b=0b = 0, so l=w=2.872l = w = 2.872.

A tilted ellipse. A solid ellipse with semi-axes 12 and 5, tilted 30 degrees, covers 193 pixels of probability 255, so M00=49215M_{00} = 49215 and s=29s = 29. Line L9 gives θ=30.98\theta = 30.98 degrees, l=6.029l = 6.029 and w=2.546w = 2.546. For the continuous ellipse the exact values are 30 degrees, 12/2=612/2 = 6 and 5/2=2.55/2 = 2.5 (the proof shows why the lengths are half the semi-axes); the difference comes from the pixel grid. Started at (36,43)(36, 43) with half size 15, the loop moves the window to the center (40,40)(40, 40).

A target that moves and grows. The frames are 80×8080 \times 80 with gray noise from 0 to 119 (seed 7) and a square target with values from 180 to 239, which moves by (3,2)(3, 2) per frame while its half side grows from 4 to 8.5 over 10 frames. The first window is the target itself, so the lookup table is 0 for all background bins. In frame 1 the window has half size 4 and the target, now a little larger, has moved 3 pixels: the loop stops at (21.98,26.60)(21.98, 26.60), 1.09 pixels short of the true center, because a window no larger than the target sees only part of it and the centroid of the part is a fixed point. The size rule then sets the half size to 6.5. From frame 2 on, the window is larger than the target, the error stays between 0.08 and 0.33 pixel, and the half size grows with the target: 6.5, 9.5, 9.5, 11.5, 11.5, 12.5, 12.5, 14.5, 14.5.

Correctness

The full proof is in proofs/correctness.md. These are theorems about the formulas.

  • Centroid. Line L6 moves the window to the centroid of the probability inside it, and a window centered on its own centroid is a fixed point of the loop.
  • Orientation and lengths. With Σ=(ab/2b/2c)\Sigma = \begin{pmatrix} a & b/2 \\ b/2 & c \end{pmatrix} the covariance of the mass, (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta) is an eigenvector for its larger eigenvalue, and ll and ww are the square roots of the two eigenvalues. For a uniform ellipse with semi-axes A≥BA \ge B these are A/2A/2 and B/2B/2, and θ\theta is the angle of its major axis.
  • Size. For a uniform target of nn pixels at 255, s=2n255/256s = 2\sqrt{n}\sqrt{255/256}, so for a square of side ℓ\ell the window side is just under 2ℓ2\ell before rounding.
  • Stopping. The loop stops after at most kmax⁡k_{\max} iterations.

Bradski's paper says that mean shift converges. For a disc window the flat-kernel step climbs a density estimate with the Epanechnikov kernel, as on the mean shift tracking page. The rectangular window used here is not covered by that argument, and on a pixel grid the loop can stop short, as in the example. So the page claims no convergence theorem; the cap is what ends the loop. Whether the window covers the true target depends on the colors, and the back projection is a heuristic.

Proof: The moment formulas of CAMShift give the centroid, the principal axis and the spread of the probability mass, the size rule doubles a uniform target, and the loop stopsfull

Notation as on the page. P(x)≥0P(x) \ge 0 is the probability image, the window RR is a finite set of pixels, and the moments are Mij=∑(u,v)∈RuivjP(u,v)M_{ij} = \sum_{(u, v) \in R} u^i v^j P(u, v). We assume M00>0M_{00} > 0; line L5 handles the other case.

Claim 1: lines L4 and L6 compute the centroid, and a fixed point is a window centered on its own centroid

(xc,yc)=(M10/M00,M01/M00)(x_c, y_c) = (M_{10} / M_{00}, M_{01} / M_{00}) is the mean of the pixel positions in RR weighted by PP, which is the definition of the centroid of the mass PP restricted to RR. Line L6 moves the window center there. If the window is centered at (xc,yc)(x_c, y_c) of its own pixels, the next centroid equals the center, so the move is 0 and line L7 stops. □\square

Claim 2: the orientation and the axis lengths are those of the covariance matrix

Let a=M20/M00−xc2a = M_{20} / M_{00} - x_c^2, b=2(M11/M00−xcyc)b = 2 (M_{11} / M_{00} - x_c y_c) and c=M02/M00−yc2c = M_{02} / M_{00} - y_c^2. Then

Σ=(ab/2b/2c)\Sigma = \begin{pmatrix} a & b/2 \\ b/2 & c \end{pmatrix}

is the covariance matrix of the position under the weights P/M00P / M_{00}, since for example ∑P(u−xc)2/M00=M20/M00−xc2\sum P (u - x_c)^2 / M_{00} = M_{20} / M_{00} - x_c^2. Let θ=12atan2⁡(b,a−c)\theta = \frac12 \operatorname{atan2}(b, a - c), e=(cos⁡θ,sin⁡θ)e = (\cos \theta, \sin \theta) and f=(−sin⁡θ,cos⁡θ)f = (-\sin \theta, \cos \theta), and let RθR_\theta be the rotation with columns ee and ff. Write a−c=κcos⁡2θa - c = \kappa \cos 2\theta and b=κsin⁡2θb = \kappa \sin 2\theta with κ=b2+(a−c)2≥0\kappa = \sqrt{b^2 + (a - c)^2} \ge 0; this is the definition of atan2. Using cos⁡2θ=(1+cos⁡2θ)/2\cos^2 \theta = (1 + \cos 2\theta)/2, sin⁡2θ=(1−cos⁡2θ)/2\sin^2 \theta = (1 - \cos 2\theta)/2 and 2sin⁡θcos⁡θ=sin⁡2θ2 \sin \theta \cos \theta = \sin 2\theta:

eTΣe=acos⁡2θ+bsin⁡θcos⁡θ+csin⁡2θ=a+c2+a−c2cos⁡2θ+b2sin⁡2θ=a+c+κ2,e^{\mathsf T} \Sigma e = a \cos^2 \theta + b \sin \theta \cos \theta + c \sin^2 \theta = \tfrac{a + c}{2} + \tfrac{a - c}{2} \cos 2\theta + \tfrac{b}{2} \sin 2\theta = \tfrac{a + c + \kappa}{2},
fTΣf=a+c2−a−c2cos⁡2θ−b2sin⁡2θ=a+c−κ2,f^{\mathsf T} \Sigma f = \tfrac{a + c}{2} - \tfrac{a - c}{2} \cos 2\theta - \tfrac{b}{2} \sin 2\theta = \tfrac{a + c - \kappa}{2},
eTΣf=−a−c2sin⁡2θ+b2cos⁡2θ=−κ2cos⁡2θsin⁡2θ+κ2sin⁡2θcos⁡2θ=0.e^{\mathsf T} \Sigma f = -\tfrac{a - c}{2} \sin 2\theta + \tfrac{b}{2} \cos 2\theta = -\tfrac{\kappa}{2} \cos 2\theta \sin 2\theta + \tfrac{\kappa}{2} \sin 2\theta \cos 2\theta = 0 .

So RθTΣRθ=diag⁡(λ1,λ2)R_\theta^{\mathsf T} \Sigma R_\theta = \operatorname{diag}(\lambda_1, \lambda_2) with λ1,2=(a+c±κ)/2\lambda_{1,2} = (a + c \pm \kappa)/2: ee is an eigenvector for the larger eigenvalue, and the length and width of line L9 are λ1\sqrt{\lambda_1} and λ2\sqrt{\lambda_2}, the standard deviations of the mass along its principal axes. The eigenvalues are nonnegative because Σ\Sigma is a covariance matrix. When κ=0\kappa = 0 the mass is isotropic, every direction is principal, and θ\theta is arbitrary. □\square

Claim 3: a uniform ellipse gives its own angle and half its semi-axes

Take the continuous mass of constant density on the ellipse EE with center 0, semi-axes A≥BA \ge B and major axis along (cos⁡φ,sin⁡φ)(\cos \varphi, \sin \varphi). In the coordinates (s,t)(s, t) of its axes, E={(s/A)2+(t/B)2≤1}E = \{ (s/A)^2 + (t/B)^2 \le 1 \}. The substitution s=Aρcos⁡αs = A \rho \cos \alpha, t=Bρsin⁡αt = B \rho \sin \alpha has Jacobian ABρA B \rho, so

∫Es2=A3B∫01ρ3 dρ∫02πcos⁡2α dα=πA3B4,∫Et2=πAB34,∫Est=0,\int_E s^2 = A^3 B \int_0^1 \rho^3 \, d\rho \int_0^{2\pi} \cos^2 \alpha \, d\alpha = \frac{\pi A^3 B}{4}, \qquad \int_E t^2 = \frac{\pi A B^3}{4}, \qquad \int_E s t = 0,

and the area is πAB\pi A B. The covariance in the axis coordinates is diag⁡(A2/4,B2/4)\operatorname{diag}(A^2/4, B^2/4). By Claim 2 the computed angle is φ\varphi (modulo π\pi, when A>BA > B), and the length and width are A/2A/2 and B/2B/2. On a pixel grid the sums approximate these integrals. □\square

Claim 4: the size rule makes the window about twice the target

If the window contains a uniform target of nn pixels, each with P=255P = 255, and no other mass, then M00=255nM_{00} = 255 n and s=2M00/256=2n255/256s = 2 \sqrt{M_{00}/256} = 2 \sqrt{n} \sqrt{255/256}. For a square target of side ℓ\ell, n=ℓ2n = \ell^2 and ss is just below 2ℓ2 \ell; line L8 rounds it up to an odd integer, so the window side is at least 2ℓ255/2562 \ell \sqrt{255/256}. A window of side about 2ℓ2 \ell contains the whole target with a margin of ℓ/2\ell / 2 on each side, so a target that grows a little is still inside the next window, and the rule settles where the window is about twice the target. □\square

Claim 5: the procedure stops

The loop of lines L3 to L7 runs at most kmax⁡k_{\max} times, and each iteration reads a finite window. □\square

What is not claimed

Bradski's paper states that mean shift converges. For a disc-shaped window the step is the mean shift step of a flat kernel, which climbs a density estimate with the Epanechnikov kernel, and the argument on the mean shift tracking page applies. For the rectangular window used here that argument does not apply directly, and with real centers and a pixel grid the window can stop one pixel short of the centroid of the whole target (see the example on the page). So termination comes from the cap, not from a convergence theorem. Nothing here says that the window covers the target: the back projection is a heuristic score of how target-like each color is.

Complexity

The back projection reads every pixel once, Θ(WH)\Theta(W H) per frame, or Θ(m′)\Theta(m') for a calculation region of m′m' pixels as in Bradski's version. Each loop iteration sums over the mm pixels of the window, so the loop costs Θ(km)\Theta(k m) in the worst case and Θ(m)\Theta(m) if it stops at once. Lines L8 to L10 cost Θ(m)\Theta(m) for the second moments. Building the lookup table costs Θ(m+B)\Theta(m + B) once. The extra space is Θ(WH)\Theta(W H) for the probability image and Θ(B)\Theta(B) for the table.

Properties

  • Adaptive size and orientation. The window grows and shrinks with the target, and the tilt comes for free from the moments.
  • Cheap. A few sums per frame over a small region, with no training beyond one histogram.
  • Color only. Like mean shift tracking, it ignores where colors are inside the window, so it cannot tell two objects of the same color apart.
  • Self-growing. If the background has some target color near the target, the window grows to cover it, and the size rule feeds that growth back.
  • Local. The target must overlap the window from the previous frame.

Variants and improvements

  • Hue and saturation. Use a 2D histogram of hue and saturation, or mask out pixels with low saturation or low brightness, which have unreliable hue.
  • Kernel histograms. Weight pixels by their distance to the window center and compare histograms with the Bhattacharyya coefficient, which gives mean shift tracking.
  • Background ratio. Divide the target histogram by a background histogram, so that colors common in the scene get a low probability.
  • Prediction. Start the search where a Kalman filter predicts the target.
  • Other probability images. Any image of per-pixel target probability works, for example the output of background subtraction or of a skin color classifier.

When to use it

Use CAMShift for a target with a distinctive color in a scene without many similar colors, when the size changes over time and you want a very cheap tracker, for example a hand or a face in front of a computer. It is a common first tracker in teaching because each step is a few sums. Do not use it for gray images, for targets whose colors are common in the background, or when two targets of the same color can meet.

Pitfalls

  • A window as small as the target. The loop stops at the centroid of the part of the target it can see, so a tight window lags behind a moving target, as in frame 1 of the example. The size rule makes the window larger than the target for this reason.
  • Low saturation. Gray, white and black pixels have a random hue. Leave them out of the histogram and the back projection.
  • Runaway growth. A target-colored background next to the target pulls the window, the window grows, and then it holds even more background. Limit the size or use a background ratio.
  • The angle when the mass is round. When b2+(a−c)2b^2 + (a - c)^2 is near 0, θ\theta is noise. Report it only when ll is clearly larger than ww.
  • Image axes. With vv pointing down, a positive θ\theta is a clockwise turn on the screen; mixing this with a yy-up convention flips the sign of the angle.

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.

camshift.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/camshift/. The authors are listed in prov/WQRMAE.jsonl.

"""CAMShift (Bradski 1998): mean shift on a back-projected probability image,
with the window size and the orientation set from the image moments.

Images are lists of rows of integer values 0..255, indexed img[v][u]; the
center of pixel (u, v) is the point (u, v). The feature of a pixel is its
value divided into `bins` equal bins (Bradski uses the hue of a color pixel).
A window is (cu, cv, au, av): the pixels with |u - cu| <= au and
|v - cv| <= av, clipped to the image. Angles are measured from the u axis
toward the v axis; since v points down, a positive angle turns clockwise on
the screen.
"""

import math


def bin_of(value, bins):
    return value * bins // 256


def lookup_table(img, window, bins):
    """The histogram of the window, scaled so that the largest bin is 255."""
    hist = [0] * bins
    for u, v in window_pixels(img, window):
        hist[bin_of(img[v][u], bins)] += 1
    top = max(hist)
    if top == 0:
        raise ValueError("empty window")
    return [255.0 * x / top for x in hist]


def back_project(img, table, bins):
    """The probability image: each pixel replaced by the table value of its bin."""
    return [[table[bin_of(x, bins)] for x in row] for row in img]


def window_pixels(img, window):
    cu, cv, au, av = window
    rows, cols = len(img), len(img[0])
    for v in range(max(0, math.ceil(cv - av)), min(rows - 1, math.floor(cv + av)) + 1):
        for u in range(max(0, math.ceil(cu - au)), min(cols - 1, math.floor(cu + au)) + 1):
            yield u, v


def moments(prob, window):
    """M00, M10, M01, M20, M11, M02 of the probability image in the window."""
    m = [0.0] * 6
    for u, v in window_pixels(prob, window):
        p = prob[v][u]
        m[0] += p
        m[1] += p * u
        m[2] += p * v
        m[3] += p * u * u
        m[4] += p * u * v
        m[5] += p * v * v
    return m


def window_side(m00):
    """Bradski's size rule s = 2 sqrt(M00 / 256), rounded up to an odd
    integer, at least 3."""
    s = math.ceil(2 * math.sqrt(m00 / 256))
    if s % 2 == 0:
        s += 1
    return max(s, 3)


def shape(m):
    """Center, orientation, and the lengths along the two axes (the square
    roots of the eigenvalues of the second central moments)."""
    m00, m10, m01, m20, m11, m02 = m
    xc, yc = m10 / m00, m01 / m00
    a = m20 / m00 - xc * xc
    b = 2 * (m11 / m00 - xc * yc)
    c = m02 / m00 - yc * yc
    theta = 0.5 * math.atan2(b, a - c)
    root = math.sqrt(b * b + (a - c) ** 2)
    length = math.sqrt(max((a + c + root) / 2, 0.0))
    width = math.sqrt(max((a + c - root) / 2, 0.0))
    return (xc, yc), theta, length, width


def camshift_frame(prob, window, eps=0.5, max_iter=20, aspect=1.0):
    """One frame. Returns (new window, (center, theta, length, width)), or
    (window, None) if the window holds no probability."""
    cu, cv, au, av = window
    m = None
    for _ in range(max_iter):  # @line L3
        m = moments(prob, (cu, cv, au, av))  # @line L4
        if m[0] == 0:  # @line L5
            return window, None
        nu, nv = m[1] / m[0], m[2] / m[0]  # @line L6
        moved = math.hypot(nu - cu, nv - cv)
        cu, cv = nu, nv
        if moved < eps:  # @line L7
            break
    m = moments(prob, (cu, cv, au, av))
    if m[0] == 0:
        return window, None
    s = window_side(m[0])  # @line L8
    center, theta, length, width = shape(m)  # @line L9
    return (cu, cv, s / 2, aspect * s / 2), (center, theta, length, width)  # @line L10


def camshift(frames, window, bins=16, eps=0.5, max_iter=20, aspect=1.0):
    """Track the target that frames[0] shows in the window. Returns one
    (window, shape) pair per later frame; shape is None when the target is lost."""
    table = lookup_table(frames[0], window, bins)  # @line L1
    out = []
    for img in frames[1:]:
        prob = back_project(img, table, bins)  # @line L2
        window, info = camshift_frame(prob, window, eps, max_iter, aspect)
        out.append((window, info))
    return out  # @line L11
test_camshift.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/camshift/. The authors are listed in prov/WQRMAE.jsonl.

import math
import random

from camshift import (
    back_project,
    camshift,
    camshift_frame,
    lookup_table,
    moments,
    shape,
    window_side,
)

N = 80


def blank():
    return [[0.0] * N for _ in range(N)]


def ellipse(phi_deg, a, b, c=(40, 40)):
    phi = math.radians(phi_deg)
    prob = blank()
    for v in range(N):
        for u in range(N):
            du, dv = u - c[0], v - c[1]
            x = math.cos(phi) * du + math.sin(phi) * dv
            y = -math.sin(phi) * du + math.cos(phi) * dv
            if (x / a) ** 2 + (y / b) ** 2 <= 1:
                prob[v][u] = 255.0
    return prob


def scene(rng, c, half):
    img = [[rng.randrange(0, 120) for _ in range(N)] for _ in range(N)]
    for v in range(N):
        for u in range(N):
            if abs(u - c[0]) <= half and abs(v - c[1]) <= half:
                img[v][u] = 180 + rng.randrange(0, 60)
    return img


def test_lookup_table_and_back_projection():
    img = scene(random.Random(1), (30, 30), 5)
    table = lookup_table(img, (30, 30, 5, 5), 16)
    assert max(table) == 255
    assert all(table[b] == 0 for b in range(8))
    prob = back_project(img, table, 16)
    assert prob[30][30] > 0 and prob[5][5] == 0


def test_size_rule():
    prob = blank()
    for v in range(30, 40):
        for u in range(20, 30):
            prob[v][u] = 255.0
    m = moments(prob, (24.5, 34.5, 15, 15))
    assert m[0] == 25500
    assert window_side(m[0]) == 21
    assert window_side(0) == 3
    for m00 in [1, 100, 2560, 25600, 123456]:
        s = window_side(m00)
        assert s % 2 == 1 and s >= 2 * math.sqrt(m00 / 256)


def test_shape_of_a_uniform_square():
    prob = blank()
    for v in range(30, 40):
        for u in range(20, 30):
            prob[v][u] = 255.0
    (xc, yc), _, length, width = shape(moments(prob, (24.5, 34.5, 15, 15)))
    assert (xc, yc) == (24.5, 34.5)
    # the variance of 10 consecutive integers is 99 / 12
    assert abs(length - math.sqrt(99 / 12)) < 1e-9
    assert abs(width - math.sqrt(99 / 12)) < 1e-9


def test_orientation_and_axes_of_an_ellipse():
    for phi in [-60, -30, 0, 15, 30, 75]:
        prob = ellipse(phi, 12, 5)
        _, theta, length, width = shape(moments(prob, (40, 40, 30, 30)))
        diff = (math.degrees(theta) - phi + 90) % 180 - 90
        assert abs(diff) < 2
        assert abs(length - 6) < 0.2
        assert abs(width - 2.5) < 0.2


def test_centered_window_is_a_fixed_point():
    prob = ellipse(30, 12, 5)
    window, info = camshift_frame(prob, (40, 40, 15, 15))
    assert math.dist(window[:2], (40, 40)) < 1e-9
    assert info is not None


def test_follows_a_moving_growing_target():
    rng = random.Random(7)
    truth = [(20 + 3 * t, 25 + 2 * t, 4 + 0.5 * t) for t in range(10)]
    frames = [scene(rng, (x, y), h) for x, y, h in truth]
    out = camshift(frames, (20, 25, 4, 4))
    errors = [math.dist(window[:2], (x, y)) for (window, _), (x, y, _) in zip(out, truth[1:])]
    assert all(info is not None for _, info in out)
    # the first window is only as large as the target, so it stops short;
    # once the size rule has grown the window, the center is close
    assert errors[0] < 1.5
    assert max(errors[1:]) < 0.5
    halves = [w[2] for w, _ in out]
    assert all(b >= a for a, b in zip(halves, halves[1:]))
    assert halves[-1] > 2 * 4


def test_empty_window_is_lost():
    window, info = camshift_frame(blank(), (40, 40, 5, 5))
    assert info is None and window == (40, 40, 5, 5)

History

Gary Bradski described CAMShift in the Intel Technology Journal in 1998 as the face tracker of a perceptual user interface, in which the position and tilt of the head serve as input to the computer. The work used the mean shift procedure of Fukunaga and Hostetler and Cheng, and added the adaptive window and the moment-based orientation. The method became widely known through the OpenCV library, which Bradski led at Intel. Comaniciu, Ramesh and Meer (2000, 2003) developed the related mean shift tracking with kernel histograms and the Bhattacharyya coefficient.

References

  1. Gary R. Bradski, Computer vision face tracking for use in a perceptual user interface, Intel Technology Journal, 2nd quarter 1998, the whole paper (the hue histogram as a lookup table, the back projection, the mean shift loop on the moments, the size rule s = 2 sqrt(M00/256), and the orientation, length and width from the second moments)
  2. 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 related tracker with kernel histograms and the Bhattacharyya coefficient)
  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 with a flat kernel and its shadow kernel)

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