我试图创建一个视频来显示数据的动态变化,比如只是连续快速地逐个显示图像,所以我使用了图像(图像只是称为1,2,3,4,... ..)并编写了以下代码:
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()
并引发了错误:
TypeError: image is not a numpy array, neither a scalar
我认为我以错误的方式使用了这个列表,但我不确定。那么我哪里做错了?
答案 0 :(得分:8)
答案 1 :(得分:1)
您可以读取帧并将它们循环写入视频。以下是您的代码,进行了少量修改以删除一个for循环。
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()
或者,您可以使用skvideo库创建视频表单图像序列。
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)