如何将 numpy 数组转换为 gif?

Nat*_*han 4 python numpy

假设我有一个 4Dnumpy数组,其中 3D 子数组是 RGB 图像。如何将其转换为 gif?我宁愿只依赖众所周知的 Python 图像处理库。

样本数据:

import numpy as np
imgs = np.random.randint(0, 255, (100, 50, 50, 3), dtype=np.uint8)
Run Code Online (Sandbox Code Playgroud)

Nat*_*han 6

这很简单,使用PIL

import numpy as np
from PIL import Image

imgs = np.random.randint(0, 255, (100, 50, 50, 3), dtype=np.uint8)
imgs = [Image.fromarray(img) for img in imgs]
# duration is the number of milliseconds between frames; this is 40 frames per second
imgs[0].save("array.gif", save_all=True, append_images=imgs[1:], duration=50, loop=0)
Run Code Online (Sandbox Code Playgroud)