How to animate just the last six newest images as a GIF?

71 views Asked by At

I need to create a GIF from the last seven newest images from a directory. The directory is constantly updating and adding new images every 10 minutes, so I already could make the code to create the GIF including all the files in the directory, but I need to be more specific and just create a GIF from the last seven newest images. In conclusion: I need to specify the limit of images which my code has to grab to create the GIF.. Below is the code so far:

import imageio
import os
import time   

now = time.time()

png_dir = 'C:/Users/dchacon/Desktop/Destino/' 
images = []
for file_name in os.listdir(png_dir):
    if file_name.endswith('.png'):
        file_path = os.path.join(png_dir, file_name)
        images.append(imageio.imread(file_path))
        imageio.mimsave('C:/Users/dchacon/Desktop/Destino/NTMPCA.gif', images, fps=1)
1

There are 1 answers

0
HansHirse On

I had the same idea as suggested in Mark's comment. For getting an appropriate list of all files in the directory, sorted by modification data, please see this helpful Q&A. We just need to add reverse=True in the sorted call of the accepted answer, such that we have the newest images at the list's start. The rest is some list comprehension and your saving call:

import imageio
import os
from pathlib import Path

# Get all image file paths, sorted by modification date, newest first
png_dir = 'your/images/path/'
image_paths = sorted(Path(png_dir).iterdir(),
                     key=os.path.getmtime,
                     reverse=True)

# Fetch the six newest images, and save GIF
images = [imageio.imread(image_path) for image_path in image_paths[:6]]
imageio.mimsave('NTMPCA.gif', images, fps=1)

I get a proper GIF of the six newest images in my test directory.

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.8.5
imageio:       2.9.0
----------------------------------------