Algorithm Search⌘K

Algorithmcore

Adaptive Gaussian mixture background model

Also called Stauffer-Grimson model, MOG background subtraction.

Model each pixel by a few Gaussians updated online, call the heavy narrow ones background, and mark pixels that fit none of them as foreground.

Time
O(N P K log K) worst
Space
O(P K) extra
Where
K = the number of Gaussians per pixel; N = the number of frames; P = the number of pixels in a frame
Properties
deterministicnot exactnot iterativeonline
Origin
Chris Stauffer, W. Eric L. Grimson, 1999

The adaptive Gaussian mixture background model of Stauffer and Grimson is an online method for background subtraction. Each pixel has its own mixture of KK Gaussians over its values, with KK from 3 to 5. Each new value updates the mixture with a fixed learning rate. The components with large weight and small variance are taken as the background, because the background is what the pixel shows most of the time and with little change. A value that fits none of them is foreground. The mixture lets one pixel have several background values, such as a leaf and the sky behind it, or a flickering screen. ViBe solves the same problem without a parametric model: it keeps raw past values per pixel and replaces them at random. The page background subtraction states the problem and compares the methods.

In plain words

A fixed camera looks at a scene. Each pixel keeps a short list of the values it usually shows, with a weight for how often it shows each one and a spread for how much that value varies. When a new picture comes, each pixel checks if its value is close to one of the values on its list. If it is, that entry gets more weight and moves a little toward the new value. If not, the pixel replaces its weakest entry with the new value. The entries that are frequent and steady are the background. A pixel is marked as moving when its value fits no background entry. A car that parks for long becomes background after a while.

The problem

The input is a sequence of gray images of the same size from a fixed camera; a color version uses vectors with a diagonal covariance. The output for each frame is a binary mask, 1 for foreground and 0 for background. The method is online: the mask of frame tt depends only on frames 11 to tt.

The model of one pixel. The pixel holds KK components (wk,μk,σk2)(w_k, \mu_k, \sigma_k^2) with wk≥0w_k \ge 0 and ∑kwk=1\sum_k w_k = 1. The paper models the recent history of the pixel as the mixture density ∑kwk η(x∣μk,σk2)\sum_k w_k \, \eta(x \mid \mu_k, \sigma_k^2), where η\eta is the Gaussian density. The parameters are the learning rate α\alpha, the background fraction TT, and the variance v0v_0 and weight w0w_0 of a new component.

The algorithm

  1. SG-PIXEL(x, the components (w_k, μ_k, σ_k²), α, T, v_0, w_0)
  2. 1order the components by w_k / σ_k, largest first; m ← the first k with |x - μ_k| ≤ 2.5 σ_k, or none
  3. 2if there is none: replace the last component by (w_0, x, v_0), scale the other weights to sum 1 - w_0, and return foreground
  4. 3for each k: w_k ← (1 - α) w_k + α [k = m]
  5. 4ρ ← α η(x | μ_m, σ_m²); μ_m ← (1 - ρ) μ_m + ρ x; σ_m² ← (1 - ρ) σ_m² + ρ (x - μ_m)²
  6. 5order the components again by w_k / σ_k; B ← the smallest b with w_(1) + ... + w_(b) > T
  7. 6return background if m is one of the first B components, else foreground

The paper replaces the least probable component when nothing matches, with the current value as its mean, a high variance and a low weight, and then renormalizes the weights. Line L2 renormalizes so that the new weight is exactly w0w_0, which makes the bounds below exact. The variance update of line L4 uses the new mean. Line L4 uses the factor ρ=αη\rho = \alpha \eta of the paper; many implementations use ρ=α/wm\rho = \alpha / w_m instead, which learns faster (see the pitfalls). The implementation also keeps σ2≥4\sigma^2 \ge 4, so that the density stays finite for a constant pixel. Components that never received a value have weight 0 and match nothing.

The defaults of the implementation are K=3K = 3, α=0.01\alpha = 0.01, T=0.7T = 0.7, v0=900v_0 = 900 (a standard deviation of 30) and w0=0.05w_0 = 0.05. They are tuned values for 8-bit gray images, not values from the paper.

Example

One pixel. The pixel has three components, written as (w,μ,σ)(w, \mu, \sigma): (0.6,50,4)(0.6, 50, 4), (0.3,120,10)(0.3, 120, 10) and (0.1,200,30)(0.1, 200, 30). The ratios w/σw / \sigma are 0.150.15, 0.030.03 and 0.00330.0033, so that is also the order. With T=0.7T = 0.7, the first weight 0.60.6 is not above TT and the first two give 0.90.9, so B=2B = 2: the components around 50 and 120 are the background. Let α=0.01\alpha = 0.01.

  • x=126x = 126. It is not within 2.5×4=102.5 \times 4 = 10 of 50, but it is within 2525 of 120, so it matches the second component. The weights become (0.594,0.307,0.099)(0.594, 0.307, 0.099). The factor is ρ=0.01×e−0.18/2π⋅100≈0.000333\rho = 0.01 \times e^{-0.18} / \sqrt{2 \pi \cdot 100} \approx 0.000333, so the mean moves from 120 to 120+6ρ≈120.002120 + 6\rho \approx 120.002. The match is among the first BB, so the pixel is background.
  • x=200x = 200. It matches the third component, and the weights become (0.594,0.297,0.109)(0.594, 0.297, 0.109). The order stays the same, the first two weights still sum to 0.891>0.70.891 > 0.7, and BB stays 2. The third component is not background, so the pixel is foreground.
  • x=90x = 90. It is 40 from 50, 30 from 120 and 110 from 200, outside 1010, 2525 and 7575, so nothing matches. The last component becomes (0.05,90,30)(0.05, 90, 30), and the other weights are scaled to 0.6330.633 and 0.3170.317. The pixel is foreground.

A parked object. A pixel shows 50 for 200 frames, so one component has weight 1. Then an object stops on it and the pixel shows 200 from then on. In the first frame no component matches, and the new component has weight w0=0.05w_0 = 0.05. After tt more frames its weight is 1−0.95×0.99t1 - 0.95 \times 0.99^t. It is background as soon as the weight of the old component, 0.95×0.99t0.95 \times 0.99^t, is at most T=0.7T = 0.7, which first happens at t=31t = 31. The old component still has weight 0.700.70 then, so the value 50 is also still background when the object leaves.

A short video. A 16×1616 \times 16 textured background with noise of standard deviation 2 is shown for 35 frames, and then a 6×66 \times 6 bright square moves across it. In the 15 frames with the square, all 480 square pixels are foreground and no background pixel is.

Correctness

The method is a heuristic: nothing proves that the background components are the true background. The proved facts are about the update rules. The proofs are in proofs/correctness.md.

  • Theorem: the weights. After every update the weights are nonnegative and sum to 1.
  • Theorem: the means stay in range. Every mean is a convex combination of values the pixel has shown, so it stays between their minimum and maximum.
  • Theorem: a heavy component is background. A component with weight at least 1−T1 - T is always among the first BB, whatever its variance.
  • Theorem: the weight of a matched component. If one component matches in tt frames in a row, its weight is 1−(1−w)(1−α)t1 - (1 - w)(1 - \alpha)^t, where ww is its weight before the run. Each weight is an exponential moving average of its match indicator.
  • Theorem: absorption time. If a new value creates a component and then matches it in every frame, the pixel is background after at most ⌈ln⁡(T/(1−w0))/ln⁡(1−α)⌉\lceil \ln(T / (1 - w_0)) / \ln(1 - \alpha) \rceil frames. With α=0.01\alpha = 0.01, T=0.7T = 0.7 and w0=0.05w_0 = 0.05 this is 31. This bound is derived on this page, not taken from the paper.
  • Not proved. The mixture is not a maximum likelihood fit. The update assigns each value to one component, like an online k-means step, instead of the soft assignment of expectation maximization, and nothing guarantees convergence to a fit of the true distribution.
Proof: Why the weights stay a probability vector, why a heavy component is background, and how long a stationary object takes to become backgroundfull

Notation as on the page. One pixel has components (wk,μk,σk2)(w_k, \mu_k, \sigma_k^2), k=1,…,Kk = 1, \ldots, K, with 0<α<10 < \alpha < 1, 0<T<10 < T < 1 and 0<w0<10 < w_0 < 1. The claims are about the update rules of lines L1 to L6. They say nothing about whether the background components describe the true background.

Claim 1: the weights are a probability vector

If wk≥0w_k \ge 0 and ∑kwk=1\sum_k w_k = 1 before an update, the same holds after it.

Proof. With a match mm (line L3), each new weight (1−α)wk+α[k=m](1 - \alpha) w_k + \alpha [k = m] is nonnegative, and their sum is (1−α)∑kwk+α=1(1 - \alpha) \sum_k w_k + \alpha = 1. Without a match (line L2), let ℓ\ell be the replaced component and S=∑k≠ℓwkS = \sum_{k \ne \ell} w_k. If S>0S > 0, each other weight becomes wk(1−w0)/S≥0w_k (1 - w_0) / S \ge 0, and these sum to 1−w01 - w_0; with wℓ=w0w_\ell = w_0 the total is 1. If S=0S = 0, the implementation sets each other weight to (1−w0)/(K−1)(1 - w_0)/(K - 1), with the same total. The start state has one weight 1 and the others 0. □\square

Claim 2: the means stay in the range of the data

Let aa and bb be the smallest and the largest value the pixel has shown. Every component with positive weight has a≤μk≤ba \le \mu_k \le b.

Proof. A component gets positive weight only when it is created with mean xx, a shown value, or in the start state with the first value. The mean changes only in line L4, to (1−ρ)μ+ρx(1 - \rho)\mu + \rho x with 0≤ρ≤10 \le \rho \le 1 (the implementation clamps ρ\rho to 1). A convex combination of two numbers in [a,b][a, b] is in [a,b][a, b]. A component of weight 0 never matches, by line L1, so it never gets weight back except by line L2. □\square

Claim 3: a heavy component is background

Let BB be defined as in line L5 and let π\pi be the order by wk/σkw_k / \sigma_k. If wj≥1−Tw_j \ge 1 - T, then jj is one of the first BB components.

Proof. Let jj be at position pp of the order. The components before it have total weight at most 1−wj≤T1 - w_j \le T by Claim 1. So for every b<pb < p, the sum w(1)+⋯+w(b)≤Tw_{(1)} + \cdots + w_{(b)} \le T, which is not above TT. The smallest bb with a sum above TT is therefore at least pp, so B≥pB \ge p and jj is among the first BB. □\square

The converse is false. With T=0.5T = 0.5, a narrow component of weight 0.250.25 that comes first in the order is background, although 0.25<1−T0.25 < 1 - T. The tests compare the background set with its definition on 500 random mixtures and check Claim 3 on each.

Claim 4: the weight under repeated matches

If component jj has weight ww and is the match in tt frames in a row, its weight after them is 1−(1−w)(1−α)t1 - (1 - w)(1 - \alpha)^t.

Proof. Line L3 gives w′=(1−α)w+αw' = (1 - \alpha) w + \alpha, so 1−w′=(1−α)(1−w)1 - w' = (1 - \alpha)(1 - w). By induction on tt, 1−wt=(1−α)t(1−w)1 - w_t = (1 - \alpha)^t (1 - w). □\square

In general, the weight of component kk after the frames 1,…,t1, \ldots, t with match indicators M1,…,MtM_1, \ldots, M_t is (1−α)tw+α∑s=1t(1−α)t−sMs(1 - \alpha)^t w + \alpha \sum_{s=1}^{t} (1 - \alpha)^{t - s} M_s, an exponential moving average of the indicators, as long as no replacement happens.

Claim 5: the absorption time

Suppose the pixel shows a value xx that matches no component, so line L2 creates a component jj with weight w0w_0, and then xx matches jj in every frame (this holds, for example, if the pixel keeps the value xx and xx is farther than 2.5σk2.5 \sigma_k from every other component). Let

t∗=⌈ln⁡(T/(1−w0))ln⁡(1−α)⌉.t^* = \left\lceil \frac{\ln\big(T / (1 - w_0)\big)}{\ln(1 - \alpha)} \right\rceil.

Then the pixel is background in frame t∗t^* after the creation and in every later frame of the run. If, in addition, the components before jj in the order have total weight 1−wj1 - w_j, then t∗t^* is the first such frame.

