python - 如何将最后六张最新图像制作成 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)
解决方案
我的想法与马克评论中的建议相同。要获取目录中所有文件的适当列表,按修改数据排序,请参阅此有用的问答。我们只需要添加已接受答案reverse=True
的sorted
调用,这样我们就可以在列表的开头拥有最新的图像。其余的是一些列表理解和您的保存电话:
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
----------------------------------------
推荐阅读
- php - FilesystemManager.php 第 121 行中的 Laravel 5.2 InvalidArgumentException:不支持驱动程序 []
- c++ - 介子添加现有的dll作为依赖
- java - java类型转换重要吗?在初学者阶段是否一定需要知道?
- pl-i - 如何获取字符串的当前剩余长度?
- spring - 如何修复表单验证,当它不起作用时
- gtk - GTK:如何在顶部窗口边框上获取按钮释放事件
- c++ - (C++ 和 OpenGL)我正在尝试在批处理渲染器中旋转一组顶点(它将模拟一个正方形),但它不是 100% 工作:(
- gcc - 多架构构建系统
- javascript - 如何将js变量传递给jinja2
- c++ - 这个简单的代码应该可以工作,但我收到警告