繁体   English   中英

在 Python 中以编程方式生成视频或动画 GIF?

[英]Programmatically generate video or animated GIF in Python?

我有一系列图像,我想从中创建视频。 理想情况下,我可以为每一帧指定一个帧持续时间,但固定的帧速率也可以。 我在 wxPython 中这样做,所以我可以渲染到 wxDC 或者我可以将图像保存到文件中,比如 PNG。 是否有允许我从这些帧创建视频(AVI、MPG 等)或动画 GIF 的 Python 库?

编辑:我已经尝试过 PIL,但它似乎不起作用。 有人可以用这个结论纠正我或建议另一个工具包吗? 这个链接似乎支持我关于 PIL 的结论: http : //www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/

我建议不要使用来自 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)

以下是使用PIL 的方法(安装: pip install Pillow ):

import glob
from PIL import Image

# filepaths
fp_in = "/path/to/image_*.png"
fp_out = "/path/to/image.gif"

# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in))]
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

好吧,现在我正在使用 ImageMagick。 我将帧保存为 PNG 文件,然后从 Python 调用 ImageMagick 的 convert.exe 来创建动画 GIF。 这种方法的好处是我可以单独为每个帧指定一个帧持续时间。 不幸的是,这取决于机器上安装的 ImageMagick。 他们有一个 Python 包装器,但它看起来很糟糕而且不受支持。 仍然对其他建议持开放态度。

截至 2009 年 6 月,最初引用的博客文章在评论中提供了一种创建动画 GIF 的方法。 下载脚本images2gif.py (以前的images2gif.py ,更新由@geographika 提供)。

然后,要反转 gif 中的帧,例如:

#!/usr/bin/env python

from PIL import Image, ImageSequence
import sys, os
filename = sys.argv[1]
im = Image.open(filename)
original_duration = im.info['duration']
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]    
frames.reverse()

from images2gif import writeGif
writeGif("reverse_" + os.path.basename(filename), frames, duration=original_duration/1000.0, dither=0)

我使用了易于使用的images2gif.py 不过,它似乎确实使文件大小增加了一倍。

26 个 110kb PNG 文件,我预计 26*110kb = 2860kb,但 my_gif.GIF 是 5.7mb

也因为 GIF 是 8 位的,漂亮的 png 在 GIF 中变得有点模糊

这是我使用的代码:

__author__ = 'Robert'
from images2gif import writeGif
from PIL import Image
import os

file_names = sorted((fn for fn in os.listdir('.') if fn.endswith('.png')))
#['animationframa.png', 'animationframb.png', 'animationframc.png', ...] "

images = [Image.open(fn) for fn in file_names]

print writeGif.__doc__
# writeGif(filename, images, duration=0.1, loops=0, dither=1)
#    Write an animated gif from the specified images.
#    images should be a list of numpy arrays of PIL images.
#    Numpy images of type float should have pixels between 0 and 1.
#    Numpy images of other types are expected to have values between 0 and 255.


#images.extend(reversed(images)) #infinit loop will go backwards and forwards.

filename = "my_gif.GIF"
writeGif(filename, images, duration=0.2)
#54 frames written
#
#Process finished with exit code 0

以下是 26 帧中的 3 帧:

这是 26 帧中的 3 帧

缩小图像缩小尺寸:

size = (150,150)
for im in images:
    im.thumbnail(size, Image.ANTIALIAS)

较小的gif

要创建视频,您可以使用opencv

#load your frames
frames = ...
#create a video writer
writer = cvCreateVideoWriter(filename, -1, fps, frame_size, is_color=1)
#and write your frames in a loop if you want
cvWriteFrame(writer, frames[i])

我遇到了这篇文章,但没有一个解决方案有效,所以这是我的解决方案。

迄今为止其他解决方案的问题:
1)关于如何修改持续时间没有明确的解决方案
2)乱序目录迭代没有解决方案,这对于GIF来说是必不可少的
3)没有解释如何为python 3安装imageio

像这样安装 imageio: python3 -m pip install imageio

注意:你需要确保你的帧在文件名中有某种索引,以便它们可以被排序,否则你将无法知道 GIF 的开始或结束位置

import imageio
import os

path = '/Users/myusername/Desktop/Pics/' # on Mac: right click on a folder, hold down option, and click "copy as pathname"

