Skip to content

Instantly share code, notes, and snippets.

@bluekyu
Last active December 9, 2017 05:47
Show Gist options
  • Save bluekyu/f1ab8d839378e276a7e109acea25d4e0 to your computer and use it in GitHub Desktop.
Save bluekyu/f1ab8d839378e276a7e109acea25d4e0 to your computer and use it in GitHub Desktop.
"""
MIT License
Copyright (c) 2017 Younguk Kim
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# References
# - https://video.stackexchange.com/questions/4563/how-can-i-crop-a-video-with-ffmpeg
# - https://superuser.com/questions/556029/how-do-i-convert-a-video-to-gif-using-ffmpeg-with-reasonable-quality
# - http://blog.pkh.me/p/21-high-quality-gif-with-ffmpeg.html
import subprocess
import pathlib
import argparse
import uuid
import os
import sys
def print_debug(msg):
print("\x1b[32;1m", msg, "\x1b[0m", sep="", flush=True)
def print_error(msg):
print("\x1b[31;1m", msg, "\x1b[0m", sep="", flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("input", type=str)
parser.add_argument("output", type=str)
parser.add_argument("--resize", type=str, help="Similar with scale filter in ffmpeg. ex) --resize=480:270")
parser.add_argument("--crop", type=str, help="Same as scale filter in ffmpeg. ex) --crop=480:270 or --crop=W:H:X:Y")
parser.add_argument("--fps", type=int, default=15, help="Default is 15 fps")
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args()
try:
subprocess.run(["ffmpeg", "-version"], check=True)
except:
print_error("Cannot run ffmpeg.")
sys.exit(1)
if args.verbose:
default_stderr = subprocess.STDOUT
else:
default_stderr = subprocess.DEVNULL
input_file = pathlib.Path(args.input).absolute()
print_debug("Input file: {}".format(input_file))
print_debug("Options:\n-- FPS: {}".format(args.fps))
if args.crop:
print_debug("-- Crop: {}".format(args.crop))
if args.resize:
print_debug("-- Resize: {}".format(args.resize))
output_file = pathlib.Path(args.output).absolute()
if output_file.exists():
print_error("Output file exists: {}".format(output_file))
sys.exit(1)
if args.crop:
crop_file = input_file.parent / (input_file.stem + "-cropped" + input_file.suffix)
if crop_file.exists():
print_error("Crop file exists: {}".format(crop_file))
sys.exit(1)
# cropping
subprocess.run(["ffmpeg", "-i", input_file.as_posix(),
"-vf", "crop={}".format(args.crop), "-c:a", "copy",
crop_file.as_posix()], stderr=default_stderr)
print_debug("Crop file: {}".format(crop_file))
# get width of cropped file
out_width = subprocess.run([
"ffprobe",
"-of", "default=noprint_wrappers=1:nokey=1",
"-select_streams", "v:0",
"-show_entries",
"stream=width",
crop_file.as_posix()],
stderr=subprocess.DEVNULL,
stdout=subprocess.PIPE).stdout.decode().strip()
input_file = crop_file
scale = str(out_width) + ":-1"
elif args.resize:
scale = args.resize
else:
scale = None
# generate a palette
palette_file = input_file.parent / (str(uuid.uuid4()) + ".png")
subprocess.run(["ffmpeg", "-i", input_file.as_posix(),
"-vf", "fps={},{}palettegen".format(
args.fps, "scale={}:flags=lanczos,".format(scale) if scale else ""),
palette_file.as_posix()], stderr=default_stderr)
print_debug("Palette file: {}".format(palette_file))
# generate gif
subprocess.run(["ffmpeg", "-i", input_file.as_posix(),
"-i", palette_file.as_posix(),
"-lavfi", "fps={},{}paletteuse=dither=sierra2_4a".format(
args.fps, "scale={}:flags=lanczos[x]; [x][1:v] ".format(scale) if scale else ""),
output_file.as_posix()], stderr=default_stderr)
print_debug("Output file: {}".format(output_file))
# remove palette
os.remove(palette_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment