How do I convert a numpy array to a gif?

Viewed 3238

Suppose I have a 4D numpy array where the 3D subarrays are RGB images. How do I convert this to a gif? I would prefer to only depend on well-known Python image processing libraries.

Sample data:

import numpy as np
imgs = np.random.randint(0, 255, (100, 50, 50, 3), dtype=np.uint8)
2 Answers

This is straightforward using 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)

You can also use ImageMagick and OpenCV to make a GIF from a set of images.

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)

You can refer to this tutorial of pyimagesearch for more clarity.

Related