如何从图像创建视频?

时间:2018-11-08 18:44:18

标签: python image matrix video cv2

我有一个算法,该算法在每次迭代后都会创建一个矩阵。在对矩阵进行一些操作后,将其绘制给用户。如果我运行程序6次,我将得到:

a bunch of images

我的目标是像电影一样动态地改变图像。

我不知道从哪方面开始。我发现了一些用python中的图像创建视频,然后将其包装在视频播放器中的方法。但这似乎有点复杂,并且在算法运行时无法看到更改。有什么建议怎么做吗?

2 个答案:

答案 0 :(得分:3)

您可以使用FFMPEG

def convert():
    os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")

或者,您可以使用ImageIO生成GIF。您可以设置每帧持续时间的参数。

import imageio
with imageio.get_writer('/path_to_video.gif', mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)

有关详细说明,请阅读网站上的手册。

with cv2

import cv2

img1 = cv2.imread('1.jpg')
img2 = cv2.imread('2.jpg')
img3 = cv2.imread('3.jpg')

height , width , layers =  img1.shape

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

video.write(img1)
video.write(img2)
video.write(img3)

cv2.destroyAllWindows()
video.release()

答案 1 :(得分:1)

在Python中从头开始使用视频数据生成代码(使用Jupyter):

import numpy as np
import skvideo.io as sk
# creating sample video data
num_vids = 5
num_imgs = 100
img_size = 50
min_object_size = 1
max_object_size = 5
 
for i_vid in range(num_vids):
 imgs = np.zeros((num_imgs, img_size, img_size)) # set background to 0
 vid_name = ‘vid’ + str(i_vid) + ‘.mp4’
 w, h = np.random.randint(min_object_size, max_object_size, size=2)
 x = np.random.randint(0, img_size — w)
 y = np.random.randint(0, img_size — h)
 i_img = 0
 while x>0:
 imgs[i_img, y:y+h, x:x+w] = 255 # set rectangle as foreground
 x = x-1
 i_img = i_img+1
 sk.vwrite(vid_name, imgs.astype(np.uint8))
# play a video
from IPython.display import Video
Video(“vid3.mp4”) # the script & video should be in same folder