Background subtractors – KNN, MOG2, and GMG

OpenCV provides a class called BackgroundSubtractor, which is a handy way to operate foreground and background segmentation.

This works similarly to the GrabCut algorithm we analyzed in Chapter 3, Processing Images with OpenCV 3, however, BackgroundSubtractor is a fully fledged class with a plethora of methods that not only perform background subtraction, but also improve background detection in time through machine learning and lets you save the classifier to a file.

To familiarize ourselves with BackgroundSubtractor, let's look at a basic example:

import numpy as np import cv2 cap = cv2.VideoCapture') mog = cv2.createBackgroundSubtractorMOG2() while(1): ret, frame = cap.read() fgmask = mog.apply(frame) ...

Get Learning OpenCV 3 Computer Vision with Python - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.