Life2Coding
Convert Image Frames to Video File using OpenCV in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to merge or convert several frames to a video by combing the image frames using OpenCV library and Python coding.

Documentation:

Python: cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) → <VideoWriter object>

Python: cv2.VideoWriter.write(image) → None

Write image frames to a video file

Parameters:          

  • filename – Name of the output video file.
  • fourcc – 4-character code of codec used to compress the frames. List of codes can be obtained at Video Codecs by FOURCC page.
    • VideoWriter_fourcc(c1, c2, c3, c4) → retval
  • fps – Framerate of the created video stream.
  • frameSize – Size of the video frames.
  • isColor – If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only).

Steps:

  • Read each image using cv2.imread()
  • Initialize the video writer using cv2.VideoWriter()
  • Save the frames to a video file using cv2.VideoWriter.write()
  • Wait for keyboard button press using cv2.waitKey()
  • Release the VideoWriter using cv2.VideoWriter.release()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np
import os

from os.path import isfile, join

def convert_frames_to_video(pathIn,pathOut,fps):
    frame_array = []
    files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]

    #for sorting the file names properly
    files.sort(key = lambda x: int(x[5:-4]))

    for i in range(len(files)):
        filename=pathIn + files[i]
        #reading each files
        img = cv2.imread(filename)
        height, width, layers = img.shape
        size = (width,height)
        print(filename)
        #inserting the frames into an image array
        frame_array.append(img)

    out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)

    for i in range(len(frame_array)):
        # writing to a image array
        out.write(frame_array[i])
    out.release()

def main():
    pathIn= './data/'
    pathOut = 'video.avi'
    fps = 25.0
    convert_frames_to_video(pathIn, pathOut, fps)

if __name__=="__main__":
    main()

Output:

Capture-1 Convert Image Frames to Video File using OpenCV in Python

Final Output

d Convert Image Frames to Video File using OpenCV in Python

life2coding_icon [] Convert Image Frames to Video File using OpenCV in Python

7 thoughts on “Convert Image Frames to Video File using OpenCV in Python

  1. Khalid Amin

    I tried running the example code, and the output video contained only the last frame … any ideas to what may be the problem ?

    1. Sadie Parker

      Hi, I had a similar problem. It turned out that a few of my images were slightly different sizes. It worked for me when all the images were the same size.

      I also used XVID instead of DIVX for the fourcc — I don’t think this is what fixed it, but just noting here to be thorough

    1. Life2Coding Post author

      Please rename your images like the way it was shown in the output images. Like “frame1, frame2, frame3”. Then it will get the numbers for sorting the frames.

  2. Brady Juagn

    Hi,

    One thing I noticed about this that can be fixed is that it stores every single image into memory, when running on longer videos (2 minutes+) at 30 fps at 8 gigs of RAM, there is the potential to run out of memory.

    To fix this you can try to run it so it stores one image at a time, storing them into a list that compiles into a video so it consumes much less memory.

  3. Alex Silkin

    Hey, thanks for this code example!

    Question: I’m a bit confused about the scope of the variables ‘size’ and ‘out’ in line

    “out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*’DIVX’), fps, size)”

    When I run this code I receive an error
    “UnboundLocalError: local variable ‘size’ referenced before assignment”

    At what point should I be defining the variable ‘size’? Or am I misunderstanding the error?

    Thanks in advance for your help!

    1. Alex Silkin

      Ahhh! I figured out my issue! There was a problem with spacing/indentation that placed the size variable outside of scope of the
      ‘out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*’DIVX’), fps, size)’ line.

      Thanks again for this code!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.