Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python creating video from images using opencv

Tags:

python

opencv

I was trying to create a video to show the dynamic variation of the data, like just continuously showing the images one by one quickly, so I used images (the images just called 1,2,3,4,.....) and wrote the following code:

import cv2
import numpy as np

img=[]
for i in range(0,5):
    img.append(cv2.imread(str(i)+'.png'))

height,width,layers=img[1].shape

video=cv2.VideoWriter('video.avi',-1,1,(width,height))

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

cv2.destroyAllWindows()
video.release()

and a error was raised:

TypeError: image is not a numpy array, neither a scalar

I think I used the list in a wrong way but I'm not sure. So where did I do wrong?

like image 828
Yingqiang Gao Avatar asked Mar 27 '17 14:03

Yingqiang Gao


People also ask

Can OpenCV capture video?

Capture Video from CameraOpenCV allows a straightforward interface to capture live stream with the camera (webcam). It converts video into grayscale and display it. We need to create a VideoCapture object to capture a video. It accepts either the device index or the name of a video file.

How do I record video on cv2?

To capture a video in Python, use the cv2 VideoCapture class and then create an object of VideoCapture. VideoCapture has the device index or the name of a video file. The device index is just an integer to define a Camera. If we pass 0, it is for the first or primary camera, 1 for the second camera, etc.


3 Answers

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

like image 191
Václav Struhár Avatar answered Oct 29 '22 00:10

Václav Struhár


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)

  
like image 31
ravikt Avatar answered Oct 29 '22 00:10

ravikt


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

img_to_vid.py -f images_directory

like image 38
Muhammad Danial Khan Avatar answered Oct 28 '22 22:10

Muhammad Danial Khan