Algorithmadvanced
ViBe
Also called visual background extractor.
Keep a set of past sample values per pixel, call a pixel background when enough samples are close, and update the samples randomly in time and space.
- Solves
- Background subtraction
- Time
- O(F P N) worst
- Space
- O(P N) extra
- Where
- F = the number of frames; N = the number of samples per pixel; P = the number of pixels in a frame
- Model
- Real RAM
- Properties
- randomizednot exactnot iterativeonlinerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Olivier Barnich, Marc Van Droogenbroeck, 2009
ViBe, the visual background extractor, is a method for background subtraction that keeps raw values instead of a fitted model. Each pixel stores a set of sample values from its past and from its neighbors. A new value is background if at least a few samples are close to it. A background pixel then replaces one of its samples, chosen at random, with the new value, and sometimes also puts the value into a random neighbor's set. The random choice of which sample to drop gives each sample a lifetime that decays exponentially, without a time stamp. The spread to neighbors lets a wrong start, such as an object present in the first frame, fade from its border. The Stauffer-Grimson model fits a mixture of Gaussians to each pixel and updates it with a learning rate; ViBe needs no density, no learning rate and no floating point, and it can start from a single frame.
In plain words
Each pixel keeps a small bag of 20 old values that it has seen, or that its neighbors have seen. When a new picture comes, the pixel checks how many values in its bag are close to its new value. If at least two are close, the pixel is background; otherwise it is foreground, something that moved in. A background pixel now and then throws a random value out of its bag and puts the new value in. Now and then it also puts its value into a neighbor's bag. Because the value thrown out is random, old values leave slowly and new ones come in without any clock. Foreground pixels never change their own bag, so a walking person does not become background.
The problem
The input is a sequence of gray images of the same size from a fixed camera; for color, the distance below is the Euclidean distance between color vectors. The output for each frame is a binary mask, 1 for foreground. The method is online and randomized.
The model. Pixel holds the samples . The parameters are , the radius , the count and the subsampling factor . The paper uses , , and , chosen by experiment.
The algorithm
VIBE-FRAME(the frame v, the samples M, N, R, #min, φ)- 1
(first frame only) for each pixel x: M(x) ← N values of random pixels of the 3 × 3 neighborhood of x - 2
for each pixel x: count the samples s ∈ M(x) with |v(x) - s| < R, stopping at #min - 3
x is background if the count reaches #min, else foreground - 4
for each foreground pixel: no update - 5
for each background pixel x: with probability 1/φ, replace a sample of M(x) chosen at random by v(x) - 6
with probability 1/φ, choose a random 8-neighbor y of x and replace a random sample of M(y) by v(x)
The classification of line L2 stops as soon as samples are close, so on most background pixels it reads only a few samples. Lines L5 and L6 are the three parts of the update of the paper. The update is conservative: only background values enter the model. The replaced sample is chosen at random, not the oldest one. Only one frame in on average updates a pixel, which the paper calls time subsampling. And the value also spreads to a neighbor, which keeps the models of nearby pixels consistent. The implementation classifies the whole frame before it updates, so the result does not depend on the order of the pixels, and it starts the model with a value from the pixel itself or one of its 8 neighbors, chosen at random.
Example
Classification. A pixel with has the samples , and , .
- The value 110 is closer than 20 to 100, 104, 96 and 119. The count reaches 2 at the second sample, so it is background.
- The value 140 is closer than 20 only to 131. The sample 160 is at distance exactly 20, which is not closer than . The count is 1, so it is foreground.
- The value 150 is closer than 20 to 131 (distance 19) and to 160 (distance 10), so it is background.
The lifetime of a sample. Each update of a pixel's own set keeps a given sample with probability , whatever happened before. So the chance that a sample survives updates is . With and an update in every frame (), a sample survives 3 frames with probability . With and , a pixel that only updates its own set keeps a sample for frames on average. An inner pixel whose 8 neighbors are also background loses samples to its neighbors too, and the mean lifetime falls to about 160 frames.
A ghost. In the first frame of a image, a object of value 200 stands on a flat background of value 50, and then it goes away. The models of the object's pixels hold the value 200, so the free background there is foreground: a ghost. The 20 border pixels of the object took some samples from the background at the start. In the seeded run of the tests they all have at least 2 such samples, so the ghost starts with the 16 inner pixels. With , the background values of the neighbors spread inward, and the ghost counts per frame are 16, 16, 12, 10, 7, 3, 1, 1, 0. With , 10 pixels are still ghost after 70 frames.
A short video. On a gradient background with noise of standard deviation 2, a bright square moves in after 25 frames. In the 15 frames with the square, every square pixel is foreground, and at most 2 percent of the foreground pixels are false.
Correctness
ViBe is a heuristic: the proved facts are about its random update, not about the quality of the mask. The proofs are in proofs/correctness.md.
- Theorem: memoryless survival. A sample in a set that is updated times survives with probability , independently of its age. This equals , an exponential decay.
- Theorem: expected lifetime. For a pixel that is always background and only updates its own set, the lifetime of a sample in frames is geometric with mean . For an inner pixel whose 8 neighbors are background and have 8 neighbors each, the survival per frame is , and the mean is about .
- Theorem: conservative update. Line L5 never writes into the set of a foreground pixel; only line L6 of a background neighbor can. In a frame where all pixels are foreground, the model does not change.
- Theorem: a ghost on a flat background only shrinks. If all later frames are the same flat image, a pixel that is background stays background, so the number of ghost pixels never grows.
- Not proved. How fast a ghost disappears on real video, and how the parameters trade false alarms for misses, are benchmark results.
Proof: Why the sample lifetimes decay exponentially, why the update is conservative, and why a ghost on a flat background only shrinksfull
Notation as on the page. Pixel holds samples , a value is background when at least samples have , and each random choice of lines L5 and L6 is independent of all others. The claims are about the random update. They say nothing about whether the mask matches the true moving objects.
Claim 1: memoryless survival
Fix a sample in . Each time line L5 or line L6 writes into , the sample survives with probability , whatever happened before. After writes it survives with probability .
Proof. A write into picks the index to replace uniformly from , independently of the past. The sample is lost only if its index is picked, which has probability . The writes use independent random numbers, so the survival probabilities multiply.
The age of does not enter: an old sample and a new one have the same chance to survive the next write. This is why ViBe needs no time stamps.
Claim 2: the expected lifetime
(a) If is background in every frame and no neighbor writes into , the number of frames that survives is geometric with parameter , and its mean is .
(b) If and its 8 neighbors are background in every frame and every neighbor has 8 neighbors, then survives one frame with probability
and the mean lifetime is .
Proof. (a) In one frame, line L5 writes into with probability , and that write removes with probability by Claim 1. So is lost in a given frame with probability , independently over frames. The first loss is geometric, with mean .
(b) In one frame, the own write removes with probability , as in (a). A neighbor removes if it makes a neighbor write (probability ), chooses among its 8 neighbors (probability ), and picks the index of (probability ), so with probability . The 9 events use independent random numbers, so survives the frame with probability , and the lifetime is geometric with mean .
With and , (a) gives a mean of 320 frames and (b) gives and a mean of about 160.36 frames. Since to first order, the mean in (b) is about . The tests check (a) by sampling and the numbers of (b) exactly.
Claim 3: the update is conservative
Line L5 never writes into the set of a foreground pixel, and only background values are written by lines L5 and L6. In a frame where every pixel is foreground, no set changes.
Proof. Line L4 skips foreground pixels, so lines L5 and L6 run only for a background pixel , and they write the value . Line L5 writes into only, and is background. If every pixel is foreground, lines L5 and L6 never run.
A foreground pixel can still receive a value through line L6 of a background neighbor. That is the spatial spread, and it is the reason a ghost, or a stopped object, is eaten from its border.
Claim 4: on a flat background a ghost only shrinks
Suppose that from some frame on, every frame is the same flat image with value at every pixel. Then a pixel that is background in one of these frames is background in every later one. So the number of foreground pixels never grows.
Proof. Let be the number of samples with . Every write of lines L5 and L6 in these frames writes the value of some background pixel, because the image is flat. A write replaces one sample of some by , and . If the replaced sample was close to , then stays the same; otherwise it grows by 1. So never decreases. A pixel is background exactly when , which then stays true. The classification of line L2 uses the sets as they are at the start of the frame, before the updates, so the argument holds frame by frame.
The claim needs the flat image. If two neighbors show values farther apart than , a write from one into the other can remove a close sample and turn a background pixel to foreground. The tests check the claim on a ghost: the counts per frame never grow, and with they reach 0.
Claim 5: the early stop gives the same answer
The loop of line L2 that stops when the count reaches returns background exactly when the full count of close samples is at least .
Proof. The count only grows during the loop. If the loop stops early, the count of the samples read so far is , and the full count is at least that. If it does not stop, it has read every sample, so its count is the full count, and that count is below .
Claim 6: cost of one frame
For pixels, line L2 reads at most samples per pixel, line L5 makes one random draw and at most one write per pixel, and line L6 makes at most two random draws, a list of at most 8 neighbors and one write. So a frame costs operations, with a random integer at unit cost, and the model takes space. Line L1 makes random draws per pixel once, so it costs .
Complexity
Let be the number of pixels and the number of samples per pixel, in the real RAM model with a random integer at unit cost. Line L2 reads at most samples per pixel, and lines L5 and L6 make constant work. One frame costs time, and frames cost . The start of line L1 costs once, and the model takes space. On background pixels the early stop makes the classification much cheaper than reads in practice.
Properties
- Randomized. The update uses random numbers; the result of a run depends on the seed.
- Start from one frame. No training sequence is needed.
- No float arithmetic. On 8-bit images all steps use small integers.
- No ordering of samples. No sample has a time stamp, and the decay is exponential by the random choice alone.
- Spatial consistency (a heuristic). Neighbor updates make nearby pixels share values, which can also help when the camera shakes a little.
Variants and improvements
- Color. Use the Euclidean distance between color vectors, or the sum of absolute differences.
- Adaptive radius and rate (a heuristic). Change and per pixel from the recent decisions, so that noisy pixels get a larger radius.
- No spread across the mask border (a heuristic). Skip a neighbor update when the chosen neighbor is foreground. Stopped objects then stay foreground longer, but ghosts also stay longer.
- Post processing. Morphological opening, a median filter of the mask, and connected component labeling clean the mask.
- Kernel density estimation. A sample based model can score a value with a kernel density sum instead of a count. This needs a kernel evaluation for each sample, and the early stop is lost.
When to use it
Use ViBe for a fixed camera when the mask must be computed fast and on simple hardware, when the model must start without a training period, or when the first frames contain moving objects that must be forgotten. It is a strong and simple baseline. Do not use it when a stopped object must stay foreground for long, since the spread from its border makes it background; and do not use it with a moving camera.
Pitfalls
- Ghosts with a slow update. With an object in the first frame leaves a ghost for many frames; in the example above, 10 of 16 ghost pixels remain after 70 frames. A smaller removes it faster but also absorbs slow objects faster.
- Objects eaten from their border. The neighbor spread works on any foreground region, also on a real object that stands still. Its border pixels become background first.
- The strict test. Decide once whether a sample at distance exactly counts, and keep it the same in tests and code.
- Visiting order. If the update runs inside the same loop as the classification, a neighbor update can change the decision of a pixel that is visited later in the same frame. Classify first, then update.
- Seeds in tests. The method is random; fix the seed of the generator, and test probabilities with a tolerance.
Implementations
The Python file follows the paper for gray images, with the parameters of the paper as defaults, and classifies each frame before the update. The tests compare the early stop with a full count, check the classification example above, measure the survival of a marked sample against and its mean lifetime against by sampling, check the lifetime formula for an inner pixel, check that foreground pixels never update, check that a ghost shrinks frame by frame to nothing 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/vibe-background-subtraction/. The authors are listed in prov/2FRG4D.jsonl.
"""ViBe, the visual background extractor (Barnich and Van Droogenbroeck 2011), gray values.
Each pixel keeps N past sample values. A value v is background if at least
min_matches samples s have |v - s| < R. A background pixel then, with
probability 1 / phi, replaces one of its own samples chosen at random by v,
and, with probability 1 / phi, replaces a random sample of a random
8-connected neighbor by v. Foreground pixels update nothing (a conservative
update). The model starts from one frame: each sample is the value of a
random pixel of the 3 by 3 neighborhood.
This file classifies the whole frame first and then updates, so the result of
a frame does not depend on the order in which the pixels are visited.
An image is a list of rows of gray values. Cost per frame: O(P N) for P pixels.
"""
import random
NEIGHBORS = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
class ViBe:
def __init__(self, first_frame, n=20, radius=20, min_matches=2, phi=16, seed=0):
self.n = n
self.radius = radius
self.min_matches = min_matches
self.phi = phi
self.rng = random.Random(seed)
self.h = len(first_frame)
self.w = len(first_frame[0])
self.samples = [[self._init_samples(first_frame, y, x) for x in range(self.w)] for y in range(self.h)]
def _init_samples(self, img, y, x):
out = []
for _ in range(self.n): # @line L1
dy, dx = self.rng.choice([(0, 0)] + NEIGHBORS)
yy = min(max(y + dy, 0), self.h - 1)
xx = min(max(x + dx, 0), self.w - 1)
out.append(img[yy][xx])
return out
def is_background(self, v, samples):
count = 0
for s in samples: # @line L2
if abs(v - s) < self.radius:
count += 1
if count >= self.min_matches:
return True
return False
def neighbors(self, y, x):
return [(y + dy, x + dx) for dy, dx in NEIGHBORS if 0 <= y + dy < self.h and 0 <= x + dx < self.w]
def apply(self, frame):
"""Returns the foreground mask of the frame (1 = foreground) and updates the model."""
mask = [[0 if self.is_background(frame[y][x], self.samples[y][x]) else 1 # @line L3
for x in range(self.w)] for y in range(self.h)]
rng = self.rng
for y in range(self.h):
for x in range(self.w):
if mask[y][x]:
continue # @line L4
v = frame[y][x]
if rng.randrange(self.phi) == 0: # @line L5
self.samples[y][x][rng.randrange(self.n)] = v
if rng.randrange(self.phi) == 0: # @line L6
nb = self.neighbors(y, x)
if nb:
yy, xx = rng.choice(nb)
self.samples[yy][xx][rng.randrange(self.n)] = v
return mask
test_vibe_background_subtraction.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vibe-background-subtraction/. The authors are listed in prov/2FRG4D.jsonl.
import itertools
import math
import random
from vibe_background_subtraction import ViBe
def brute_is_background(v, samples, radius, min_matches):
return sum(1 for s in samples if abs(v - s) < radius) >= min_matches
def test_classification_against_full_count():
rng = random.Random(1)
model = ViBe([[0]])
for _ in range(2000):
samples = [rng.randint(0, 255) for _ in range(20)]
v = rng.randint(0, 255)
assert model.is_background(v, samples) == brute_is_background(v, samples, 20, 2)
def test_page_example_classification():
model = ViBe([[0]], n=6)
samples = [100, 104, 131, 96, 160, 119]
assert model.is_background(110, samples) # 100, 104, 96 and 119 are closer than 20
assert not model.is_background(140, samples) # only 131; 160 is at distance 20, not closer
assert model.is_background(150, samples) # 131 and 160
def survival_frequency(n, phi, frames, runs, seed):
"""A 1 by 1 image that is always background: how often does the first sample survive?"""
rng = random.Random(seed)
alive = 0
for _ in range(runs):
model = ViBe([[100]], n=n, phi=phi, seed=rng.randrange(10 ** 9))
model.samples[0][0] = [101] + [100] * (n - 1) # mark the first sample
for _ in range(frames):
model.apply([[100]])
alive += 101 in model.samples[0][0]
return alive / runs
def test_survival_is_memoryless():
# With phi = 1 each frame replaces one of N = 5 samples: survival (4/5)^t.
for t in (1, 3, 6):
f = survival_frequency(5, 1, t, 1200, 10 + t)
assert abs(f - 0.8 ** t) < 0.045
def test_expected_lifetime_is_phi_times_n():
rng = random.Random(4)
n, phi, runs = 5, 4, 1500
total = 0
for _ in range(runs):
model = ViBe([[100]], n=n, phi=phi, seed=rng.randrange(10 ** 9))
model.samples[0][0] = [101] + [100] * (n - 1)
t = 0
while 101 in model.samples[0][0]:
model.apply([[100]])
t += 1
total += t
mean = total / runs
assert abs(mean - phi * n) < 0.1 * phi * n
def test_interior_lifetime_formula():
# Own updates and the eight neighbors: the survival per frame and the mean lifetime.
n, phi = 20, 16
q = (1 - 1 / (phi * n)) * (1 - 1 / (8 * phi * n)) ** 8
assert abs(1 / (1 - q) - 160.36) < 0.01
assert abs(math.log(q) * 320 + 2.0) < 0.002
def test_foreground_pixels_never_update():
model = ViBe([[50] * 6 for _ in range(6)], phi=1, seed=3)
before = [[s[:] for s in row] for row in model.samples]
for _ in range(20):
mask = model.apply([[200] * 6 for _ in range(6)])
assert all(all(row) for row in mask)
assert model.samples == before
def ghost_counts(phi, frames, seed):
"""The first frame has a 6 by 6 object of value 200 on a background of 50, then
the object is gone. Returns the number of foreground pixels per frame."""
size = 12
first = [[200 if 3 <= y < 9 and 3 <= x < 9 else 50 for x in range(size)] for y in range(size)]
model = ViBe(first, phi=phi, seed=seed)
bg = [[50] * size for _ in range(size)]
return [sum(itertools.chain(*model.apply(bg))) for _ in range(frames)]
def test_ghost_erodes_from_its_border():
counts = ghost_counts(1, 80, 7)
assert 16 <= counts[0] <= 36 # at most the object; its border already mixes in background samples
assert all(a >= b for a, b in zip(counts, counts[1:]))
assert counts[-1] == 0
# with the default phi = 16 the same ghost is still there after 80 frames
assert ghost_counts(16, 80, 7)[-1] > 0
def test_moving_square_detected():
rng = random.Random(5)
size = 16
base = [[60 + 3 * x + 2 * y for x in range(size)] for y in range(size)]
model = ViBe(base, seed=9)
tp = fp = fn = 0
for f in range(1, 40):
img = [[base[y][x] + rng.gauss(0, 2) for x in range(size)] for y in range(size)]
truth = [[0] * size for _ in range(size)]
if f >= 25:
for y in range(5, 11):
for x in range(f - 25, min(size, f - 19)):
img[y][x] = 230 + rng.gauss(0, 2)
truth[y][x] = 1
mask = model.apply(img)
if f < 25:
continue
for a, b in zip(itertools.chain(*mask), itertools.chain(*truth)):
tp += a and b
fp += a and not b
fn += b and not a
assert fn == 0
assert fp <= 0.02 * (tp + fp)
History
The parametric model of Stauffer and Grimson from 1999 was a common baseline for pixel models; the survey of Bouwmans covers it and the sample based models. In 2009, Barnich and Van Droogenbroeck presented ViBe at ICASSP. Its main ideas were to replace a random sample instead of the oldest one, to spread values to neighbors, and to start from one frame. The journal version of 2011 gave the full method, the analysis of the exponential decay of the sample lifetimes, and the parameter values found by experiment.
References
- Olivier Barnich and Marc Van Droogenbroeck, ViBe: a universal background subtraction algorithm for video sequences, IEEE Transactions on Image Processing 20(6), 2011, 1709-1724, Section 3.1 (the classification), Section 3.2 (the start from one frame), Section 3.3 (the conservative, random and spatial update), Section 4.1 (the parameter values)
- Olivier Barnich and Marc Van Droogenbroeck, ViBe: a powerful random technique to estimate the background in video sequences, IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), 2009, 945-948, the whole paper (the first version of the method)
- Chris Stauffer and W. Eric L. Grimson, Adaptive background mixture models for real-time tracking, CVPR 1999, vol. 2, 246-252, the parametric model that ViBe is compared with
- Thierry Bouwmans, Traditional and recent approaches in background modeling for foreground detection: an overview, Computer Science Review 11, 2014, 31-66, the survey of sample based models
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 2FRG4D Edit this page History Report an error Markdown