zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用Python、OpenCV,ImageMagick工具箱制作GIF动画

PythonOpencv动画 制作 gif 工具箱 ImageMagick 使用
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)