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.

2 comments:

  1. back ground subtraction directly from cam
    am gettin error
    code is

    import cv2
    import numpy

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

    capture = cv2.VideoCapture(0)
    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

    ReplyDelete
  2. creat-tabu:

    Try capture = cv2.VideoCapture(-1) instead of (0).

    ALSO uncomment the cv2.waitKey(1) line...

    ...without that OpenCV will not run in a loop.

    The WaitKey(ms) command is the command
    that makes all the other events fire/update...

    ...something like that. ;]

    Neat code, small!

    ReplyDelete