Python creating video from images using opencv

You can use this pip package. It provides CLI commands to make video from images.

img_to_vid.py -f images_directory


You can read the frames and write them to video in a loop. Following is your code with a small modification to remove one for loop.

  import cv2
  import numpy as np
  
  # choose codec according to format needed
  fourcc = cv2.VideoWriter_fourcc(*'mp4v') 
  video = cv2.VideoWriter('video.avi', fourcc, 1, (width, height))

  for j in range(0,5):
     img = cv2.imread(str(i) + '.png')
     video.write(img)

  cv2.destroyAllWindows()
  video.release()

Alternatively, you can use skvideo library to create video form sequence of images.

  import numpy as np
  import skvideo.io
   
  out_video =  np.empty([5, height, width, 3], dtype = np.uint8)
  out_video =  out_video.astype(np.uint8)
  
  for i in range(5):
      img = cv2.imread(str(i) + '.png')
      out_video[i] = img

  # Writes the the output image sequences in a video file
  skvideo.io.vwrite("video.mp4", out_video)

  

You are writing the whole array of frames. Try to save frame by frame instead:

...
for j in range(0,5):
  video.write(img[j])
...

reference

Tags:

Python

Opencv