The Wayback Machine - https://web.archive.org/web/20240930183548/https://www.geeksforgeeks.org/background-subtraction-opencv/
Open In App

Background subtraction – OpenCV

Last Updated : 19 Feb, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Background subtraction is a way of eliminating the background from image. To achieve this we extract the moving foreground from the static background.

Background Subtraction has several use cases in everyday life, It is being used for object segmentation, security enhancement, pedestrian tracking, counting the number of visitors, number of vehicles in traffic etc. It is able to learn and identify the foreground mask.

In OpenCV we have 3 algorithms to do this operation –

BackgroundSubtractorMOG – It is a Gaussian Mixture-based Background/Foreground Segmentation Algorithm.

BackgroundSubtractorMOG2 – It is also a Gaussian Mixture-based Background/Foreground Segmentation Algorithm. It provides better adaptability to varying scenes due illumination changes etc.

BackgroundSubtractorGMG – This algorithm combines statistical background image estimation and per-pixel Bayesian segmentation.

How to apply OpenCV in-built functions for background subtraction –
Step #1 – Create an object to signify the algorithm we are using for background subtraction.
Step #2 – Apply backgroundsubtractor.apply() function on image.

Below is the Python implementation for Background subtraction –




# importing libraries
import numpy as np
import cv2
  
# creating object
fgbg1 = cv2.bgsegm.createBackgroundSubtractorMOG();   
fgbg2 = cv2.createBackgroundSubtractorMOG2();
fgbg3 = cv2.bgsegm.createBackgroundSubtractorGMG();
  
# capture frames from a camera 
cap = cv2.VideoCapture(0);
while(1):
    # read frames
    ret, img = cap.read();
      
    # apply mask for background subtraction
    fgmask1 = fgbg1.apply(img);
    fgmask2 = fgbg2.apply(img);
    fgmask3 = fgbg3.apply(img);
      
    cv2.imshow('Original', img);
    cv2.imshow('MOG', fgmask1);
    cv2.imshow('MOG2', fgmask2);
    cv2.imshow('GMG', fgmask3);
    k = cv2.waitKey(30) & 0xff;
    if k == 27:
        break;
  
cap.release();
cv2.destroyAllWindows();


Output:

 

We can see that there is a lot of noise in the resultant image for BackgroundSubtractorGMG, hence it is always preferred to use morphological transformation to the result to remove the noises.




# importing libraries
import numpy as np
import cv2
  
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3));
  
# creating object
fgbg = cv2.bgsegm.createBackgroundSubtractorGMG();
  
# capture frames from a camera 
cap = cv2.VideoCapture(0);
while(1):
    # read frames
    ret, img = cap.read();
      
    # apply mask for background subtraction
    fgmask = fgbg.apply(img);
      
    # with noise frame
    cv2.imshow('GMG noise', fgmask);
      
    # apply transformation to remove noise
    fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel);
      
    # after removing noise
    cv2.imshow('GMG', fgmask);
      
    k = cv2.waitKey(30) & 0xff;
    if k == 27:
        break;
  
cap.release();
cv2.destroyAllWindows();


Output:



Previous Article
Next Article

Similar Reads