image_folder = os.fsencode(path)

filenames = []

for file in os.listdir(image_folder):
    filename = os.fsdecode(file)
    if filename.endswith( ('.jpeg', '.png', '.gif') ):
        filenames.append(filename)

filenames.sort() # this iteration technique has no built in order, so sort the frames

images = list(map(lambda filename: imageio.imread(filename), filenames))

imageio.mimsave(os.path.join('movie.gif'), images, duration = 0.04) # modify duration as needed

我要发布一个答案,因为它比到目前为止发布的所有内容都更简单:

from PIL import Image

width = 300
height = 300
im1 = Image.new("RGBA", (width, height), (255, 0, 0))
im2 = Image.new("RGBA", (width, height), (255, 255, 0))
im3 = Image.new("RGBA", (width, height), (255, 255, 255))
im1.save("out.gif", save_all=True, append_images=[im2, im3], duration=100, loop=0)

使用现有图像:

from PIL import Image

im1 = Image.open('a.png')
im2 = Image.open('b.png')
im3 = Image.open('c.png')
im1.save("out.gif", save_all=True, append_images=[im2, im3], duration=100, loop=0)

并且,由于枕头的版本太低而无声地失败了,这里是带有库版本检查的附加版本:

from packaging import version
from PIL import Image

im1 = Image.open('a.png')
im2 = Image.open('b.png')
im3 = Image.open('c.png')
if version.parse(Image.PILLOW_VERSION) < version.parse("3.4"):
    print("Pillow in version not supporting making animated gifs")
    print("you need to upgrade library version")
    print("see release notes in")
    print("https://pillow.readthedocs.io/en/latest/releasenotes/3.4.0.html#append-images-to-gif")
else:
    im1.save("out.gif", save_all=True, append_images=[
             im2, im3], duration=100, loop=0)

正如沃伦去年所说,这是一个老问题。 由于人们似乎仍在查看页面,我想将他们重定向到更现代的解决方案。 就像 blakev 在这里说的, github上有一个 Pillow 示例。

 import ImageSequence
 import Image
 import gifmaker
 sequence = []

 im = Image.open(....)

 # im is your original image
 frames = [frame.copy() for frame in ImageSequence.Iterator(im)]

 # write GIF animation
 fp = open("out.gif", "wb")
 gifmaker.makedelta(fp, frames)
 fp.close()

注意:这个例子已经过时了( gifmaker不是一个可导入的模块,只是一个脚本)。 Pillow 有一个GifImagePlugin (其来源在 GitHub 上),但ImageSequence 上的文档似乎表明支持有限(只读)

正如上面提到的一位成员,imageio 是一个很好的方式来做到这一点。 imageio 还允许您设置帧速率,实际上我用 Python 编写了一个函数,允许您设置最后一帧的保持。 我将此功能用于科学动画,其中循环很有用,但立即重新启动没有用。 这是链接和功能:

如何使用 Python 制作 GIF

import matplotlib.pyplot as plt
import os
import imageio

def gif_maker(gif_name,png_dir,gif_indx,num_gifs,dpi=90):
    # make png path if it doesn't exist already
    if not os.path.exists(png_dir):
        os.makedirs(png_dir)

    # save each .png for GIF
    # lower dpi gives a smaller, grainier GIF; higher dpi gives larger, clearer GIF
    plt.savefig(png_dir+'frame_'+str(gif_indx)+'_.png',dpi=dpi)
    plt.close('all') # comment this out if you're just updating the x,y data

    if gif_indx==num_gifs-1:
        # sort the .png files based on index used above
        images,image_file_names = [],[]
        for file_name in os.listdir(png_dir):
            if file_name.endswith('.png'):
                image_file_names.append(file_name)       
        sorted_files = sorted(image_file_names, key=lambda y: int(y.split('_')[1]))

        # define some GIF parameters

        frame_length = 0.5 # seconds between frames
        end_pause = 4 # seconds to stay on last frame
        # loop through files, join them to image array, and write to GIF called 'wind_turbine_dist.gif'
        for ii in range(0,len(sorted_files)):       
            file_path = os.path.join(png_dir, sorted_files[ii])
            if ii==len(sorted_files)-1:
                for jj in range(0,int(end_pause/frame_length)):
                    images.append(imageio.imread(file_path))
            else:
                images.append(imageio.imread(file_path))
        # the duration is the time spent on each image (1/duration is frame rate)
        imageio.mimsave(gif_name, images,'GIF',duration=frame_length)

使用此方法的示例 GIF

老问题,很多好的答案,但可能仍然对另一种选择感兴趣......

我最近在 github ( https://github.com/WarrenWeckesser/numpngw ) 上发布的numpngw模块可以从 numpy 数组编写动画 PNG 文件。 更新numpngw现在在 pypi 上: https : numpngw 。)

例如,这个脚本:

import numpy as np
import numpngw


img0 = np.zeros((64, 64, 3), dtype=np.uint8)
img0[:32, :32, :] = 255
img1 = np.zeros((64, 64, 3), dtype=np.uint8)
img1[32:, :32, 0] = 255
img2 = np.zeros((64, 64, 3), dtype=np.uint8)
img2[32:, 32:, 1] = 255
img3 = np.zeros((64, 64, 3), dtype=np.uint8)
img3[:32, 32:, 2] = 255
seq = [img0, img1, img2, img3]
for img in seq:
    img[16:-16, 16:-16] = 127
    img[0, :] = 127
    img[-1, :] = 127
    img[:, 0] = 127
    img[:, -1] = 127

numpngw.write_apng('foo.png', seq, delay=250, use_palette=True)

创建:

动画 png

您需要一个支持动画 PNG(直接或使用插件)的浏览器才能查看动画。

它不是 python 库,但 mencoder 可以做到这一点: Encoding from multiple input image files 您可以像这样从 python 执行 mencoder:

import os

os.system("mencoder ...")

使用 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)

让它对我有用的最简单的事情是在 Python 中调用 shell 命令。

如果您的图像存储为 dummy_image_1.png、dummy_image_2.png ... dummy_image_N.png,那么您可以使用该函数:

import subprocess
def grid2gif(image_str, output_gif):
    str1 = 'convert -delay 100 -loop 1 ' + image_str  + ' ' + output_gif
    subprocess.call(str1, shell=True)

只需执行:

grid2gif("dummy_image*.png", "my_output.gif")

这将构建您的 gif 文件 my_output.gif。

你试过PyMedia吗? 我不是 100% 确定,但看起来本教程示例针对您的问题。

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 出现闪烁问题,此方法修复了它。

该任务可以通过从与图片文件序列相同的文件夹中运行两行 python 脚本来完成。 对于 png 格式的文件,脚本是 -

from scitools.std import movie
movie('*.png',fps=1,output_file='thisismygif.gif')

我正在寻找单行代码,发现以下内容适用于我的应用程序。 这是我所做的:

第一步:从下面的链接安装 ImageMagick

https://www.imagemagick.org/script/download.php

在此处输入图片说明

第二步:将 cmd 行指向放置图像(在我的情况下为 .png 格式)的文件夹

在此处输入图片说明

第三步:输入以下命令

magick -quality 100 *.png outvideo.mpeg

在此处输入图片说明

感谢 FogleBird 的想法!

安装

pip install imageio-ffmpeg
pip install imageio

代码

import imageio
images = []
for filename in filenames:
    images.append(imageio.imread(filename))
imageio.mimsave('movie.mp4', images)

当保存为 mp4 而不是 gif 时,质量提高,大小从 8Mb 减少到 80Kb

我刚刚尝试了以下方法并且非常有用:

首先将库Figtodatimages2gif下载到您的本地目录。

其次收集数组中的数字并将它们转换为动画 gif:

import sys
sys.path.insert(0,"/path/to/your/local/directory")
import Figtodat
from images2gif import writeGif
import matplotlib.pyplot as plt
import numpy

figure = plt.figure()
plot   = figure.add_subplot (111)

plot.hold(False)
    # draw a cardinal sine plot
images=[]
y = numpy.random.randn(100,5)
for i in range(y.shape[1]):
    plot.plot (numpy.sin(y[:,i]))  
    plot.set_ylim(-3.0,3)
    plot.text(90,-2.5,str(i))
    im = Figtodat.fig2img(figure)
    images.append(im)

writeGif("images.gif",images,duration=0.3,dither=0)

我发现了 PIL 的ImageSequence模块,它提供了更好(更标准)的 GIF 动画。 这次我也用了Tk的after()方法,比time.sleep()好

