我希望能够将numpy数组转换为图像。首先,我学习了如何将3D(hight x width x color
)数组转换为图像。经过一些研究后,我认为PIL(或Pillow)是最自然的方式。这就是我现在这样做的方式(并且工作正常):
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数组,其中时间是附加维度)并生成相应的动画。所以,到目前为止我还没有找到怎么做。
看起来Pillow能够读取gif动画。使用ImageSequence,我们可以访问它的帧。但是,我无法找到如何将一系列图像放入动画中。
我看到一些使用ìmages2gif
的解决方案,但我想继续使用单个库。
ADDED
答案here不回答我的问题。他们使用gifmaker
库,我甚至无法通过pip安装。
答案 0 :(得分:4)
因此,该问题的主要反对意见是生成由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)
答案 1 :(得分:0)
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)