首页 > 解决方案 > 如何将最后六张最新图像制作成 GIF 动画?

问题描述

我需要从一个目录中的最后七个最新图像创建一个 GIF。该目录每 10 分钟不断更新和添加新图像,因此我已经可以编写代码来创建包含目录中所有文件的 GIF,但我需要更具体,只需从最后七个最新图像创建一个 GIF . 总之:我需要指定我的代码必须抓取的图像的限制以创建 GIF。. 以下是到目前为止的代码:

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)

标签: pythonpython-3.xpython-imageio

解决方案


我的想法与马克评论中的建议相同。要获取目录中所有文件的适当列表,按修改数据排序,请参阅此有用的问答。我们只需要添加已接受答案reverse=Truesorted调用,这样我们就可以在列表的开头拥有最新的图像。其余的是一些列表理解和您的保存电话:

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)

我在我的测试目录中获得了六个最新图像的正确 GIF。

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

推荐阅读