34364185213
Abdul Jamjoom
Edited on 11/1/22
Created on November 1, 2022 at 2:41 pm
Edited on November 1, 2022 at 5:35 pm
·
threads-blog
Click to watch narration
Watch narration
6:16
0:00

Improve GIF quality with ffmpeg

Blog-Unfurl (2).png
0:27

Let's skip straight to the result before diving into the details

The left side is old, right is new. s/o to this post on the pkh blog that offers great insights into this process!

CleanShot%202022-11-01%20at%2017.17.33%402x.png
0:28

So, how did we create GIFs?

We relied on defaults:

  1. Generic color pallet
  2. Ordered bayer dithering (cross-hatch pattern)
  3. Scale to 480
ffmpeg -i <input_video>.mp4 -t 5 -vf fps=15,scale=480:-1 ./generated_gif.gif
0:55

[GIF internals] Color Pallet

  1. GIFs support 256 colors
  2. The standard/default color pallet covers a range of all colors, so it's able to convert any video into a decent GIF
CleanShot%25202022-10-13%2520at%252016.38.21%25402x.png
1:18

[GIF internals] Dithering

Approximate colors not available in your pallet by diffusing colored pixels from your pallet

CleanShot%25202022-10-31%2520at%252023.05.16%25402x.png
1:50

How do we create GIFs now with improved quality?

  1. palettegen → generate a single palette for a whole video stream and save it as a PNG (process frames and generate a histogram of colors)
    1. stats_mode=diff (focus on the moving object)
  2. paletteuse → use the generated pallet to approximate and paint the GIF frames
  3. floyd_steinberg dithering
CleanShot%202022-11-01%20at%2017.36.49%402x.png
0:16

Code for generating HQ GIFs

./<file_name>.sh <video_file_name>.mp4

#!/bin/bash

filename=$(basename -- "$1")
palette_png="./palette_png.png"

ffmpeg -t 5 -i "$1" -vf "$filters_new,palettegen=stats_mode=diff" -y $palette_png
ffmpeg -t 5 -i "$1" -i $palette_png -lavfi "$filters_new [x]; [x][1:v] paletteuse=dither=floyd_steinberg" -y "./generated_GIF.gif"
0:08

Have questions or suggestions?

Shoot me a note at abdul@threads.com or DM me on Twitter @abduljamjoom

©2022 Threads, Inc.
BlogTwitterLog in
Made with 💜 in SF, NYC, TOR, DEN, SEA, AA