Skip to content

Instantly share code, notes, and snippets.

@totetmatt
Last active August 11, 2022 15:20
Show Gist options
  • Save totetmatt/1a3addd0b1ae7f7d1dc08caaca5c6e53 to your computer and use it in GitHub Desktop.
Save totetmatt/1a3addd0b1ae7f7d1dc08caaca5c6e53 to your computer and use it in GitHub Desktop.
#!/bin/sh
import os
from pathlib import Path
import argparse
import subprocess
def _gif_this(source_file, output, start_time, end_time, duration, fps, scale):
"""
http://blog.pkh.me/p/21-high-quality-gif-with-ffmpeg.html
"""
""" Step 0 : Init variables """
if not output:
stem = Path(source_file).stem
output = f"{stem}.gif"
palette = "/tmp/palette.png"
filters = f"fps={fps},scale={scale}:flags=lanczos"
ffmpeg_base = ["ffmpeg", "-y", "-v", "warning"]
input_media_option = ["-i", source_file]
if duration:
input_media_option = ["-t", str(duration)] + input_media_option
if end_time:
input_media_option = ["-to", end_time] + input_media_option
if start_time:
input_media_option = ["-ss", start_time] + input_media_option
""" Step 1 : Palette generation """
palette_option = ["-vf", f"{filters},palettegen", palette]
subprocess.run(ffmpeg_base + input_media_option + palette_option)
""" Step 2 : Gif Generation """
input_palette_option = ["-i", palette]
output_filter_option = ["-lavfi", f"{filters} [x];[x][1:v] paletteuse"]
subprocess.run(
ffmpeg_base
+ input_media_option
+ input_palette_option
+ output_filter_option
+ [output]
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Gif from video")
parser.add_argument("source_file", type=str, help="Source file")
parser.add_argument("--output", type=str, help="Result filename")
parser.add_argument("--start_time", type=str, help="Start Time")
parser.add_argument("--fps", type=float, help="Fps", default=15.0)
parser.add_argument("--scale", type=str, help="Scale", default="320:-1")
action = parser.add_mutually_exclusive_group()
action.add_argument("--end_time", type=str, help="End Time")
action.add_argument("--duration", type=float, help="Duration")
args = parser.parse_args()
_gif_this(**args.__dict__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment