Python creates video from images using opencv
I was trying to create a video to show dynamically changing data, for example, just constantly displaying images one by one, so I used images (images that were named only 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 the error was raised:
TypeError: image is not a numpy array, neither a scalar
I think I was using the list incorrectly, but I'm not sure. So where am I going wrong?
+7
source to share
2 answers
You can read the frames and write them to the video in a loop. Below is the code with a slight modification to remove the 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 the skvideo library to create a video 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)
0
source to share