Python | Background subtraction using OpenCV
Background Subtraction has several use cases in everyday life, It is being used for object segmentation, security enhancement, pedestrian tracking, counting the number of visitors, number of vehicles in traffic etc. It is able to learn and identify the foreground mask.As the name suggests, it is able to subtract or eliminate the background portion
2 min read
Python OpenCV - Background Subtraction
Background Subtraction is one of the major Image Processing tasks. It is used in various Image Processing applications like Image Segmentation, Object Detection, etc. OpenCV provides us 3 types of Background Subtraction algorithms:- BackgroundSubtractorMOG BackgroundSubtractorMOG2 BackgroundSubtractorGMG Normally, we can perform background Subtract
2 min read
Arithmetic Operations on Images using OpenCV | Set-1 (Addition and Subtraction)
Arithmetic Operations like Addition, Subtraction, and Bitwise Operations(AND, OR, NOT, XOR) can be applied to the input images. These operations can be helpful in enhancing the properties of the input images. The Image arithmetics are important for analyzing the input image properties. The operated images can be further used as an enhanced input im
3 min read
Background Subtraction in an Image using Concept of Running Average
Background subtraction is a technique for separating out foreground elements from the background and is done by generating a foreground mask. This technique is used for detecting dynamically moving objects from static cameras. Background subtraction technique is important for object tracking. There are several techniques for background subtraction
4 min read
Project Idea | Motion detection using Background Subtraction Techniques
Foreground detection based on video streams is the first step in computer vision applications, including real-time tracking and event analysis. Many researchers in the field of image and video semantics analysis pay attention to intelligent video surveillance in residential areas, junctions, shopping malls, subways, and airports which are closely a
4 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Removing Black Background and Make Transparent using Python OpenCV
In this article, we will discuss how to remove the black background and make it transparent in Python OpenCV. cv2.cvtColor method cv2.cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV. Syntax: cv2.cvtColor(src, code[, dst[, dstCn]]) Parameters: s
2 min read
Addition and Subtraction on TimeDelta objects using Pandas - Python
TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. Operations on TimeDelta dataframe or series - 1) Addition - df['Result'] = df['TimeDelta1']
2 min read
Perform addition and subtraction using CherryPy
CherryPy also known as a web application library is a Python web framework that provides a friendly interface to the HTTP protocol for Python developers. It allows developers to build web applications the same way as in traditional object-oriented Python programs. Thereby, resulting in smaller source code developed in no time. This framework is mai
2 min read
How to perform element-wise subtraction on tensors in PyTorch?
In this article, we are going to understand how to perform element-wise subtraction on tensors in PyTorch in Python. We can perform element-wise subtraction using torch.sub() method. torch.sub() method allows us to perform subtraction on the same or different dimensions of tensors. It takes two tensors as the inputs and returns a new tensor with th
3 min read
OpenCV C++ Program to play a video
The following is the explanation to the C++ code to play a video in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) To run in windows, please use the file: 'play_video.o' and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and
3 min read
OpenCV C++ Program to create a single colored blank image
The following is the explanation to the C++ code to create a single colored blank image in C++ using the tool OpenCV. Things to know:  (1) The code will only compile in Linux environment. (2) To run in windows, please use the file: 'blank.o' and run it in cmd. However if it does not run (problem in system architecture) then compile it in windows by
3 min read
OpenCV C++ Program to blur an image
The following is the explanation to the C++ code to blur an Image in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) Compile command: g++ -w article.cpp -o article `pkg-config --libs opencv` (3) Run command: ./article (4) The image bat.jpg has to be in the same directory as the code. Before you ru
5 min read
OpenCV C++ Program for coin detection
The following is the explanation to the C++ code for coin detection in C++ using the tool OpenCV. Things to know: The code will only compile in Linux environment. To run in windows, please use the file: 'coin.o' and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious ch
4 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Set up Opencv with anaconda environment
If you love working on image processing and video analysis using python then you have come to the right place. Python is one of the major languages that can be used to process images or videos. Requirements for OpenCV and Anaconda - 32- or a 64-bit computer. - For Miniconda—400 MB disk space. - For Anaconda—A minimum 3 GB disk space to download and
3 min read
OpenCV: Segmentation using Thresholding
In this article, a basic technique for object segmentation called Thresholding. But before moving into anymore detail, below is a brief overview of OpenCV. OpenCV (Open Source Computer Vision) is a cross platform, open-source library of programming functions, aimed at performing real-time computer vision tasks in a wide variety of fields, such as:
5 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
2 min read
Draw geometric shapes on images using OpenCV
OpenCV provides many drawing functions to draw geometric shapes and write text on images. Let's see some of the drawing functions and draw geometric shapes on images using OpenCV. Some of the drawing functions are : cv2.line() : Used to draw line on an image. cv2.rectangle() : Used to draw rectangle on an image. cv2.circle() : Used to draw circle o
3 min read
Python | Play a video in reverse mode using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV's application areas include : 1) Facial recognition system 2) motion tracking 3) Artificial neural network 4) Deep neural network 5) video streaming etc. In Python, one can use an OpenCV library named C
3 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Opening multiple color windows to capture using OpenCV in Python
OpenCV is an open source computer vision library that works with many programming languages and provides a vast scope to understand the subject of computer vision.In this example we will use OpenCV to open the camera of the system and capture the video in two different colors. Approach: With the libraries available in OpenCV-Python below we will op
2 min read
Converting Color video to grayscale using OpenCV in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format. Approach: Import the cv2 module.Read the video file to be converted usi
1 min read
Python | Detect corner of an image using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi metho
2 min read
Image Pyramid using OpenCV | Python
Image Pyramids are one of the most beautiful concept of image processing.Normally, we work with images with default resolution but many times we need to change the resolution (lower it) or resize the original image in that case image pyramids comes handy. The pyrUp() function increases the size to double of its original size and pyrDown() function
1 min read
Face Detection using Python and OpenCV with webcam
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
4 min read