使用Python、OpenCVImageMagick工具箱制作GIF动画
生活随笔
收集整理的這篇文章主要介紹了
使用Python、OpenCVImageMagick工具箱制作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 osdef 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、OpenCVImageMagick工具箱制作GIF动画的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL语句第二高的薪水查询
- 下一篇: 使用Python,OpenCV,面部标志