Theory
Background Separation (BS) is a common technique for generating a foreground mask (a binary image containing pixels belonging to moving objects in the scene) by using a static camera
As the name suggests, BS calculates the foreground mask, performing a subtraction operation between the current frame and the background model, which contains the static part of the scene, which can be viewed as as background for everything.
Background modeling includes two main steps:
- ##1. Background initialization
- 2. Background update The first step is to calculate the initial model of the background. In the second step, the model is updated to adapt to possible changes in the scene
cv2.BackgroundSubtractorMOG2 will be used to generate the foreground mask.
from __future__ import print_function import cv2 import argparse parser = argparse.ArgumentParser( description='This program shows how to use background subtraction methods provided by OpenCV. You can process both videos and images.') parser.add_argument('--input', type=str, help='Path to a video or a sequence of image.', default='vtest.avi') parser.add_argument('--algo', type=str, help='Background subtraction method (KNN, MOG2).', default='MOG2') args = parser.parse_args() ## [create] # create Background Subtractor objects if args.algo == 'MOG2': backSub = cv2.createBackgroundSubtractorMOG2() else: backSub = cv2.createBackgroundSubtractorKNN() ## [create] ## [capture] capture = cv2.VideoCapture(args.input) if not capture.isOpened(): print('Unable to open: ' + args.input) exit(0) ## [capture] while True: ret, frame = capture.read() if frame is None: break ## [apply] # update the background model fgMask = backSub.apply(frame) ## [apply] ## [display_frame_number] # get the frame number and write it on the current frame cv2.rectangle(frame, (10, 2), (100,20), (255,255,255), -1) cv2.putText(frame, str(capture.get(cv2.CAP_PROP_POS_FRAMES)), (15, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,0)) ## [display_frame_number] ## [show] # show the current frame and the fg masks cv2.imshow('Frame', frame) cv2.imshow('FG Mask', fgMask) ## [show] keyboard = cv2.waitKey(30) if keyboard == 'q' or keyboard == 27: breakCode analysisAnalyze the main part of the above code:
- ##cv2.BackgroundSubtractor
The object will be used to generate the foreground mask code. In this example, default parameters are used, but specific parameters can also be declared in the
create
function.# create Background Subtractor objects KNN or MOG2 if args.algo == 'MOG2': backSub = cv2.createBackgroundSubtractorMOG2() else: backSub = cv2.createBackgroundSubtractorKNN()
- cv2.VideoCapture
Object is used to read input video or input image sequence
capture = cv2.VideoCapture(args.input) if not capture.isOpened: print('Unable to open: ' + args.input) exit(0)
- Each frame is used to calculate the foreground mask and update the background
. If you want to change the learning rate used to update the background model, you can set a specific learning rate by passing arguments to the apply method
# update the background model fgMask = backSub.apply(frame)
- The current frame number can be extracted from the
- cv2.Videocapture
object and punched in the upper left corner of the current frame. Use a white rectangle to highlight the black frame number
# get the frame number and write it on the current frame cv2.rectangle(frame, (10, 2), (100,20), (255,255,255), -1) cv2.putText(frame, str(capture.get(cv2.CAP_PROP_POS_FRAMES)), (15, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,0))
- Display the current input frame and results
-
# show the current frame and the fg masks cv2.imshow('Frame', frame) cv2.imshow('FG Mask', fgMask)
The above is the detailed content of How does python OpenCV use the background separation method?. For more information, please follow other related articles on the PHP Chinese website!

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor