Background subtraction

Using Background Subtraction for computer vision applications

Guilherme Gaigher Netto
5 min readJul 23, 2019

Fala pessoal. Vamos começar com um post dedicado a uma das ferramentas que, particularmente, eu acho extremamente eficiente no campo de visão computacional: A Subtração de Fundo (Background Subtraction — BgS).

What’s up, everyone. Let’s get started with a post dedicated to one of the tools that particularly I think is extremely efficient in the field of computer vision: the Background Subtraction — BgS.

Em poucas palavras, o BgS faz exatamente isso! Ela retira o fundo da imagem. Mas o que é o fundo de uma imagem? Podemos pensar que o fundo seria aquilo que não se movimenta em uma imagem, ou seja, aqueles pixels que permanecem aproximadamente com o mesmo valor após uma sequência de frames. Eu particularmente gosto de pensar dessa forma ao invés de pensar em um “fundo”, ou algo que esteja em um “segundo plano”. Para isso também temos outras técnicas, como Extração de Saliência, mas vamos falar delas em outra ocasião.

In a few words, BgS does exactly that! It removes the background from the image. But what is the background of an image? We may think that the background would be what does not move in an image, ie those pixels that remain with approximate values after a sequence of frames. I particularly like to think that way instead of thinking in “background” itself. For removing this kind of background, we also have other techniques, like Saliency Extraction, but let’s talk about these another time.

E para que isso seria usado? Para um infinidade de coisas! Já que nós conseguimos detectar o que está em movimento em uma imagem, nós então podemos detectar veículos e/ou pedestres passando em uma rua, ou criar um sistema inteligente de câmeras de segurança. E interagir com o computador? Claro! Aliando essa técnica com outras, como por exemplo, Optical Flow, nós podemos criar aplicações, tanto de hobbistas quanto industriais bastante poderosas. E tudo isso sem precisar da famosa REDE NEURAL CONVOLUCIONAL POWER EXTREME SUPREME, ou seja, uma aplicação que roda até naquele computador velho da portaria do prédio.

And what would that be used for? For several things! Since we can detect what is in motion in an image, we can then detect vehicles and/or pedestrians passing on a street, or create a smart surveillance system. And interact with the computer? Of course! Combining this technique with others, such as Optical flow, we can create applications, both for hobbyists as industrial quite powerful. And all this without the needing of the famous CONVOLUTIONAL NEURAL NETWORK POWER EXTREME SUPREME, that is, an application that runs even in that old computer of your building’s entrance.

O OpenCV possui implementados vários métodos de BgS, sendo alguns no módulo bgsegm (Improved Background-Foreground Segmentation Methods). Todes eles com diversos parâmetros de ajustes para melhor compor cada aplicação. Obviamente, é sempre bom fazer uma leitura de como o método funciona, mesmo que seja aquela famosa leitura na diagonal, assim você consegue saber melhor para que serve cada parâmetro. Mas vamos lá, vamos fazer alguma coisa então.

OpenCV has implemented many methods of BgS, some in the module bgsegm (Improved Background-Foreground Segmentation Methods). All of them with many adjusts parameters for improving each application. It’s always good taking a look in how the method works, even if just a quick reading, then you can know better how works for each parameter.

Abaixo segue um pequeno código e um gif demonstrando o uso de BgS para segmentação de um objeto em movimento. Dos parâmetros que modifiquei do default foram o background ratio, para 0.85, e shadow value, para 255. O dever de casa vai ser descobrir para que eles servem (além de brincar com outros parâmetros e métodos de BgS). Obs.: Meu OpenCV está na versão “3.4.1”.

Below is a short code and gif demonstrating the use of BgS for segmenting a moving object. The parameters I changed from the default were Background Ratio, to 0.85, and Shadow Value, to 255. The homework will be figuring out what they’re for (besides playing with the others parameters and BgS methods). Note: My OpenCV is at version “3.4.1”.

Background subtraction demonstration
Tracking a moving object

Observem agora esse outro gif, onde eu criei três versões de BgS modificando os parâmetros anteriores para as três versões. Observem a influência deles no resultado final. O primeiro é exatamente o do código acima. O segundo está com o background ratio em 0.5 e shadow value em 127. Por fim, o terceiro está com background ratio em 0.9 e shadow value em 0. O que será que esses parâmetros fazem hein?!

Now, look at this other gif where I created three versions of BgS by modifying the previous parameters for the three versions. Notice their influence on the end result. The first is exactly that of the code above. The second has a background ratio of 0.5 and a shadow value of 127. Finally, the third has a background ratio of 0.9 and a shadow value of 0. What do these parameters do huh?!

Background subtraction with different parameters

Claro que uma aplicação para fazer tracking de uma caneta não é lá grandes coisa, mas isso foi só pra demonstrar a técnica. Atualmente, eu trabalho como engenheiro de soluções na MVISIA, empresa de inteligência artificial e visão computacional focada em aplicações industriais nos mais diversos ramos. Aqui já utilizei diversas vezes essa técnica. Por exemplo, um mesmo sistema que desenvolvemos é capaz de detectar se existe ou não vazão em uma linha industrial, e estimar essa vazão. Tudo isso utilizando BgS.

Of course, an application for tracking a pen is no big deal, but that was just for the demonstrate the technique. I currently work as a solution engineer at MVISIA, an artificial intelligence and computer vision company applied focused on industrial application in many sectors. Here I have used this technique several times. For example, the same system we develop can detect whether or not there is flow in an industrial line, and estimate this flow. All this using BgS.

Bom, minha intenção nesse primeiro post foi apresentar uma técnica bastante eficiente no campo de visão computacional, que serve para uma infinidade de coisas. Lembrem-se que estamos detectando movimento em uma sequência de frames. Olhem só o tanto de coisa que podemos então fazer com isso! É só usar a criatividade. Obrigado!

Well, my intention in this first post was to present a very efficient technique in the field of computer vision that serves for several things. Remember that we are detecting motion in a frame sequence. Just look at how much we can do with it! Just use creativity. Thank you!

--

--

Guilherme Gaigher Netto

Computer vision engineer focused on industrial applications of Artificial Intelligence