使用Python、OpenCV,ImageMagick工具箱制作GIF动画
2023-09-27 14:26:27 时间
使用Python、OpenCV,ImageMagick工具箱制作GIF动画
这篇博客将介绍如何根据给定的源图片文件夹制作动画,Python负责根据给定文件夹获取所有图片文件,并根据图片名进行排序,实质上动画是调用ImageMagick的命令行生成的;
ImageMagick的安装可参考:使用Python,OpenCV创建动画GIF图
原始文件夹图片:
效果图:
看起来后边的俩张图小是因为原始图片就分辨率不一致哈。原始图片一致的就没这问题了;
源码:
# USAGE
# python create_gif.py --config config.json --output out.gif
# 导入必要的包
from imutils import paths
import argparse
import json
import cv2
import os
def create_gif(inputPath, outputPath, delay, finalDelay, loop):
# 获取输入路径的所有图像
imagePaths = sorted(list(paths.list_images(inputPath)))
# 移除list中的最后一个路径
lastPath = imagePaths[-1]
imagePaths = imagePaths[:-1]
# 构建 ImageMagick命令行以生成输出的GIF,给一个足够大的时间延迟以得到最终输出动画
cmd = "magick -delay {} {} -delay {} {} -loop {} {}".format(
delay, " ".join(imagePaths), finalDelay, lastPath, loop,
outputPath)
print(cmd)
os.system(cmd)
# 构建命令行参数并解析
# --config: JSON配置文件的路径
# --output: 输出gif的路径
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--config", required=True,
help="path to configuration file")
ap.add_argument("-o", "--output", required=True,
help="path to output GIF")
args = vars(ap.parse_args())
# 加载config文件
config = json.loads(open(args["config"]).read())
# 所有图像的帧已写入临时文件夹中,制作GIF图
print("[INFO] creating GIF...")
# 调用 create_gif 函数来生成GIF动画文件,create_gif 函数是将参数传递给ImageMagick的convert的包装器工具以执行其命令行。
create_gif(config['temp_dir'], args["output"], config["delay"],
config["final_delay"], config["loop"])
cv2.waitKey(0)
# 清理删除临时文件夹
print("[INFO] cleaning up...")
# shutil.rmtree(config["temp_dir"], ignore_errors=True)
相关文章
- Python中zipfile压缩文件模块的使用
- opencv官方文档:Python通过url获取图片的几种方法以及图像格式之间的转换,imencode()+imdecode()使用
- Python基础之:Python中的IO
- Python twisted框架使用解析
- python局域网alive ip侦听
- python基础
- 将自己OpenCV-Python-PyCharm开发环境的Python-3.6.8更换为python-3.9.10的详细过程记录
- OpenCV-Python中的函数cv.imread()读取到的图像的数据存储结构是怎样的?
- linux使用vi浏览python源码
- python 创建文件夹并写入文件源码
- Linux下安装OpenCV+Python支持
- 「基于Python技术的智慧中医商业项目」Django后端新闻应用设计
- 解决Python无法写入Mongodb数据仓库方法汇总
- 如何使用OpenCV Python比较两个图像的直方图?
- python快速排序实现元素递增
- Python Manim教程大全之 02 数学方程(教程含源码)
- Python代码库OpenCV之04读取图片绘制直方图(含代码)
- Python代码库OpenCV之09线检测line detection(含代码)
- 用Python绑定调用C/C++/Rust库
- 华为OD机试 - 乘积最大值(Python)
- [Python]Python 使用 for 循环的小例子
- python 3.7.4 安装 opencv(windows7+pycharm),拍照功能
- Python Opencv 之 简单的视频裁剪功能的实现
- (原)windows8.1上使用opencv for python