Ask Your Question
0

How do I save a video with background subtraction applied

asked 2019-01-05 10:37:04 -0500

christa gravatar image

updated 2019-01-05 10:59:42 -0500

berak gravatar image

.

import numpy as np
import cv2 as cv
cap = cv.VideoCapture('testvid.mov')
fgbg = cv.createBackgroundSubtractorMOG2()
while(1):
    ret, frame = cap.read()
    fgmask = fgbg.apply(frame)
    cv.imshow('frame',fgmask)
    k = cv.waitKey(30) & 0xff
    if k == 27:
        break
cap.release()

cv.destroyAllWindows()

I have this working, however cant figure out how to save it once BGS has been applied?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2019-01-06 05:25:31 -0500

LBerger gravatar image

updated 2019-01-06 05:49:23 -0500

You can extract foreground and backgroung from original image using copyTo` :

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
ret, frame = cap.read()
if ret is False:
    print("Cannot read video stream")
    exit()
myvideo=cv.VideoWriter("forground.avi", cv.VideoWriter_fourcc('M','J','P','G'), 30, (int(frame.shape[1]),int(frame.shape[0])))
fgbg = cv.createBackgroundSubtractorMOG2()
while(1):
    ret, frame = cap.read()
    if ret is False:
        print("Cannot read video stream")
        exit()    
    fgmask = fgbg.apply(frame)
    cv.imshow('frame',fgmask)
    fg = cv.copyTo(frame,fgmask)
    myvideo.write(fg)
    cv.imshow('Foreground',fg)
    cv.imshow('Background',cv.copyTo(frame,cv.bitwise_not(fgmask)))
    k = cv.waitKey(30) & 0xff
    if k == 27:
        break
cap.release()
myvideo.release()
cv.destroyAllWindows()

My answer is good with opencv >=4.0 (you have to build opencv yourself) If opencv version is <4.0 you can use code given in this issue for copyTo

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2019-01-05 10:37:04 -0500

Seen: 429 times

Last updated: Jan 06 '19