Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save masks of videos in openCV2 python

I can capture a video from the webcam and save it fine with this code

cap = cv2.VideoCapture(0)
fgbg= cv2.BackgroundSubtractorMOG()

fourcc = cv2.cv.CV_FOURCC(*'DIVX')
out    = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret,frame = cap.read()
    if ret:
        fgmask = fgbg.apply(frame)
        out.write(frame)          #Save it                                      
        cv2.imshow('Background Subtraction', fgmask)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break                 #q to quit                                    
    else:
        break                     #EOF                                          

cap.release()
out.release()
cv2.destroyAllWindows()

This records it as one would expect, and shows the background subtraction thing also. It saves it to output.avi. All is well. But I can't save the foreground mask, it gives me a Could not demultiplex stream error. (This line is changed in the code above).

out.write(fgmask)          #Save it    

Why is this? Is the fgmask not a frame like when I am reading from the capture?

like image 356
SetSlapShot Avatar asked Mar 17 '23 07:03

SetSlapShot


1 Answers

Alright figured it out! Let me know if there's a more efficient way to do this or if I am missing something..

The foreground mask generated in background subtraction is an 8bit binary image, so we have to convert it to a different format. Probably a better one exists, but I used RGB

frame = cv2.cvtColor(fgmask, cv2.COLOR_GRAY2RGB)
like image 147
SetSlapShot Avatar answered Mar 28 '23 17:03

SetSlapShot