Skip to content

KNN background subtraction

Classify a pixel using how many nearby samples in its recent history agree with it.

Try it on your image ↓

VISUAL WALKTHROUGHMotion
REFERENCE INPUTCurrent frame

The object has moved away from its earlier location.

RESULTForeground mask

The moving region is retained in this ideal example. Startup, shadows and camera motion complicate real masks.

STEP 03 / 03

Accept supported observations as background and update the history.

Illustrative example. The stages explain the method; they are not a live OpenCV execution.

Try it on an image

YOUR IMAGE · REAL OPENCV

Experiment at pixel level

Open full lab ↗

Warm up a KNN background model using the first image, then classify the second image.

The engine loads on your first run. Your images stay in this browser.

Input448 × 320
OutputWaiting for a result

Scroll over either image to zoom at the pointer. Use the scrollbars to pan both views over the same relative area. Zoom is relative to the input; pixel coordinates belong to each image. Warps can change scene correspondence.

Pixel inspector RGBA · native values · matched scale · 9 × 9 output pixels
Hover to inspect. Click to pin a pixel.
Input
Select a pixel

Output
Select a pixel

Sample models and licenses

When to use it

Extract moving foreground from a relatively fixed camera without fitting a Gaussian mixture.

How it works

  1. 01Maintain a history of pixel observations.
  2. 02Count samples close to the current colour.
  3. 03Accept supported observations as background and update the history.

background when enough historical samples are nearby

What to tune

history, distance threshold and required neighbour count control adaptation and background acceptance.

Where it breaks down

It shares the fixed-camera and adaptation limitations of other per-pixel background models.

TypeScript API

Open an entry for its exact overloads, parameter descriptions, result ownership and pinned upstream source.

All of these calls execute on the CPU. Native objects need explicit disposal. See matrices and ownership and build compatibility.