Proof. Assume 1−w0>T1 - w_0 > T; otherwise t∗≤0t^* \le 0 and Claim 3 applies at once. By Claim 4 with w=w0w = w_0, after tt matches 1−wj=(1−w0)(1−α)t1 - w_j = (1 - w_0)(1 - \alpha)^t. This is at most TT if and only if (1−α)t≤T/(1−w0)(1 - \alpha)^t \le T / (1 - w_0). Taking logarithms, and dividing by ln⁡(1−α)<0\ln(1 - \alpha) < 0, which turns the inequality around, gives t≥ln⁡(T/(1−w0))/ln⁡(1−α)t \ge \ln(T / (1 - w_0)) / \ln(1 - \alpha), so the condition holds from t=t∗t = t^* on, since 1−wj1 - w_j decreases in tt. Then wj≥1−Tw_j \ge 1 - T, and by Claim 3 the match jj is among the first BB, so line L6 says background.

For the second sentence: if the components before jj have total weight 1−wj1 - w_j, then for t<t∗t < t^* that total is above TT, so BB ends before jj and the pixel is foreground. □\square

With α=0.01\alpha = 0.01, T=0.7T = 0.7 and w0=0.05w_0 = 0.05, ln⁡(0.7/0.95)/ln⁡(0.99)=30.39\ln(0.7 / 0.95) / \ln(0.99) = 30.39, so t∗=31t^* = 31. In the example of the page the old background component has weight 0.95⋅0.99t0.95 \cdot 0.99^t and comes first, because its σ\sigma is small, and the third component has weight 0. So the second sentence applies, and the pixel turns to background at exactly t=31t = 31. The tests check this.

Claim 6: cost of one update

Line L1 sorts KK numbers and scans them, line L3 changes KK weights, line L4 is constant work, and line L5 sorts again and scans. So one update costs O(Klog⁡K)O(K \log K) operations, with the exponential and the square root at unit cost. □\square

Complexity

Let PP be the number of pixels, KK the number of components per pixel and NN the number of frames, in the real RAM model with exp⁡\exp and square root at unit cost. One pixel update sorts the KK components twice and touches each a constant number of times, so it costs O(Klog⁡K)O(K \log K), or O(K)O(K) with an insertion step that keeps the order. One frame costs O(PKlog⁡K)O(P K \log K) and a video O(NPKlog⁡K)O(N P K \log K). The model takes O(PK)O(P K) space. The pixels are independent, so the update is easy to run in parallel.

Properties

  • Online and per pixel. Each pixel is handled alone, with no neighbors.
  • Multimodal. A pixel can have several background values, as long as each has weight; a single Gaussian cannot.
  • Adaptive. Changes of light and objects that stop become background after a number of frames set by α\alpha and TT.
  • Deterministic. The output depends only on the input and the parameters.

Variants and improvements

  • Zivkovic's model. It chooses the number of components per pixel online and drops components whose weight becomes negative under a prior.
  • Faster learning. ρ=α/wm\rho = \alpha / w_m makes a new component learn its mean and variance fast, because its weight is small.
  • Shadows. In color, a pixel whose color is the background color with less brightness is often a shadow and is not marked as foreground.
  • Post processing. Morphological opening and connected component labeling remove isolated pixels and group the rest into objects.
  • Nonparametric models. Kernel density estimation over recent values and ViBe avoid the Gaussian form.

When to use it

Use it for a fixed camera with a background that changes slowly or moves in a repeating way, such as trees, water or flicker, when the mask must be produced in real time and frame by frame. It is a standard baseline. Do not use it for a moving camera, for scenes where objects stop for long and must stay foreground, or when a scene with sudden light changes must not give a full-frame false alarm.

Pitfalls

  • Slow learning with ρ=αη\rho = \alpha \eta. The density η\eta is small, often below 0.05, so ρ\rho is much smaller than α\alpha. In the short video above the variance of a background component is still about 894 after 50 frames, from v0=900v_0 = 900. Use ρ=α/w\rho = \alpha / w or start with a smaller v0v_0.
  • Absorbed objects. A person who stands still becomes background after the absorption time, and then shows as foreground "ghost" pixels where the background reappears if the old component was dropped.
  • Variance collapse. On a pixel with constant value the variance goes to 0, and the smallest noise breaks the match. Keep a floor on the variance.
  • TT too small. With TT below the weight of the main component, B=1B = 1, and a second background value, such as the sky behind a leaf, is foreground.
  • Mixing the two orders. The background test uses the order by w/σw / \sigma after the update. Testing against the order before the update, or against weight alone, gives a different mask.

