KNN background subtraction
Classify a pixel using how many nearby samples in its recent history agree with it.
The object has moved away from its earlier location.
Previous object locations show why a temporal model needs multiple observations.
Compare the current sample with its history and count nearby values.
The moving region is retained in this ideal example. Startup, shadows and camera motion complicate real masks.
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
Experiment at pixel level
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.
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
Select a pixel
Select a pixel
When to use it
Extract moving foreground from a relatively fixed camera without fitting a Gaussian mixture.
How it works
- 01Maintain a history of pixel observations.
- 02Count samples close to the current colour.
- 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.
Related methods
Lucas-Kanade optical flow
Follow selected points by finding the small displacement that best aligns each local patch.
Farneback dense optical flow
Estimate a displacement vector at every pixel using local polynomial approximations.
DIS dense optical flow
Combine fast patch alignment with spatial propagation and dense refinement.
Dual TV-L1 optical flow
Estimate flow with a robust data term and a total-variation smoothness penalty.