blogs
Setup terminal to be fast and charming
๐Ÿ’ป
2022-10-03
Better GIF quality with ffmpeg
๐Ÿ“บ
2022-10-02
Assymetric encryption with power of symmetric encryption in NodeJS
๐Ÿ”‘
2021-12-12
Creating customized blog using Gatsby + Notion
๐Ÿงญ
2021-07-09
Fixing ambiguous AWS ELB 504 random errors at scale
๐Ÿค•
2020-08-12

Better GIF quality with ffmpeg

๐Ÿ“บ | 2022-10-02

App link :- MP4 to GIF converter

I was facing recently facing problem with quality of GIF on crusher's Readme page. Check before/after version here.

Even with good resolution quality the conversion quality was not upto the mark.

Before


After

After stumbling on internet while scratching my head, I came across post by threads (implementation doesn't work) and one on pkh.com.

1st culprit : standard palette

The default GIF algorithm conversion process uses 256 standard colors. This is done to cover all variety of content.

With standard paeltter we generally see gradient bandin and out of place pixel colors.

Solution: In general for our use case, we don't use all the colors. Generating our own color palette can be good way to overcome this.

We will use palletegen tool to generate a palette .

2nd culprit : Dithering

Dithering is way to correct colors in spatial space range. Here is example of image with limited color set, without and with proper ditering.

We're going to use Floydโ€“Steinberg dithering, it worked for use the best and use the palleteuse tool to generate the code. You can experiment with different dethering modes.

ffmpeg script

Here's bash script to covert mp4 to video.

filename=$(basename -- "$1")
pattern_name="${1}.png"
gif_name="${1}.gif"
filters="fps=15,scale=1080:-1:flags=lanczos"

ffmpeg -v warning -i $1 -vf "$filters,palettegen" -y $pattern_name
ffmpeg -v warning -i $1 -i $pattern_name -lavfi "$filters [x]; [x][1:v] paletteuse=dither=floyd_steinberg" -y $gif_name

deploying with streamlit

Streamlit is fantastic tool to convert python based program to fully functional web app. It is mainly used for data models, but we used it to deploy our nifty tool. And within few hours we had proper running app.

It is framework + infra with streamlit cloud. The only cons is that we don't have GPU access.

For that we should use gradio on huggingface space.