Implementations

The Python file models gray pixels, with the update of the paper by default and ρ=α/w\rho = \alpha / w as an option. The tests compare the background set with its definition by search, check the weight invariant and the closed form of the weights, check the example above, check that the parked object becomes background at exactly frame 31, check that an alternating pixel is background with K=3K = 3 and never with K=1K = 1, and run the moving square video.

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.

stauffer_grimson_background_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stauffer-grimson-background-model/. The authors are listed in prov/193Y4C.jsonl.
"""Adaptive Gaussian mixture background model (Stauffer and Grimson 1999), gray values.

Each pixel has K Gaussian components (w, mu, var). For a new value x:
  1. order the components by w / sigma and take the first one with
     |x - mu| <= 2.5 sigma as the match;
  2. no match: replace the last component by (w0, x, v0) and scale the
     other weights so that all weights sum to 1;
  3. match m: w_k <- (1 - alpha) w_k + alpha [k = m] for all k, then
     rho = alpha * eta(x | mu_m, var_m), mu_m <- (1 - rho) mu_m + rho x,
     var_m <- (1 - rho) var_m + rho (x - mu_m)^2 with the new mu_m;
  4. order again by w / sigma; the first B components, B the smallest b with
     w_(1) + ... + w_(b) > T, are the background;
  5. the pixel is background if its match is one of the first B components.

rho_mode "paper" uses rho = alpha * eta as in the paper; "alpha_over_w" uses
rho = alpha / w_m, a common faster choice. var_min is a floor on the variance,
an implementation choice that keeps the density finite.
An image is a list of rows of gray values. Cost per pixel and frame: O(K log K).
"""

import math


def gaussian_density(x, mu, var):
    return math.exp(-0.5 * (x - mu) ** 2 / var) / math.sqrt(2.0 * math.pi * var)


def ranked(comps):
    """Indices of the components by w / sigma, largest first (ties: lower index first)."""
    return sorted(range(len(comps)), key=lambda k: (-comps[k][0] / math.sqrt(comps[k][2]), k))


def background_set(comps, t):
    """The first B components by w / sigma, B the smallest b with a weight sum above t."""
    order = ranked(comps)
    total, chosen = 0.0, []
    for k in order:
        chosen.append(k)
        total += comps[k][0]
        if total > t:
            break
    return set(chosen)


class PixelMixture:
    """The mixture of one pixel: a list of [w, mu, var]."""

    def __init__(self, x, k=3, v0=900.0):
        self.comps = [[1.0, float(x), v0]] + [[0.0, 0.0, v0] for _ in range(k - 1)]

    def update(self, x, alpha=0.01, t=0.7, v0=900.0, w0=0.05, rho_mode="paper", var_min=4.0):
        """Feed one value. Returns True if the value is background."""
        c = self.comps
        order = ranked(c)
        match = None
        for k in order:  # @line L1
            if c[k][0] > 0 and abs(x - c[k][1]) <= 2.5 * math.sqrt(c[k][2]):
                match = k
                break
        if match is None:  # @line L2
            last = order[-1]
            rest = sum(c[k][0] for k in range(len(c)) if k != last)
            for k in range(len(c)):
                if k != last:
                    c[k][0] = c[k][0] * (1.0 - w0) / rest if rest > 0 else (1.0 - w0) / (len(c) - 1)
            c[last] = [w0, float(x), v0]
            return False
        for k in range(len(c)):  # @line L3
            c[k][0] = (1.0 - alpha) * c[k][0] + (alpha if k == match else 0.0)
        w, mu, var = c[match]
        if rho_mode == "paper":  # @line L4
            rho = min(1.0, alpha * gaussian_density(x, mu, var))
        else:
            rho = min(1.0, alpha / w)
        mu = (1.0 - rho) * mu + rho * x
        var = max(var_min, (1.0 - rho) * var + rho * (x - mu) ** 2)
        c[match][1], c[match][2] = mu, var
        bg = background_set(c, t)  # @line L5
        return match in bg  # @line L6


class BackgroundModel:
    """A Stauffer-Grimson model for gray images of a fixed size."""

    def __init__(self, first_frame, k=3, alpha=0.01, t=0.7, v0=900.0, w0=0.05,
                 rho_mode="paper", var_min=4.0):
        self.params = dict(alpha=alpha, t=t, v0=v0, w0=w0, rho_mode=rho_mode, var_min=var_min)
        self.pixels = [[PixelMixture(x, k, v0) for x in row] for row in first_frame]

    def apply(self, frame):
        """Returns the foreground mask of the frame: a list of rows of 0 and 1."""
        return [[0 if p.update(x, **self.params) else 1 for p, x in zip(prow, row)]
                for prow, row in zip(self.pixels, frame)]
test_stauffer_grimson_background_model.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stauffer-grimson-background-model/. The authors are listed in prov/193Y4C.jsonl.

import itertools
import math
import random

from stauffer_grimson_background_model import (
    BackgroundModel,
    PixelMixture,
    background_set,
)


def brute_background_set(comps, t):
    """The definition by search: the smallest prefix of the w / sigma order with weight above t."""
    keys = [c[0] / math.sqrt(c[2]) for c in comps]
    order = sorted(range(len(comps)), key=lambda k: (-keys[k], k))
    for b in range(1, len(comps) + 1):
        if sum(comps[k][0] for k in order[:b]) > t:
            return set(order[:b])
    return set(order)


def random_comps(rng, k):
    ws = [rng.random() for _ in range(k)]
    s = sum(ws)
    return [[w / s, rng.uniform(0, 255), rng.uniform(4, 900)] for w in ws]


def test_background_set_against_definition_and_heavy_component():
    rng = random.Random(1)
    for _ in range(500):
        comps = random_comps(rng, rng.randint(1, 5))
        t = rng.choice([0.5, 0.7, 0.9])
        got = background_set(comps, t)
        assert got == brute_background_set(comps, t)
        for k, c in enumerate(comps):
            if c[0] >= 1.0 - t:
                assert k in got  # a component of weight at least 1 - T is background


def test_page_example():
    base = [[0.6, 50.0, 16.0], [0.3, 120.0, 100.0], [0.1, 200.0, 900.0]]
    assert background_set(base, 0.7) == {0, 1}
    results = {}
    for x in (126.0, 200.0, 90.0):
        p = PixelMixture(0.0)
        p.comps = [c[:] for c in base]
        results[x] = (p.update(x), p.comps)
    bg, comps = results[126.0]
    assert bg and [round(c[0], 12) for c in comps] == [0.594, 0.307, 0.099]
    rho = 0.01 * math.exp(-0.18) / math.sqrt(2 * math.pi * 100.0)
    assert abs(rho - 0.000333) < 1e-6
    assert abs(comps[1][1] - (120.0 + 6.0 * rho)) < 1e-12
    bg, comps = results[200.0]
    assert not bg and [round(c[0], 12) for c in comps] == [0.594, 0.297, 0.109]
    bg, comps = results[90.0]
    assert not bg and comps[2] == [0.05, 90.0, 900.0]
    assert abs(comps[0][0] - 0.95 * 2 / 3) < 1e-12 and abs(comps[1][0] - 0.95 / 3) < 1e-12


def test_weights_stay_a_probability_vector():
    rng = random.Random(2)
    for mode in ("paper", "alpha_over_w"):
        p = PixelMixture(100.0, k=4)
        lo = hi = 100.0
        for _ in range(2000):
            x = rng.choice([rng.gauss(100, 3), rng.gauss(180, 5), rng.uniform(0, 255)])
            lo, hi = min(lo, x), max(hi, x)
            p.update(x, rho_mode=mode)
            assert all(c[0] >= 0 for c in p.comps)
            assert abs(sum(c[0] for c in p.comps) - 1.0) < 1e-9
            assert all(c[2] >= 4.0 for c in p.comps)
            assert all(lo - 1e-9 <= c[1] <= hi + 1e-9 for c in p.comps if c[0] > 0)


def test_weight_closed_form_under_repeated_matches():
    alpha, w0 = 0.01, 0.05
    p = PixelMixture(50.0)
    for _ in range(200):
        p.update(50.0, alpha=alpha)
    assert p.update(200.0, alpha=alpha, w0=w0) is False  # no match: a new component
    k = max(range(3), key=lambda i: p.comps[i][1])
    assert p.comps[k][0] == w0
    for t in range(1, 60):
        p.update(200.0, alpha=alpha)
        assert abs(p.comps[k][0] - (1.0 - (1.0 - w0) * (1.0 - alpha) ** t)) < 1e-12


