Search code examples
pythonpython-imageioapng

How to make an animated set of images with a working duration per image


I want to make an animated set of images in python. I can't use an animated gif as I need more than 256 colors. I have tried an animated png but it seems the duration argument doesn't work. Here is a MWE:

import seaborn as sns
import io
import matplotlib.pyplot as plt
import scipy
import math
import numpy as np
import imageio

vmin = 0
vmax = 0.4
images = []
for i in range(3):
    mu = 0
    variance = i+0.1
    sigma = math.sqrt(variance)
    x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
    row = scipy.stats.norm.pdf(x, mu, sigma)
    matrix = []
    for _ in range(100):
        matrix.append(row)
    cmap = "viridis"
    hmap = sns.heatmap(matrix, vmin=vmin, vmax=vmax, cmap=cmap)
    hmap.set_xticklabels([*range(0, 100, 4)])
    cbar = hmap.collections[0].colorbar
    cbar.set_label("Colorbar Label", labelpad=10)  # Set the label and adjust the spacing using labelpad
    plt.savefig(f"image_{i}.png", format='png')

    plt.close()
    images.append(imageio.v3.imread(f"image_{i}.png"))
    
imageio.mimwrite("out.png", images, duration=4)

Is there way to set the duration, or alternatively, is there another way to make an animated set of images that doesn't require any external tools other than python?


Solution

  • You are setting the duration:

    imageio.mimwrite("out.png", images, duration=4)
    

    Per the Pillow docs, duration is expressed in milliseconds. Setting duration=1000 results in a slower APNG.

    animated PNG