from Tkinter import * 
from PIL import Image, ImageTk, ImageSequence

def stop(event):
  global play
  play = False
  exit() 

root = Tk()
root.bind("<Key>", stop) # Press any key to stop
GIFfile = {path_to_your_GIF_file}
im = Image.open(GIFfile); img = ImageTk.PhotoImage(im)
delay = im.info['duration'] # Delay used in the GIF file 
lbl = Label(image=img); lbl.pack() # Create a label where to display images
play = True;
while play:
  for frame in ImageSequence.Iterator(im):
    if not play: break 
    root.after(delay);
    img = ImageTk.PhotoImage(frame)
    lbl.config(image=img); root.update() # Show the new frame/image

root.mainloop()

一个制作 GIF 的简单函数:

import imageio
import pathlib
from datetime import datetime


def make_gif(image_directory: pathlib.Path, frames_per_second: float, **kwargs):
    """
    Makes a .gif which shows many images at a given frame rate.
    All images should be in order (don't know how this works) in the image directory

    Only tested with .png images but may work with others.

    :param image_directory:
    :type image_directory: pathlib.Path
    :param frames_per_second:
    :type frames_per_second: float
    :param kwargs: image_type='png' or other
    :return: nothing
    """
    assert isinstance(image_directory, pathlib.Path), "input must be a pathlib object"
    image_type = kwargs.get('type', 'png')

    timestampStr = datetime.now().strftime("%y%m%d_%H%M%S")
    gif_dir = image_directory.joinpath(timestampStr + "_GIF.gif")

    print('Started making GIF')
    print('Please wait... ')

    images = []
    for file_name in image_directory.glob('*.' + image_type):
        images.append(imageio.imread(image_directory.joinpath(file_name)))
    imageio.mimsave(gif_dir.as_posix(), images, fps=frames_per_second)

    print('Finished making GIF!')
    print('GIF can be found at: ' + gif_dir.as_posix())


def main():
    fps = 2
    png_dir = pathlib.Path('C:/temp/my_images')
    make_gif(png_dir, fps)

if __name__ == "__main__":
    main()

我知道您问的是将图像转换为 gif 的问题; 但是,如果原始格式是 MP4,则可以使用FFmpeg

ffmpeg -i input.mp4 output.gif

除了 Smart Manoj 答案:从文件夹中的所有图像制作 .mp4 电影

安装:

pip install imageio-ffmpeg
pip install imageio

代码:

import os
import imageio

root = r'path_to_folder_with_images'

images = []    
for subdir, dirs, files in os.walk(root):
    for file in files:
        images.append(imageio.imread(os.path.join(root,file)))

savepath = r'path_to_save_folder'
imageio.mimsave(os.path.join(savepath,'movie.mp4'), images)

PS:确保您的“文件”列表按您想要的方式排序,如果您已经相应地保存了图像,您将节省一些时间

这真是令人难以置信......所有人都提出了一些用于播放动画 GIF 的特殊包,目前可以使用 Tkinter 和经典的 PIL 模块来完成!

这是我自己的 GIF 动画方法(我不久前创建的)。 很简单的:

from Tkinter import * 
from PIL import Image, ImageTk
from time import sleep

def stop(event):
  global play
  play = False
  exit() 

root = Tk()
root.bind("<Key>", stop) # Press any key to stop
GIFfile = {path_to_your_GIF_file}    
im = Image.open(GIFfile); img = ImageTk.PhotoImage(im)
delay = float(im.info['duration'])/1000; # Delay used in the GIF file 
lbl = Label(image=img); lbl.pack() # Create a label where to display images
play = True; frame = 0
while play:
  sleep(delay);
  frame += 1
  try:
    im.seek(frame); img = ImageTk.PhotoImage(im)
    lbl.config(image=img); root.update() # Show the new frame/image
  except EOFError:
    frame = 0 # Restart

root.mainloop()

您可以设置自己的方法来停止动画。 如果您想获得带有播放/暂停/退出按钮的完整版本,请告诉我。

注意:我不确定连续帧是从内存还是从文件(磁盘)中读取的。 在第二种情况下,如果它们都一次读取并保存到数组(列表)中,效率会更高。 (我不是很想知道!:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM