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.
- Solves
- Background subtraction
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativeonline
- Evidence
- Proof sketchCode in 1 languages
- 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 Gaussians over its values, with 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 depends only on frames to .
The model of one pixel. The pixel holds components with and . The paper models the recent history of the pixel as the mixture density , where is the Gaussian density. The parameters are the learning rate , the background fraction , and the variance and weight of a new component.
The algorithm
SG-PIXEL(x, the components (w_k, μ_k, σ_k²), α, T, v_0, w_0)- 1
order the components by w_k / σ_k, largest first; m ← the first k with |x - μ_k| ≤ 2.5 σ_k, or none - 2
if 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 - 3
for each k: w_k ← (1 - α) w_k + α [k = m] - 4
ρ ← α η(x | μ_m, σ_m²); μ_m ← (1 - ρ) μ_m + ρ x; σ_m² ← (1 - ρ) σ_m² + ρ (x - μ_m)² - 5
order the components again by w_k / σ_k; B ← the smallest b with w_(1) + ... + w_(b) > T - 6
return 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 , which makes the bounds below exact. The variance update of line L4 uses the new mean. Line L4 uses the factor of the paper; many implementations use instead, which learns faster (see the pitfalls). The implementation also keeps , 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 , , , (a standard deviation of 30) and . They are tuned values for 8-bit gray images, not values from the paper.
Example
One pixel. The pixel has three components, written as : , and . The ratios are , and , so that is also the order. With , the first weight is not above and the first two give , so : the components around 50 and 120 are the background. Let .
- . It is not within of 50, but it is within of 120, so it matches the second component. The weights become . The factor is , so the mean moves from 120 to . The match is among the first , so the pixel is background.
- . It matches the third component, and the weights become . The order stays the same, the first two weights still sum to , and stays 2. The third component is not background, so the pixel is foreground.
- . It is 40 from 50, 30 from 120 and 110 from 200, outside , and , so nothing matches. The last component becomes , and the other weights are scaled to and . 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 . After more frames its weight is . It is background as soon as the weight of the old component, , is at most , which first happens at . The old component still has weight then, so the value 50 is also still background when the object leaves.
A short video. A textured background with noise of standard deviation 2 is shown for 35 frames, and then a 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 is always among the first , whatever its variance.
- Theorem: the weight of a matched component. If one component matches in frames in a row, its weight is , where 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 frames. With , and 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 , , with , and . 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 and before an update, the same holds after it.
Proof. With a match (line L3), each new weight is nonnegative, and their sum is . Without a match (line L2), let be the replaced component and . If , each other weight becomes , and these sum to ; with the total is 1. If , the implementation sets each other weight to , with the same total. The start state has one weight 1 and the others 0.
Claim 2: the means stay in the range of the data
Let and be the smallest and the largest value the pixel has shown. Every component with positive weight has .
Proof. A component gets positive weight only when it is created with mean , a shown value, or in the start state with the first value. The mean changes only in line L4, to with (the implementation clamps to 1). A convex combination of two numbers in is in . A component of weight 0 never matches, by line L1, so it never gets weight back except by line L2.
Claim 3: a heavy component is background
Let be defined as in line L5 and let be the order by . If , then is one of the first components.
Proof. Let be at position of the order. The components before it have total weight at most by Claim 1. So for every , the sum , which is not above . The smallest with a sum above is therefore at least , so and is among the first .
The converse is false. With , a narrow component of weight that comes first in the order is background, although . 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 has weight and is the match in frames in a row, its weight after them is .
Proof. Line L3 gives , so . By induction on , .
In general, the weight of component after the frames with match indicators is , an exponential moving average of the indicators, as long as no replacement happens.
Claim 5: the absorption time
Suppose the pixel shows a value that matches no component, so line L2 creates a component with weight , and then matches in every frame (this holds, for example, if the pixel keeps the value and is farther than from every other component). Let
Then the pixel is background in frame after the creation and in every later frame of the run. If, in addition, the components before in the order have total weight , then is the first such frame.
Proof. Assume ; otherwise and Claim 3 applies at once. By Claim 4 with , after matches . This is at most if and only if . Taking logarithms, and dividing by , which turns the inequality around, gives , so the condition holds from on, since decreases in . Then , and by Claim 3 the match is among the first , so line L6 says background.
For the second sentence: if the components before have total weight , then for that total is above , so ends before and the pixel is foreground.
With , and , , so . In the example of the page the old background component has weight and comes first, because its is small, and the third component has weight 0. So the second sentence applies, and the pixel turns to background at exactly . The tests check this.
Claim 6: cost of one update
Line L1 sorts numbers and scans them, line L3 changes weights, line L4 is constant work, and line L5 sorts again and scans. So one update costs operations, with the exponential and the square root at unit cost.
Complexity
Let be the number of pixels, the number of components per pixel and the number of frames, in the real RAM model with and square root at unit cost. One pixel update sorts the components twice and touches each a constant number of times, so it costs , or with an insertion step that keeps the order. One frame costs and a video . The model takes 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 and .
- 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. 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 . The density is small, often below 0.05, so is much smaller than . In the short video above the variance of a background component is still about 894 after 50 frames, from . Use or start with a smaller .
- 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.
- too small. With below the weight of the main component, , 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 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 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 and never with , 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.
# 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
- 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
- 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 193Y4C Edit this page History Report an error Markdown