如何将numpy数组转换为gif?

4
假设我有一个4D的numpy数组,其中3D子数组是RGB图像。如何将其转换为gif格式?我希望只依赖于Python中众所周知的图像处理库。
示例数据:
import numpy as np
imgs = np.random.randint(0, 255, (100, 50, 50, 3), dtype=np.uint8)
2个回答

5

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

1
你也可以使用ImageMagick和OpenCV从一组图像中制作GIF。
def create_gif(inputPath, outputPath, delay, finalDelay, loop):
    # grab all image paths in the input directory
    imagePaths = sorted(list(paths.list_images(inputPath)))
    
    # remove the last image path in the list
    lastPath = imagePaths[-1]
    imagePaths = imagePaths[:-1]
    # construct the image magick 'convert' command that will be used
    # generate our output GIF, giving a larger delay to the final
    # frame (if so desired)
    cmd = "convert -delay {} {} -delay {} {} -loop {} {}".format(
        delay, " ".join(imagePaths), finalDelay, lastPath, loop,
        outputPath)
    os.system(cmd)

你可以参考pyimagesearch的教程来更加清晰地了解。

1
如果示例展示如何从问题中的示例数据获取gif,那将更好。一个纯Python解决方案也比仅使用Python作为命令行包装器更好。 - Nathan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接