How to save Background Subtraction MOG to reuse between executions

asked 2015-05-06 10:19:21 -0600

joanmanel gravatar image

I have the classic Python code for Background Substraction MOG (OpenCV 2.x) and it works well:

backsub = cv2.BackgroundSubtractorMOG()
capture = cv2.VideoCapture(filename)
While True:
    ret, frame = capture.read()
    fgmask = backsub.apply(frame, None, 0,005)

I know there are some parts missing, like checking if frame is something and so, but this is the backbone, and it does work.

What I would like to do is to save the BackgroundSubtractorMOG in some file, and then reuse again when I execute the code some time later.

I have an script that records 1 minute videos and then it runs the backsub. The problem with my current method is that I lose around 3s of video while it tries to guess what is background and what is not, so that is why I would like to reuse the previous information, to be more efficient.

I tried to pickle backsub, and it says it cannot be pickled.

edit retag flag offensive close merge delete

Comments

In opencv 3.0 :

cv::Ptr<cv::BackgroundSubtractor> b;
b = cv::bgsegm::createBackgroundSubtractorMOG(); 
....
b.dynamicCast<cv::bgsegm::BackgroundSubtractorMOG>()->getBackgroundImage(*imgBack);

(DynamicCast is not usefull but it is my orignal code) May be you are not in opencv 3.0

LBerger gravatar imageLBerger ( 2015-05-06 13:12:47 -0600 )edit

shame, but you cannot serialize the state of it. (also, no- you cannot pickle cv2 objects)

berak gravatar imageberak ( 2015-05-07 01:03:29 -0600 )edit
1

If you lose 3s at the beginning may be you can try to read in reverse order and try to mix results.

LBerger gravatar imageLBerger ( 2015-05-07 01:28:14 -0600 )edit

I have tried 'deepcopy' and 'pickle' to make a copy or write it to file, but it couldn't find BackgroundSubtractorMOG2 on cv2

bestzxp gravatar imagebestzxp ( 2017-09-12 21:54:58 -0600 )edit