【问题标题】:How to animate just the last six newest images as a GIF?如何将最后六张最新图像制作为 GIF 动画?
【发布时间】:2021-01-25 17:08:15
【问题描述】:

我需要从一个目录中的最后七个最新图像创建一个 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)

【问题讨论】:

  • 使用“os.stat”,您可以检索文件的创建和修改时间戳。然后你可以检查它是否在最后 70 分钟左右,也许按时间对文件进行排序,然后进一步处理。
  • 嗯...,您的标题是 6,您的代码是 7。尝试获取文件列表并按修改日期排序。

标签: python python-3.x python-imageio


【解决方案1】:

我的想法与Mark's comment 中的建议相同。要获取目录中所有文件的适当列表,按修改数据排序,请参阅this helpful Q&A。我们只需要在接受答案的sorted 调用中添加reverse=True,这样我们就可以在列表的开头拥有最新的图像。剩下的就是一些列表理解和你的保存电话:

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
----------------------------------------

【讨论】:

    猜你喜欢
    • 2014-03-14
    • 2011-11-25
    • 1970-01-01
    • 2021-07-21
    • 2012-09-10
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多