我有一系列的图片,我想从中创建一个视频。理想情况下,我可以为每帧指定帧持续时间,但固定的帧速率也可以。我在wxPython中这样做,所以我可以渲染到wxDC或我可以将图像保存到文件,如PNG。是否有一个Python库,将允许我创建一个视频(AVI, MPG等)或一个动画GIF从这些帧?
编辑:我已经尝试过PIL,它似乎不起作用。有人能用这个结论来纠正我吗?这个链接似乎支持我关于PIL的结论:http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/
使用windows7, python2.7, opencv 3.0,以下工作为我:
import cv2
import os
vvw = cv2.VideoWriter('mymovie.avi',cv2.VideoWriter_fourcc('X','V','I','D'),24,(640,480))
frameslist = os.listdir('.\\frames')
howmanyframes = len(frameslist)
print('Frames count: '+str(howmanyframes)) #just for debugging
for i in range(0,howmanyframes):
print(i)
theframe = cv2.imread('.\\frames\\'+frameslist[i])
vvw.write(theframe)
我建议不要使用visvis的images2gif,因为它有PIL/Pillow的问题,并且没有积极维护(我应该知道,因为我是作者)。
相反,请使用imageio,它是为解决这个问题而开发的,并打算保留。
快速而肮脏的解决方案:
import imageio
images = []
for filename in filenames:
images.append(imageio.imread(filename))
imageio.mimsave('/path/to/movie.gif', images)
对于较长的电影,使用流媒体方法:
import imageio
with imageio.get_writer('/path/to/movie.gif', mode='I') as writer:
for filename in filenames:
image = imageio.imread(filename)
writer.append_data(image)
from PIL import Image
import glob #use it if you want to read all of the certain file type in the directory
imgs=[]
for i in range(596,691):
imgs.append("snap"+str(i)+'.png')
print("scanned the image identified with",i)
标识不同文件名的索引的起始值和结束值+1
imgs = glob.glob("*.png") #do this if you want to read all files ending with .png
我的文件是:snap596.png, snap597.png ......snap690.png
frames = []
for i in imgs:
new_frame = Image.open(i)
frames.append(new_frame)
保存到一个GIF文件,永远循环
frames[0].save('fire3_PIL.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=300, loop=0)
我发现闪烁的问题与imageio和这个方法固定。
下面是如何使用PIL (install with: pip install Pillow):
import glob
import contextlib
from PIL import Image
# filepaths
fp_in = "/path/to/image_*.png"
fp_out = "/path/to/image.gif"
# use exit stack to automatically close opened images
with contextlib.ExitStack() as stack:
# lazily load images
imgs = (stack.enter_context(Image.open(f))
for f in sorted(glob.glob(fp_in)))
# extract first image from iterator
img = next(imgs)
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=200, loop=0)
查看文档:https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif