Ask Your Question
1

backgroundsubtractormog with python

asked Jul 28 '13

VoidMee gravatar image

updated Jul 28 '13

berak gravatar image

Hello, I want to use backgroundsubtractormog with python so my code is this

import cv2
import numpy as np

winname = "GRS"

bgs_mog = cv2.BackgroundSubtractorMOG(500, 6, 0.9, 1)

capture = cv2.VideoCapture(0)

frame = capture.read()[1]

if __name__ == "__main__":
    while frame != None:
        #fgmask = bgs_mog.apply(frame)
        cv2.imshow(winname, frame)
        c = cv2.waitKey(1)
        if c == 27:
            cv2.destroyWindow(winname)
            break
        frame = capture.read()[1]
    cv2.destroyAllWindows()

The output I am having is some mask of binary images. But I want only coloured image of moving objects. I do not know how to implement this mask to get the coloured image of moving objects only. I have referred the opencv2refman doc about this function but I am no getting clear about how to determine the parameters for mog constructor. Can somebody explain how to do this, Plz. Thanks

Preview: (hide)

1 answer

Sort by » oldest newest most voted
2

answered Jul 28 '13

berak gravatar image

updated Jul 28 '13

so, you get the fg mask.

fgmask = bgs_mog.apply(frame)

now this is an 8bit 1channel mat. to apply it to the frame (rgb) image, we need to convert the mask to rbg, too:

mask_rbg = cv2.cvtColor(fgmask,cv2.COLOR_GRAY2BGR)

then we can "and" it into a drawing image:

draw = frame & mask_rbg

the whole thing, again:

import cv2
import numpy as np

winname = "GRS"
bgs_mog = cv2.BackgroundSubtractorMOG(500, 6, 0.9, .1)
capture = cv2.VideoCapture(0)

if __name__ == "__main__":
    while capture.isOpened():
        _,frame = capture.read()
        fgmask = bgs_mog.apply(frame)
        mask_rbg = cv2.cvtColor(fgmask,cv2.COLOR_GRAY2BGR)
        draw = frame & mask_rbg
        cv2.imshow(winname, draw)
        c = cv2.waitKey(1)
        if c == 27:
            break
    cv2.destroyAllWindows()
Preview: (hide)

Comments

thanx, really appreciated your help. what a silly thing I did not know. :)

VoidMee gravatar imageVoidMee (Jul 28 '13)edit

nice structured answer :) we should really consider a code snippet area with stuff like this :)

StevenPuttemans gravatar imageStevenPuttemans (Jul 28 '13)edit

Question Tools

Stats

Asked: Jul 28 '13

Seen: 5,528 times

Last updated: Jul 28 '13