Algorithm Search⌘K

Algorithmcore

CONDENSATION algorithm

Also called conditional density propagation, Isard-Blake tracker.

Track contours in clutter by a particle filter over shape and motion, weighting each sample by image measurements along its contour.

Time
Θ(T N (log N + d² + M L)) worst · average · best
Space
Θ(N d) extra
Where
L = the reach of the search along a normal in pixels; M = the number of normals of the contour; N = the number of samples; T = the number of frames; d = the dimension of the shape space
Properties
randomizednot exactnot iterativenot localonline
Origin
Michael Isard, Andrew Blake, 1996

The CONDENSATION algorithm tracks the outline of an object through a video when the background is full of edges that look like the outline. Instead of one best guess, it keeps a set of NN guesses, called samples, each a full contour with its own position, shape and motion, and each with a weight. In each frame it picks samples in proportion to their weights, moves each one by a random motion model, and weights it by how well the edges of the image line up with its contour along short lines normal to the curve. The weighted set approximates the probability density of the contour given all images so far, so it can hold several hypotheses at once and keep a hypothesis alive while the object is hidden. Michael Isard and Andrew Blake published the method in 1996 and 1998. It is a particle filter, the bootstrap filter of Gordon, Salmond and Smith, with a contour state and an edge-based observation density. This page is about those vision parts, and the particle filter page covers the general filter.

In plain words

Imagine a hundred people each holding a cut-out of the object's outline over a photo of a messy room. Each person places the cut-out somewhere plausible and scores it by how many edges in the photo fall right on its border. For the next photo, the people with high scores get copied more, the low scorers drop out, and everyone nudges their copy a little in the direction the object was moving, plus some random wobble. Then everyone scores again. If two places look equally good, the crowd can split between them until the photos make the answer clear. If the object is hidden, nobody scores well, so the crowd just keeps drifting along with the motion and spreads out until the object reappears.

The problem

The input is a video and a model of the object: a shape space of contours, a dynamical model and an observation model. The output in each frame is an estimate of the contour, or the whole set of samples, which approximates the conditional density p(xt∣Zt)p(x_t \mid Z_t) of the state xtx_t given the images Zt=(z1,…,zt)Z_t = (z_1, \ldots, z_t). This is a solution to the visual object tracking problem in which the state is a curve.

Shape space. A contour is a parametric curve, usually a B-spline r(s)=(B(s)TQx,B(s)TQy)r(s) = (B(s)^{\mathsf T} Q^x, B(s)^{\mathsf T} Q^y), 0≤s≤L0 \le s \le L. Its control points are restricted to a low-dimensional space, (Qx,Qy)=WX+Qˉ(Q^x, Q^y) = W X + \bar Q, where XX has dimension dd, for example the 6 parameters of planar affine changes of a template Qˉ\bar Q.

Dynamics. A second-order autoregressive model in discrete time,

xt−xˉ=A(xt−1−xˉ)+Bwt,wt∼N(0,I),x_t - \bar x = A (x_{t-1} - \bar x) + B w_t, \qquad w_t \sim N(0, I),

with the stacked state xt=(Xt−1,Xt)x_t = (X_{t-1}, X_t). Isard and Blake learn AA, xˉ\bar x and BB from training sequences by maximum likelihood.

Observations. Along MM normals of the hypothesized contour, an edge detector finds features at signed offsets ν\nu from the curve. On one normal, if the object is not seen with probability qq and the clutter is a Poisson process with density λ\lambda, the observation density is

p(z∣x)∝1+12π σα∑mexp⁡(−νm22σ2),α=qλ,p(z \mid x) \propto 1 + \frac{1}{\sqrt{2\pi}\, \sigma \alpha} \sum_m \exp\Big( -\frac{\nu_m^2}{2 \sigma^2} \Big), \qquad \alpha = q \lambda,

where σ\sigma is the standard deviation of a true edge about the curve. The density of the whole contour is the product over the normals. The paper also uses a cheaper form with the nearest feature only,

p(z∣x)∝exp⁡(−∑m=1M12rMmin⁡(ν1(sm)2,μ2)),p(z \mid x) \propto \exp\Big( -\sum_{m=1}^M \frac{1}{2 r M} \min(\nu_1(s_m)^2, \mu^2) \Big),

where ν1(sm)\nu_1(s_m) is the offset of the nearest feature on normal mm and μ\mu caps the cost of a missing or far feature.

The algorithm

  1. STEP(the old set {(s_j, π_j, c_j)} with c_0 = 0 and c_j = c_{j-1} + π_j, the image z_t)
  2. 1for n ← 1 to N do r ← a uniform random number in [0, c_N]
  3. 2j ← the smallest index with c_j ≥ r, by binary subdivision; s' ← s_j ▷ select
  4. 3s_n ← A s' + B w with w a vector of standard normal numbers ▷ predict
  5. 4π_n ← p(z_t | x_t = s_n), the product of the densities of the normals ▷ measure
  6. 5divide every π_n by their sum
  7. 6c_0 ← 0; c_n ← c_{n-1} + π_n for n = 1, ..., N
  8. 7return the estimate Σ_n π_n s_n and the new set {(s_n, π_n, c_n)}

The first set is drawn from a prior density, for example a Gaussian around a hand-placed contour, or the steady state of the dynamics run with no measurements. Lines L1 and L2 are the selection, with replacement, so a heavy sample can be chosen many times and a light one not at all. In line L3 the copies of one sample first move together (the deterministic part As′A s') and then split (the random part BwB w). Line L7 can report any moment of the set, not only the mean.

Example

One normal by hand. Take σ=1\sigma = 1 pixel and α=0.05\alpha = 0.05, so the constant in front of the sum is 1/(2π⋅0.05)≈7.981 / (\sqrt{2\pi} \cdot 0.05) \approx 7.98. A normal with no feature has density 1. One feature exactly on the curve gives 1+7.98=8.981 + 7.98 = 8.98. One feature 1 pixel away gives 1+7.98 e−1/2≈5.841 + 7.98\, e^{-1/2} \approx 5.84, and 2 pixels away 1+7.98 e−2≈2.081 + 7.98\, e^{-2} \approx 2.08. A feature far away adds almost nothing, so the density does not punish a missing edge more than the constant level 1: this is what lets a hypothesis survive an occlusion.

Selection by hand. With weights (0.1,0.2,0.3,0.4)(0.1, 0.2, 0.3, 0.4) the cumulative weights are (0.1,0.3,0.6,1.0)(0.1, 0.3, 0.6, 1.0). The random number r=0.45r = 0.45 selects index 3, the first with cj≥0.45c_j \ge 0.45. Each index is selected for an interval of rr of length equal to its weight. In 20,000 draws the test sees each frequency within 0.012 of its weight.

Tracking a circle in clutter. The implementation uses a circle of radius 8 as the contour, so the shape space is the translations (d=2d = 2, state (Xt−1,Xt)(X_{t-1}, X_t), AA with damping 1, noise 1 pixel), M=16M = 16 normals probed from −6-6 to 66 pixels, σ=1\sigma = 1, α=0.05\alpha = 0.05 and N=300N = 300 samples. These are this page's choices. The 60×6060 \times 60 edge maps have 4% of the pixels set at random as clutter, and the circle moves by (2,1.5)(2, 1.5) pixels per frame. In frames 5 and 6 the circle is missing. The errors of the weighted mean over frames 1 to 11 are 0.43, 0.22, 0.08, 0.07, then 0.95 and 3.14 while the circle is hidden, then 2.05 when it comes back, then 0.09, 0.38, 0.18 and 0.13 pixel. During the occlusion every sample has density near the clutter level, so the set keeps moving with the velocities of its samples and spreads; when the circle returns, the samples near it get almost all the weight.

A sharp density. In a scene with two circles centered at (20,30)(20, 30) and (42,30)(42, 30) and no clutter, the log-likelihood is 40.29 at both centers, 33.40 one pixel off, and 12.18 halfway between. A one-pixel error costs a factor near e6.9≈1000e^{6.9} \approx 1000 in weight. Started between two such circles 20 pixels apart, with 400 samples, the set kept both modes only in some runs. In others one mode got all the weight at the first step. With a density this sharp, few samples carry the weight, and the selection can drop a mode by chance. A larger σ\sigma, more samples or a smoother density keep both modes longer.

Correctness

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

  • Theorem: selection. With rr uniform on [0,cN][0, c_N], the smallest jj with cj≥rc_j \ge r is index kk with probability πk/cN\pi_k / c_N, and bisection finds it in O(log⁡N)O(\log N) comparisons.
  • Theorem: one step is factored sampling. Given the old set, the new samples are independent draws from the predicted prior q(x)=∑jπjp(x∣sj)q(x) = \sum_j \pi_j p(x \mid s_j), and for every bounded gg the weighted mean ∑nπng(sn)\sum_n \pi_n g(s_n) converges almost surely, as N→∞N \to \infty, to the posterior mean of gg under the prior qq and the observation density.
  • Theorem: the dynamics. The update of line L3 is the second-order autoregressive model. With no noise and damping 1 it keeps a constant velocity.
  • Theorem: the observation density. The density of one normal follows from the clutter model above, is at least 1 and bounded, and equals 1 when there is no feature. So a frame with no features leaves all weights equal.

The behavior over many frames for a fixed NN, and whether the tracked contour is the object, are not proved. They depend on the models and on the number of samples, and the experiments of the paper are evidence, not proof.

Proof: Why the selection by binary subdivision draws each sample with its weight, why one step of CONDENSATION is factored sampling of the posterior, and what the contour observation model givesfull

Notation as on the page. The sample set at time t−1t - 1 is {(sj,πj,cj)}j=1N\{(s_j, \pi_j, c_j)\}_{j=1}^N with weights πj≥0\pi_j \ge 0 and cumulative weights c0=0c_0 = 0, cj=cj−1+πjc_j = c_{j-1} + \pi_j. The claims say what one step computes. Whether the tracked contour follows the object depends on the dynamical model and the observation model, which are assumptions.

Claim 1: selection draws index j with probability proportional to its weight, in O(log N)

Let rr be uniform on [0,cN][0, c_N] with cN>0c_N > 0, and let jj be the smallest index with cj≥rc_j \ge r (lines L1 and L2). Then Pr⁡(j=k)=πk/cN\Pr(j = k) = \pi_k / c_N for every kk, and binary subdivision finds jj with at most ⌈log⁡2(N+1)⌉\lceil \log_2 (N + 1) \rceil comparisons.

Proof. The cumulative weights are non-decreasing, so j=kj = k holds exactly when ck−1<r≤ckc_{k-1} < r \le c_k. This is an interval of length ck−ck−1=πkc_k - c_{k-1} = \pi_k inside [0,cN][0, c_N], so it has probability πk/cN\pi_k / c_N (the single point r=0r = 0, which selects the first index with cj≥0c_j \ge 0, has probability 0). Because the sequence is sorted, the set of indices with cj≥rc_j \ge r is a suffix {j,…,N}\{j, \ldots, N\}, and bisection on this monotone predicate halves the candidate range at each comparison. □\square

A sample with weight 0 is never chosen, except for the event r=0r = 0 of probability 0. The implementation clamps the index to NN, which covers rounding when rr equals cNc_N. The test checks the definition on 500 random values and the frequencies on 20,000 draws.

Claim 2: one step is factored sampling of the posterior

Assume the old set represents the density p(xt−1∣Zt−1)p(x_{t-1} \mid Z_{t-1}) by the weighted empirical measure ∑jπjδsj\sum_j \pi_j \delta_{s_j} with ∑jπj=1\sum_j \pi_j = 1. Let

q(xt)=∑jπj p(xt∣xt−1=sj)q(x_t) = \sum_j \pi_j\, p(x_t \mid x_{t-1} = s_j)

be the predicted prior. Then, given the old set:

(a) after lines L1 to L3, the new samples s1,…,sNs_1, \ldots, s_N are independent with density qq;

(b) after lines L4 to L6, for every bounded function gg,

∑nπn g(sn)=1N∑ng(sn) p(zt∣sn)1N∑np(zt∣sn)⟶∫g(x) p(zt∣x) q(x) dx∫p(zt∣x) q(x) dx\sum_n \pi_n\, g(s_n) = \frac{\frac1N \sum_n g(s_n)\, p(z_t \mid s_n)}{\frac1N \sum_n p(z_t \mid s_n)} \longrightarrow \frac{\int g(x)\, p(z_t \mid x)\, q(x)\, dx}{\int p(z_t \mid x)\, q(x)\, dx}

almost surely as N→∞N \to \infty, provided ∫p(zt∣x)q(x)dx>0\int p(z_t \mid x) q(x) dx > 0. The right side is the expectation of gg under the posterior that Bayes' rule gives from the prior qq and the observation density.

Proof. (a) Each new sample uses its own uniform rr and its own noise ww, independent of the others. By Claim 1 its parent is sks_k with probability πk\pi_k, and given the parent it has density p(xt∣sk)p(x_t \mid s_k), so its density is the mixture qq. (b) The weights of line L4 are p(zt∣sn)p(z_t \mid s_n), and line L5 divides them by their sum, which gives the first equality. The numerator and the denominator are means of NN independent copies of g(X)p(zt∣X)g(X) p(z_t \mid X) and p(zt∣X)p(z_t \mid X) with X∼qX \sim q. These have finite means because gg is bounded and p(zt∣x)p(z_t \mid x) is bounded (Claim 4 shows it for the model of the page). By the strong law of large numbers each mean converges almost surely to its expectation, and the quotient converges because the limit of the denominator is positive. □\square

This is the factored sampling of Section 3 of Isard and Blake, applied once per frame. Line L7, the weighted mean, is (b) with g(x)=xg(x) = x on the bounded image region. The claim is conditional on the old set. That the error does not grow over many frames is a result about particle filters in general, which needs conditions on the model that are not proved here; the particle filter page treats it.

Claim 3: the prediction is the second-order autoregressive model

With the state (xt−1,xt)(x_{t-1}, x_t) and the damping aa, line L3 computes

xt+1=xt+a(xt−xt−1)+Bwt,wt∼N(0,I),x_{t+1} = x_t + a (x_t - x_{t-1}) + B w_t, \qquad w_t \sim N(0, I),

which is Xt+1−Xˉ=A(Xt−Xˉ)+B′wtX_{t+1} - \bar X = A (X_t - \bar X) + B' w_t for the stacked state Xt=(xt−1,xt)X_t = (x_{t-1}, x_t) with Xˉ=0\bar X = 0 and

A=(0I−aI(1+a)I),B′=(0B).A = \begin{pmatrix} 0 & I \\ -a I & (1 + a) I \end{pmatrix}, \qquad B' = \begin{pmatrix} 0 \\ B \end{pmatrix}.

With B=0B = 0 and a=1a = 1, a sample that moves by vv between xt−1x_{t-1} and xtx_t moves by vv again: the model holds a constant velocity. With ∣a∣<1|a| < 1 and B=0B = 0 the velocity is multiplied by aa at each step and goes to 0.

Proof. The second block row of AXtA X_t is −axt−1+(1+a)xt=xt+a(xt−xt−1)-a x_{t-1} + (1 + a) x_t = x_t + a (x_t - x_{t-1}), and the first block row copies xtx_t into the new first slot. The velocity vt+1=xt+1−xt=a(xt−xt−1)=avtv_{t+1} = x_{t+1} - x_t = a (x_t - x_{t-1}) = a v_t when B=0B = 0. □\square

This is the form of equations (10) and (11) of the paper, with AA fixed by hand instead of learned. The test checks the constant velocity case with zero noise.

Claim 4: the observation density of one normal, and what it does with no features

Along one normal, let the features be at signed offsets ν1,…,νK\nu_1, \ldots, \nu_K from the hypothesized contour point. The density used for that normal is

p1(ν1,…,νK)∝1+12π σα∑k=1Kexp⁡(−νk22σ2),p_1(\nu_1, \ldots, \nu_K) \propto 1 + \frac{1}{\sqrt{2\pi}\, \sigma \alpha} \sum_{k=1}^K \exp\Big( -\frac{\nu_k^2}{2 \sigma^2} \Big),

and the density of a contour is the product over its MM normals (line L4). Then:

(a) The density is at least 1 and at most 1+K/(2πσα)1 + K / (\sqrt{2\pi} \sigma \alpha) per normal, so it is bounded and positive.

(b) If no normal of any hypothesis has a feature, every sample has weight 1/N1/N after line L5, and the step only moves the samples by the dynamics.

(c) It comes from this model: with probability qq the object is not seen and all features on the normal are clutter; otherwise exactly one feature is the true edge, displaced by a normal error with standard deviation σ\sigma, and each feature is the true one with the same probability pp. The clutter is a Poisson process with density λ\lambda along the normal.

Proof. (a) Each term of the sum is in (0,1](0, 1]. (b) With K=0K = 0 on every normal, the density is 1 for every hypothesis, so all weights are equal before and after normalization. (c) For a Poisson process with density λ\lambda on a window of length WW, the density of KK given points is e−λWλKe^{-\lambda W} \lambda^K. If the object is not seen, the KK features are clutter, which gives q e−λWλKq\, e^{-\lambda W} \lambda^K. If feature kk is the true one, the other K−1K - 1 are clutter, which gives p e−λWλK−112πσe−νk2/(2σ2)p\, e^{-\lambda W} \lambda^{K-1} \frac{1}{\sqrt{2\pi} \sigma} e^{-\nu_k^2 / (2 \sigma^2)}. Sum over the K+1K + 1 cases and divide by q e−λWλKq\, e^{-\lambda W} \lambda^K, which does not depend on the hypothesis:

1+pqλ⋅12πσ∑ke−νk2/(2σ2).1 + \frac{p}{q \lambda} \cdot \frac{1}{\sqrt{2\pi} \sigma} \sum_k e^{-\nu_k^2 / (2 \sigma^2)}.

This is the stated form with one constant in front of the sum. Isard and Blake write it as 1/(2πσα)1 / (\sqrt{2\pi} \sigma \alpha) with α=qλ\alpha = q \lambda, equation (13). □\square

Part (b) is the "tunnelling" of the paper: when the object is hidden, the samples keep moving with the dynamics and spread, so they can find the object when it appears again. Equation (16) of the paper replaces the sum by the nearest feature only, exp⁡(−∑mf(ν1(m);μ)/(2rM))\exp(-\sum_m f(\nu_1(m); \mu) / (2 r M)) with f(ν;μ)=min⁡(ν2,μ2)f(\nu; \mu) = \min(\nu^2, \mu^2). Its logarithm is also bounded, between −μ2/(2r)-\mu^2 / (2 r) and 0, so Claim 2 applies to it too.

Cost

Line L2 costs O(log⁡N)O(\log N) by Claim 1, line L3 costs O(d2)O(d^2) for a state of dimension dd, and line L4 costs O(ML)O(M L) for MM normals that are each probed at 2L+12 L + 1 points. Lines L5 to L7 cost O(N)O(N) in all. So a step costs Θ(N(log⁡N+d2+ML))\Theta(N (\log N + d^2 + M L)) and holds Θ(Nd)\Theta(N d) numbers.

What is not claimed

The observation model is an assumption. Its sharpness decides how many samples survive a step: in the example on the page, moving a hypothesis by one pixel lowers its log-likelihood by about 7, so its weight falls by a factor near 1000. With so sharp a density, a sample set can lose one of two equally good modes within a few steps by chance, and Claim 2 does not prevent this for a fixed NN. The convergence in Claim 2 is for N→∞N \to \infty and says nothing about the error for a given NN.

Complexity

Selection costs O(log⁡N)O(\log N) per sample by bisection, prediction O(d2)O(d^2) for the matrix product, and measurement O(ML)O(M L) for MM normals probed at 2L+12L + 1 points. Normalization and the cumulative weights cost O(N)O(N). A frame costs Θ(N(log⁡N+d2+ML))\Theta(N (\log N + d^2 + M L)), and TT frames cost TT times that. The extra space is Θ(Nd)\Theta(N d) for the samples and their weights. In practice the measurement dominates. Isard and Blake used N=1000N = 1000 in their first experiment. The cost of selection can be cut to O(1)O(1) per sample with systematic resampling, which draws one random number for all samples and walks through the cumulative weights once.

Properties

  • Multimodal. The set can represent several hypotheses at once, which a Kalman filter cannot.
  • Robust to clutter. The observation density is never 0, so a few missing or false edges do not kill a correct hypothesis.
  • Survives short occlusions. With no features, the weights stay equal and the samples follow the dynamics.
  • Randomized. Two runs with different seeds give different sets and slightly different estimates.
  • Fixed cost. The number of samples is fixed, so the time per frame is bounded and does not depend on the image content.
  • No covariance algebra. Unlike the Kalman filter, there is no Riccati equation, only sampling and evaluation of the density.

Variants and improvements

  • ICONDENSATION. Isard and Blake later combined the contour samples with samples drawn near color blobs found by a low-level detector, by importance sampling, so the tracker can recover from a lost track.
  • Mixed discrete and continuous states. Add a discrete label, such as the kind of motion, to each sample and switch it by a Markov chain.
  • Partitioned and annealed sampling. For articulated bodies with many dimensions, sample one part of the state at a time, or anneal the observation density over several layers.
  • Color-based particle filters. Replace the edge density by the similarity of color histograms, as in the kernel used by mean-shift tracking.
  • Better proposals. Draw the predicted samples from a density that already uses the new image, and correct by importance weights.
  • Systematic or residual resampling. Lower the variance of the selection step and its cost.

When to use it

Use CONDENSATION, or a particle filter with a contour state, when the background is cluttered, the motion is fast or erratic, and the density of the state can have several peaks. Examples are a hand or a head in front of a busy background, or a leaf among leaves. It needs a shape model and a dynamical model, ideally learned from training data. If the density is close to a single Gaussian, a Kalman filter or an extended Kalman filter is cheaper and has no sampling noise. For a target described by its appearance instead of its outline, use an appearance tracker such as mean-shift tracking or a correlation filter.

Pitfalls

  • Too few samples for the dimension. The number of samples needed grows quickly with the dimension of the shape space. A 12-dimensional state with a few hundred samples leaves large parts of the density empty.
  • A density that is too sharp. With a small σ\sigma, one sample takes almost all the weight, the selection copies it, and the set collapses to one point. The example shows a factor of about 1000 per pixel.
  • Underflow. The product over many normals can underflow. Add logarithms and subtract the largest before taking the exponential, as the implementation does.
  • Weights of zero sum. If the density can be 0, a frame with no good hypothesis makes all weights 0. The constant 1 of the clutter model avoids this.
  • Dynamics that do not match. If the true motion is faster than the noise of the model allows, no sample lands near the object, and the tracker loses it with no warning.
  • Reporting only the mean. With two modes, the mean lies between them, on no object. Report the largest mode as well when the density can be multimodal.

Implementations

The Python code tracks a circle of fixed radius with the state of the second-order model, on synthetic edge maps. It implements the density of one normal (equation 13 of the paper) and the nearest-feature form (equation 16), the selection by binary subdivision with the module bisect, the prediction and the normalization in log space. The tests check the selection against its definition and its frequencies, the densities by hand, the constant density with no features, the constant velocity of the dynamics, the two equal peaks of a two-circle scene, and tracking through clutter and a two-frame occlusion.

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.

condensation_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/condensation-algorithm/. The authors are listed in prov/SEFHQG.jsonl.
"""CONDENSATION: a sample set of contours, propagated by select, predict and measure.

The contour is a circle of fixed radius, so the shape space is the translations
of the plane. A state is (previous center, current center), the state of a
second-order autoregressive model. Measurements are edge pixels found along the
normals of the contour. Images are edge maps, edge[v][u] is True on an edge,
and pixel (u, v) has its center at (u, v).
"""

import bisect
import math
import random


def contour(center, radius, m):
    """m points on the circle and their unit normals, the radial directions."""
    cx, cy = center
    out = []
    for k in range(m):
        a = 2 * math.pi * k / m
        nx, ny = math.cos(a), math.sin(a)
        out.append(((cx + radius * nx, cy + radius * ny), (nx, ny)))
    return out


def features_on_normal(edge, point, normal, reach):
    """Signed offsets nu in [-reach, reach] (step 1) where the normal meets an edge pixel."""
    h, w = len(edge), len(edge[0])
    (px, py), (nx, ny) = point, normal
    out = []
    for t in range(-reach, reach + 1):
        u, v = round(px + t * nx), round(py + t * ny)
        if 0 <= u < w and 0 <= v < h and edge[v][u]:
            out.append(t)
    return out


def clutter_density(nus, sigma, alpha):
    """The density of one normal, up to a constant: 1 + sum exp(-nu^2 / 2 sigma^2) / (sqrt(2 pi) sigma alpha)."""
    c = 1.0 / (math.sqrt(2 * math.pi) * sigma * alpha)
    return 1.0 + c * sum(math.exp(-nu * nu / (2 * sigma * sigma)) for nu in nus)


def nearest_feature_log_likelihood(nearest, r, mu):
    """log of exp(-sum over normals of min(nu_1^2, mu^2) / (2 r M)); None means no feature on that normal."""
    m = len(nearest)
    return -sum(mu * mu if nu is None else min(nu * nu, mu * mu) for nu in nearest) / (2 * r * m)


def log_likelihood(edge, center, radius, m, reach, sigma, alpha):
    """log p(z | x): the product of the clutter densities of the m normals."""
    return sum(math.log(clutter_density(features_on_normal(edge, p, n, reach), sigma, alpha))
               for p, n in contour(center, radius, m))


def select(cumulative, r):
    """The smallest j with cumulative[j] >= r, by binary subdivision."""
    j = bisect.bisect_left(cumulative, r)
    return min(j, len(cumulative) - 1)


class Condensation:
    def __init__(self, center, radius, n=300, spread=3.0, damping=1.0, noise=1.0,
                 m=16, reach=6, sigma=1.0, alpha=0.05, seed=0):
        self.rng = random.Random(seed)
        self.radius, self.m, self.reach = radius, m, reach
        self.sigma, self.alpha = sigma, alpha
        self.damping, self.noise = damping, noise
        g = self.rng.gauss
        self.samples = []
        for _ in range(n):  # the prior: a Gaussian around the first center, zero mean velocity
            cur = (center[0] + g(0, spread), center[1] + g(0, spread))
            prev = (cur[0] + g(0, noise), cur[1] + g(0, noise))
            self.samples.append((prev, cur))
        self.weights = [1.0 / n] * n
        self.cumulative = [(k + 1) / n for k in range(n)]

    def step(self, edge):
        n = len(self.samples)
        g = self.rng.gauss
        new = []
        for _ in range(n):
            r = self.rng.random() * self.cumulative[-1]  # @line L1
            prev, cur = self.samples[select(self.cumulative, r)]  # @line L2
            vx, vy = cur[0] - prev[0], cur[1] - prev[1]  # @line L3
            nxt = (cur[0] + self.damping * vx + self.noise * g(0, 1),
                   cur[1] + self.damping * vy + self.noise * g(0, 1))
            new.append((cur, nxt))
        logs = [log_likelihood(edge, s[1], self.radius, self.m, self.reach, self.sigma, self.alpha)
                for s in new]  # @line L4
        top = max(logs)
        w = [math.exp(t - top) for t in logs]
        total = sum(w)
        self.weights = [t / total for t in w]  # @line L5
        c, acc = [], 0.0
        for t in self.weights:  # @line L6
            acc += t
            c.append(acc)
        self.samples, self.cumulative = new, c
        return self.mean()  # @line L7

    def mean(self):
        x = sum(wt * s[1][0] for wt, s in zip(self.weights, self.samples))
        y = sum(wt * s[1][1] for wt, s in zip(self.weights, self.samples))
        return (x, y)


def draw_circle(edge, center, radius):
    """Mark the pixel nearest to each of about 8 pi radius points of the circle."""
    h, w = len(edge), len(edge[0])
    k = max(8, int(8 * math.pi * radius))
    for i in range(k):
        a = 2 * math.pi * i / k
        u, v = round(center[0] + radius * math.cos(a)), round(center[1] + radius * math.sin(a))
        if 0 <= u < w and 0 <= v < h:
            edge[v][u] = True
test_condensation_algorithm.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/condensation-algorithm/. The authors are listed in prov/SEFHQG.jsonl.

import math
import random

from condensation_algorithm import (
    Condensation,
    clutter_density,
    contour,
    draw_circle,
    features_on_normal,
    log_likelihood,
    nearest_feature_log_likelihood,
    select,
)

N = 60


def edge_map(*circles, clutter=()):
    e = [[False] * N for _ in range(N)]
    for u, v in clutter:
        e[v][u] = True
    for c in circles:
        draw_circle(e, c, 8)
    return e


def test_select_is_the_smallest_index_reaching_r():
    rng = random.Random(1)
    w = [rng.random() for _ in range(50)]
    c, acc = [], 0.0
    for t in w:
        acc += t
        c.append(acc)
    for _ in range(500):
        r = rng.random() * c[-1]
        j = select(c, r)
        assert c[j] >= r and (j == 0 or c[j - 1] < r)
    assert select(c, c[-1]) == 49 and select(c, 0.0) == 0


def test_selection_frequencies_follow_the_weights():
    rng = random.Random(2)
    c = [0.1, 0.3, 0.6, 1.0]
    counts = [0, 0, 0, 0]
    for _ in range(20000):
        counts[select(c, rng.random())] += 1
    for k, p in enumerate((0.1, 0.2, 0.3, 0.4)):
        assert abs(counts[k] / 20000 - p) < 0.012


def test_clutter_density_and_nearest_feature():
    c = 1 / (math.sqrt(2 * math.pi) * 1.0 * 0.05)
    assert clutter_density([], 1.0, 0.05) == 1.0
    assert abs(clutter_density([0], 1.0, 0.05) - (1 + c)) < 1e-12
    assert abs(clutter_density([0, 2], 1.0, 0.05) - (1 + c + c * math.exp(-2))) < 1e-12
    assert abs(nearest_feature_log_likelihood([0, 1, -3, None], 2.0, 2.0)
                - (-(0 + 1 + 4 + 4) / (2 * 2.0 * 4))) < 1e-12


def test_normals_find_the_circle():
    e = edge_map((30, 30))
    for p, n in contour((30, 30), 8, 16):
        assert 0 in features_on_normal(e, p, n, 3)
    for p, n in contour((30, 30), 5, 16):  # a smaller circle sees the edge 3 pixels out
        got = features_on_normal(e, p, n, 4)  # the drawn edge can be two pixels thick
        assert 3 in got and set(got) <= {2, 3, 4}


def test_no_features_give_likelihood_one_and_equal_weights():
    empty = edge_map()
    assert log_likelihood(empty, (30, 30), 8, 16, 6, 1.0, 0.05) == 0.0
    tracker = Condensation((30, 30), 8, n=50, seed=3)
    tracker.step(empty)
    assert max(tracker.weights) - min(tracker.weights) < 1e-15


def test_prediction_is_the_second_order_model():
    tracker = Condensation((30, 30), 8, n=20, noise=0.0, seed=4)
    tracker.samples = [((10.0, 10.0), (12.0, 11.0))] * 20
    assert math.dist(tracker.step(edge_map()), (14.0, 12.0)) < 1e-9
    assert math.dist(tracker.step(edge_map()), (16.0, 13.0)) < 1e-9


def test_likelihood_has_one_peak_per_circle():
    e = edge_map((20, 30), (42, 30))
    left = log_likelihood(e, (20, 30), 8, 16, 6, 1.0, 0.05)
    right = log_likelihood(e, (42, 30), 8, 16, 6, 1.0, 0.05)
    mid = log_likelihood(e, (31, 30), 8, 16, 6, 1.0, 0.05)
    assert abs(left - right) < 1e-9
    assert left > mid + 10


def test_tracks_through_clutter_and_a_short_occlusion():
    rng = random.Random(3)
    clutter = [(rng.randrange(N), rng.randrange(N)) for _ in range(144)]  # 4% of the pixels
    path = [(16 + 2 * t, 18 + 1.5 * t) for t in range(12)]
    hidden = {5, 6}
    tracker = Condensation(path[0], 8, seed=0)
    for k in range(1, len(path)):
        e = edge_map(clutter=clutter) if k in hidden else edge_map(path[k], clutter=clutter)
        est = tracker.step(e)
        err = math.dist(est, path[k])
        if k in hidden:
            assert err < 4.0
        elif k == 7:
            assert err < 2.5
        else:
            assert err < 1.0

History

Kalman filter trackers for curves, developed by Blake and colleagues in the early 1990s, failed in clutter because a single Gaussian cannot hold two explanations of the edges. In 1996 Michael Isard and Andrew Blake presented CONDENSATION at ECCV, and in 1998 they published the full method in the International Journal of Computer Vision. It applies factored sampling, a method of Grenander and colleagues for single images, to each frame of a sequence. The same scheme was developed at the same time for target tracking and statistics: the bootstrap filter of Gordon, Salmond and Smith (1993) and the Monte Carlo filter of Kitagawa (1996). Isard and Blake extended it to ICONDENSATION in 1998. The method made particle filters common in computer vision, for tracking people, hands and faces, and for robot localization.

References

  1. Michael Isard and Andrew Blake, CONDENSATION, conditional density propagation for visual tracking, International Journal of Computer Vision 29(1), 1998, 5 to 28, Sections 3 to 6 (factored sampling, the algorithm in Figure 6 on page 12, the dynamics of equations 10 to 12, the observation densities of equations 13 to 16 on pages 13 to 15) and Section 7.1 (1000 samples on a cluttered sequence)
  2. Michael Isard and Andrew Blake, Visual tracking by stochastic propagation of conditional density, European Conference on Computer Vision (ECCV), Cambridge, 1996, 343 to 356, the whole paper (the first version of the method)
  3. Neil J. Gordon, David J. Salmond and Adrian F. M. Smith, Novel approach to nonlinear/non-Gaussian Bayesian state estimation, IEE Proceedings F 140(2), 1993, 107 to 113, the whole paper (the bootstrap filter, the same sampling scheme developed for target tracking)

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