DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at on

#OpenCV – Background Subtraction in a camera feed 🎦 using MOG2

Hi !

Yesterday I wrote a post about how to remove the background from my camera feed. To remove the background, I used a python library β€œcvzone”.

While talking with some friends, someone asked about using some of the out-of-the-box features included in OpenCV, like MOG2 or KNN. So I read a little about them and I get this sample up and running.

OpenCV Remove Background from Camera using MOG2

As you can see the output is completely different than before, and not even close to what I’m looking for. And it makes sense, the official OpenCV documentation explains how this method works here: [How to Use Background Subtraction Methods].

Background subtraction (BS) is a common and widely used technique for generating a foreground mask (namely, a binary image containing the pixels belonging to moving objects in the scene) by using static cameras.

As the name suggests, BS calculates the foreground mask performing a subtraction between the current frame and a background model, containing the static part of the scene or, more in general, everything that can be considered as background given the characteristics of the observed scene.


Background modeling consists of two main steps:

  1. Background Initialization;
  2. Background Update.

In the first step, an initial model of the background is computed, while in the second step that model is updated in order to adapt to possible changes in the scene.

And the sample code:

Happy coding!


El Bruno

More posts in my blog

Top comments (0)