def test_stationary_object_absorbed_after_the_bound():
    alpha, t_bg, w0 = 0.01, 0.7, 0.05
    bound = math.ceil(math.log(t_bg / (1.0 - w0)) / math.log(1.0 - alpha))
    assert bound == 31
    p = PixelMixture(50.0)
    for _ in range(200):
        assert p.update(50.0, alpha=alpha, t=t_bg)
    flags = [p.update(200.0, alpha=alpha, t=t_bg, w0=w0) for _ in range(60)]
    # frame 0 creates the component; frame 31 is the first background frame
    assert flags.index(True) == bound and all(flags[bound:])
    # the old background value is still background
    assert p.update(50.0, alpha=alpha, t=t_bg)


def test_bimodal_pixel_is_background():
    rng = random.Random(4)
    p3 = PixelMixture(60.0, k=3)
    p1 = PixelMixture(60.0, k=1)
    flags3, flags1 = [], []
    for f in range(600):
        x = (60.0 if f % 2 == 0 else 190.0) + rng.gauss(0, 2)
        flags3.append(p3.update(x))
        flags1.append(p1.update(x))
    assert all(flags3[100:])  # both modes are background
    assert not any(flags1[1:])  # one Gaussian never settles on two modes


def make_video(seed, size=16, frames=50, start=35):
    """A static textured background with noise 2, and a 6 by 6 square of value 230
    that enters at frame `start` and moves one pixel to the right per frame."""
    rng = random.Random(seed)
    base = [[rng.uniform(40, 120) for _ in range(size)] for _ in range(size)]
    video, truth = [], []
    for f in range(frames):
        img = [[base[y][x] + rng.gauss(0, 2) for x in range(size)] for y in range(size)]
        mask = [[0] * size for _ in range(size)]
        if f >= start:
            x0 = f - start
            for y in range(5, 11):
                for x in range(x0, min(size, x0 + 6)):
                    img[y][x] = 230.0 + rng.gauss(0, 2)
                    mask[y][x] = 1
        video.append(img)
        truth.append(mask)
    return video, truth


def test_moving_square_detected():
    for mode in ("paper", "alpha_over_w"):
        video, truth = make_video(5)
        model = BackgroundModel(video[0], rho_mode=mode)
        tp = fp = fn = 0
        for f in range(1, len(video)):
            mask = model.apply(video[f])
            if f < 35:
                continue
            for a, b in zip(itertools.chain(*mask), itertools.chain(*truth[f])):
                tp += a and b
                fp += a and not b
                fn += b and not a
        assert fn == 0
        assert fp <= 0.01 * (tp + fp)

History

Wren, Azarbayejani, Darrell and Pentland modeled each background pixel by one Gaussian in their Pfinder system of 1997. In 1999, Stauffer and Grimson replaced it by an adaptive mixture of Gaussians per pixel, updated online, so that a pixel could have more than one background value and the model could follow slow changes. They used it in a tracking system that ran in real time and learned patterns of activity, described in their 2000 paper. Zivkovic made the number of components adaptive in 2004. Surveys such as Bouwmans (2014) list the mixture model as one of the most used and extended background models.

References

  1. Chris Stauffer and W. Eric L. Grimson, Adaptive background mixture models for real-time tracking, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 1999, vol. 2, 246-252, the sections on the online mixture update and on the background model estimate
  2. Chris Stauffer and W. Eric L. Grimson, Learning patterns of activity using real-time tracking, IEEE Transactions on Pattern Analysis and Machine Intelligence 22(8), 2000, 747-757, the description of the adaptive background model in the tracking system
  3. Zoran Zivkovic, Improved adaptive Gaussian mixture model for background subtraction, International Conference on Pattern Recognition (ICPR), 2004, vol. 2, 28-31, the whole paper (the number of components chosen per pixel)
  4. Christopher R. Wren, Ali Azarbayejani, Trevor Darrell and Alex P. Pentland, Pfinder: real-time tracking of the human body, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(7), 1997, 780-785, the background model with one Gaussian per pixel
  5. Thierry Bouwmans, Traditional and recent approaches in background modeling for foreground detection: an overview, Computer Science Review 11, 2014, 31-66, the survey of mixture models and their variants

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.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