Background subtraction in opencv python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Background Subtraction with OpenCV and BGS Libraries

License

WorqHat/Background-Subtraction-with-Python

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Background Subtraction with OpenCV and BGS Libraries

Please, follow the instructions to set up the environment for Linux-based systems. This installation guide is based on the official instruction, with some additions and corrections.

If you are using Windows OS follow the Building BGSLibrary with Python support on Windows section from the same instruction.

Our code is tested using Python 3.7.5, but it should also work with any other python3.x. If you’d like to check your version run:

Note: We assume, that your current location is learnopencv/Background-Subtraction and will refer it as work_dir .

Let’s create a new virtual environment. You’ll need to install virtualenv package if you don’t have it:

Now we can create a new virtualenv variable and call it env :

python3.7 -m virtualenv venv

The last thing we have to do is to activate it:

To will need also to install numpy package:

In this blog post we are using BGS Library, which is heavily based on OpenCV. That is why, we first need to build the OpenCV library. To do so:

sudo apt-get update sudo apt-get install build-essential cmake unzip pkg-config sudo apt-get install libjpeg-dev libpng-dev libtiff-dev sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev sudo apt-get install libxvidcore-dev libx264-dev sudo apt-get install libgtk-3-dev sudo apt-get install libatlas-base-dev gfortran sudo apt-get install python3-dev
cd ~ wget -O opencv.zip https://github.com/opencv/opencv/archive/4.3.0.zip wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.3.0.zip
unzip opencv.zip unzip opencv_contrib.zip
mv opencv-4.3.0 opencv mv opencv_contrib-4.3.0 opencv_contrib
cd ~/opencv mkdir build cd build

Run CMake to configure the OpenCV build. Don’t forget to set the right pass to the PYTHON_EXECUTABLE .

cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D INSTALL_C_EXAMPLES=OFF \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D PYTHON_EXECUTABLE=work_dir/venv/bin/python3 \ -D OPENCV_GENERATE_PKGCONFIG=ON \ -D BUILD_EXAMPLES=ON ..

Check the output and make sure that everything is set correctly. After that we are ready to build it with:

Читайте также:  Python list files with path

Make sure, you didn’t get any errors. Then run the following commands:

sudo make install sudo ldconfig

which creates the necessary links and cache to our freshly-built shared library.

Put lib/python3/cv2.cpython-37m-x86_64-linux-gnu.so into the virtual environment installed packages:

cp lib/python3/cv2.cpython-37m-x86_64-linux-gnu.so work_dir/venv/lib/python3.7/site-packages/cv2.so

Now everything is ready to build BGS Library.

cd work_dir git clone --recursive https://github.com/andrewssobral/bgslibrary.git
cd bgslibrary mkdir build && cd build
  1. Run CMake to configure the build. Don’t forget to set PYTHON_EXECUTABLE to your virtual environment python.
cmake -D BGS_PYTHON_SUPPORT=ON\ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D OpenCV_DIR=~/opencv/build \ -D PYTHON_EXECUTABLE=work_dir/venv/bin/python ..
  1. Check the output. Pay attention to the Python library status section. It should look similar to this:
-- Python library status: -- executable: ~/env/bin/python -- library: ~/.pyenv/versions/3.7.5/lib/libpython3.7m.so -- include path: ~/.pyenv/versions/3.7.5/include/python3.7m

Make sure, that your python library is build as a shared library (.so file), not as a static (.a file). That might cause an error if you are using pyenv, that builds python library as a static library by default. To rebuild it as a shared library, run:

PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install --force 3.7.5
  1. Make sure, you didn’t get any errors. You can check, that everything is working by running the demo script:

The proposed for experiments background_subtr_opencv.py and background_subtr_bgslib.py scripts support —input_video key to customize the background subtraction pipeline. —input_video contains the path to the input video. By default its value is «space_traffic.mp4» . Please, follow the below instructions for each case.

To run OpenCV case, please, choose one of the described below scenarios:

python3 background_subtr_opencv.py
python3 background_subtr_opencv.py --input_video VIDEO_PATH>

To run BGSLibrary case, please, choose one of the described below scenarios:

python3 background_subtr_bgslib.py
python3 background_subtr_bgslib.py --input_video VIDEO_PATH>

The first step is compiling of the proposed .cpp files with the appropriate commands for each case.

To compile background_subtr_opencv.cpp you need to run the below command:

g++ background_subtr_opencv.cpp `pkg-config --cflags --libs opencv4` -o background_subtr_opencv.out -std=c++11

After background_subtr_opencv.out was obtained, we can run the BS-pipeline:

./background_subtr_opencv.out

By default space_traffic.mp4 will be used. To provide another video as input, you need to define —input key value:

./background_subtr_opencv.out --input=VIDEO_PATH>

To compile background_subtr_bgslib.cpp you need to run the below command:

g++ background_subtr_bgslib.cpp `pkg-config --cflags --libs opencv4` -lbgslibrary_core -I bgslibrary/src -o background_subtr_bgslib.out -std=c++11

After background_subtr_bgslib.out was obtained, we can run the BS-pipeline:

./background_subtr_bgslib.out

By default space_traffic.mp4 will be used. To provide another video as input, you need to define —input key value:

./background_subtr_bgslib.out --input=VIDEO_PATH>

Want to become an expert in AI? AI Courses by OpenCV is a great place to start.

About

Background Subtraction with OpenCV and BGS Libraries

Источник

Background subtraction in opencv python

  • 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_Subtraction_Tutorial_Scheme.png

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.

Goals

In this tutorial you will learn how to:

  1. Read data from videos or image sequences by using cv::VideoCapture ;
  2. Create and update the background model by using cv::BackgroundSubtractor class;
  3. Get and show the foreground mask by using cv::imshow ;

Code

In the following you can find the source code. We will let the user choose to process either a video file or a sequence of images.

We will use cv::BackgroundSubtractorMOG2 in this sample, to generate the foreground mask.

The results as well as the input data are shown on the screen.

Источник

Background Subtraction OpenCV Python Using MOG2 and KNN Read it later

In this blog, we will learn about the basics of background subtraction and how to implement it in OpenCV using Python.

What is Background Subtraction?

Background subtraction is a technique used to separate the foreground from the background in a video stream.

The basic idea is to subtract the background image from the current frame of the video stream to obtain the foreground objects.

The background image can either be a static image or a dynamically updated image that adapts to changes in the scene.

Resulting foreground objects can then be used for further processing, such as object detection or tracking.

Why is Background Subtraction Important?

Background subtraction is an essential step in many computer vision and image processing applications. Here are some of the reasons why it’s important:

  1. Object Detection: Background subtraction is a critical step in object detection, which is used in surveillance systems, traffic monitoring, and other applications.
  2. Motion Analysis: Background subtraction can be used to track motion in a video sequence, which is important in applications such as human-computer interaction, sports analysis, and medical imaging.
  3. Image Segmentation: Background subtraction can be used as a preprocessing step for image segmentation, which is used in computer vision applications such as face recognition, object recognition, and scene understanding.

Types of Background Subtraction

There are several types of background subtraction algorithms, each with its strengths and weaknesses. Some of the most commonly used algorithms are:

  1. Gaussian Mixture-based Background/Foreground Segmentation Algorithm (MOG2)
  2. Adaptive Background Mixture Model (ABM):
  3. Codebook-based Background Subtraction (CBBS)
  4. Approximate Median Filter-based Background Subtraction (AMF)

Background Subtraction using OpenCV Python

In this section, we will demonstrate how to perform background subtraction using OpenCV and Python.

Read Video Stream

We can create an instance of the VideoCapture class and pass the path of the video file or the camera index as an argument. The camera index is usually 0 for the default camera.

First, we need to read the video stream from a camera or a file. OpenCV provides the VideoCapture function for this purpose.

import cv2 cap = cv2.VideoCapture(0) # Read video stream from default camera

Applying Background Subtraction OpenCV Python

Next, we need to apply background subtraction to the video stream.

OpenCV provides several functions for this purpose, such as createBackgroundSubtractorMOG2, createBackgroundSubtractorKNN, etc.

We can choose any of these functions based on our requirements.

# Create a background subtractor object using MOG2 algorithm fgbg = cv2.createBackgroundSubtractorMOG2() while True: # Read a frame from the video stream ret, frame = cap.read() if not ret: break # Apply background subtraction to the current frame fgmask = fgbg.apply(frame) # Display the foreground mask cv2.imshow('Foreground Mask', fgmask) # Exit if 'q' is pressed if cv2.waitKey(1) == ord('q'): break # Release the video stream and destroy all windows cap.release() cv2.destroyAllWindows()

In the above code, we create an instance of the MOG2 background subtractor using the cv2.createBackgroundSubtractorMOG2() function. We then read a frame from the video stream using the cap.read() function and apply the background subtraction using the fgbg.apply(frame) function. The resulting foreground mask is displayed using the cv2.imshow() function. Finally, we release the video stream using the cap.release() function and destroy all windows using the cv2.destroyAllWindows() function.

Источник

Оцените статью