Book Image

Learning OpenCV 3 Computer Vision with Python (Update)

Book Image

Learning OpenCV 3 Computer Vision with Python (Update)

Overview of this book

Table of Contents (16 chapters)
Learning OpenCV 3 Computer Vision with Python Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
6
Retrieving Images and Searching Using Image Descriptors
Index

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)
    cv2.imshow('frame',fgmask)
    if cv2.waitKey(30) & 0xff:
        break

cap.release()
cv2.destroyAllWindows()

Let's go through this in order. First of all, let's talk about the background subtractor object. There are three background...