jeffpkamp
jeffpkamp

Reputation: 2856

Sending OpenCV2 Videowrite input to buffer instead of file

I would like to write openCV2 videorecorder output to a buffer in the memory rather than to a file on my hard drive. Following that i could write out to a file or not (and this way save a flash based object from over use). I've tried pyfilesystem and i've tried things like IO and StringIO, but VideoRecorder does not accept these saying it was looking for a String or Unicode type and instead found a (_IOTextWrapper, IOString, etc....) type.

Upvotes: 2

Views: 4337

Answers (1)

ljetibo
ljetibo

Reputation: 3094

I get now what you mean, however that would somehow tend to break the purpose of VideoWriter I suppose. It's job is to write the video on the disk. However, I agree, it would be nice to have a Video class that then we could manipulate within cv2.

Meanwhile, lucky for us, video's are nothing but sequences of frames, which are but numpy arrays. We can do a lot with those so here's the general idea I'd propose:

import numpy as np
import cv2

def save_to_vid(video):
    path = ".../output.avi"
    height , width , layers =  video[0].shape
    out = cv2.VideoWriter(path, cv2.cv.FOURCC("X", "V", "I", "D"),
                          20.0, (width, height))
    for frame in frames:
        out.write(frame)

    out.release()


##CAPTURING SOME TEST FRAMES
cap = cv2.VideoCapture(0)
frames = list() #THIS IS YOUR VIDEO
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)
        frames.append(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

#SOMETIMES LATER IN THE RPOGRAM
doYouWantToSave = True
if doYouWantToSave:
    save_to_vid(frames)
else:
    del frames

Of course this all can be done smarter I suppose by creating your own class Video and then instantiating that and handling it as an object in your code. Video could have a method "writeToFile" as well. It could even be scripted a bit smarter to save some space, or work as an actual buffer if that's exactly what you need.

Upvotes: 1

Related Questions