How to save masks of videos in openCV2 python

陌路散爱 提交于 2020-01-01 14:49:07

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/28049295/how-to-save-masks-of-videos-in-opencv2-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!