是否可以仅使用枕头库生成gif动画?

2024-06-17 09:59:45 发布

您现在位置:Python中文网/ 问答频道 /正文

能够将数组转换成numpi图像。首先,我学习了如何将3D(hight x width x color)数组转换为图像。经过一番研究,我认为枕头(或枕头)是最自然的方法。我现在就是这样做的(而且效果很好):

from PIL import Image
import numpy as np

if __name__ == '__main__':
    h = 4
    w = 8
    arr = np.zeros((h,w,3), dtype=np.uint8)

    arr[0, 0, :] = [255,255,0]
    arr[3, 7, :] = [0,255,0]

    img = Image.fromarray(arr, 'RGB')
    img.save('viz.png')

下一步,我希望能够获取3D数组(或4D数组,其中时间是附加维度)的列表并生成相应的动画。所以,到目前为止我还没有找到怎么做。在

看起来枕头可以读gif动画。使用ImageSequence我们可以访问它的帧。然而,我无法找到一个动画序列。在

我看到了一些使用ìmages2gif的解决方案,但我想保留一个库。在

添加

答案here不能回答我的问题。它们使用gifmaker库,我甚至不能用pip安装它。在


Tags: 方法图像imageimportimgnp动画数组
2条回答

所以,这个问题的主要目的是生成一个由3D数组(帧)或4D矩阵(以宽度、高度、颜色和时间为维度)表示的gif动画,而不使用Python“外部”的工具。在

看起来PIL库不能做到这一点。至少在没有黑客或解决方法的情况下,不会以简单的方式出现。但是,这个目标可以通过使用moviepy库来实现。以下是该库提供的优雅解决方案:

import numpy as np
import moviepy.editor as mpy

def make_frame(t):

    h = 100
    w = 100

    ar = np.zeros((h, w, 3))

    for hi in range(h):
        for wi in range(w):
            for ci in range(3):
                ar[hi, wi, ci] = 255.0*t/15.0
    return ar


if __name__ == '__main__':

    clip = mpy.VideoClip(make_frame, duration=15.0)
    clip.write_gif('ani.gif', fps=15)
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)

使用现有图像:

^{pr2}$

而且,由于枕头太低的版本正在悄悄地失败,这里是一个带有图书馆版本检查的奖励版本:

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)

相关问题 更多 >