Showing posts with label Background Subtraction. Show all posts
Showing posts with label Background Subtraction. Show all posts

2012-10-24

OpenCV Background Subtraction in Python

Recently, I tried  finding an example of Background Subtraction being done in OpenCV and Python without success. The code is not complicated or special in any way. However, I guess, the example might be helpful, if you want to get started with Background Subtraction quickly.

The script reads a video file and writes out a mask for every frame.
#!/usr/bin/env python
#-*- encoding: utf-8 -*-

import cv2
import numpy

bgs = cv2.BackgroundSubtractorMOG(24*60, 1, 0.9, 0.01)

capture = cv2.VideoCapture("00185.MTS.mp4")
cv2.namedWindow("input")

a = 0
while(True):
    
    f, img = capture.read()
    fgmask = bgs.apply(img)
    
    #cv2.imshow("input", fgmask)
    #cv2.waitKey(1)
    cv2.imwrite("./pngs/image-"+str(a).zfill(5)+".png", fgmask)

    a = a + 1
    print(a)

Unfortunately there seem to be no Python bindings for BackgroundSubtractorMOG2 at the time of this writing.