Skip to content
Advertisement

How to create a video out of frames without saving it to disk using python?

I have a function that returns a frame as result. I wanted to know how to make a video out of a for-loop with this function without saving every frame and then creating the video.

What I have from now is something similar to:

JavaScript

Then the video will be created as video.mp4 and I can access it on memory. I’m asking myself if there’s a way to have this video in a variable that I can easily convert to bytes later. My purpose for that is to send the video via HTTP post.

I’ve looked on ffmpeg-python and opencv but I didn’t find anything that applies to my case.

Advertisement

Answer

We may use PyAV for encoding “in memory file”.

PyAV is a Pythonic binding for the FFmpeg libraries.
The interface is relatively low level, but it allows us to do things that are not possible using other FFmpeg bindings.

Here are the main stages for creating MP4 in memory using PyAV:

  • Create BytesIO “in memory file”:

    JavaScript
  • Use PyAV to open “in memory file” as MP4 video output file:

    JavaScript
  • Add H.264 video stream to the MP4 container, and set codec parameters:

    JavaScript
  • Iterate the OpenCV images, convert image to PyAV VideoFrame, encode, and “Mux”:

    JavaScript
  • Flush the encoder and close the “in memory” file:

    JavaScript

The following code samples encode 100 synthetic images to “in memory” MP4 memory file.
Each synthetic image applies OpenCV image, with sequential blue frame number (used for testing).
At the end, the memory file is written to output.mp4 file for testing.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement