How to Use the Colorkey Filter in FFmpeg
This article provides a quick and practical guide on how to use the
colorkey filter in FFmpeg to perform chroma keying (green
or blue screen removal). You will learn the basic syntax of the filter,
understand its key parameters for adjusting sensitivity and edge
blending, and see step-by-step command examples for making video
backgrounds transparent and overlaying videos.
Understanding the Colorkey Filter Syntax
The colorkey filter is designed to make a specific color
in a video or image transparent. It is most commonly used for green
screen or blue screen footage.
The basic syntax for the filter is:
colorkey=color:similarity:blend
color: The color you want to make transparent. You can specify this as a hex value (e.g.,0x00FF00for pure green) or a color name (e.g.,green,blue,black).similarity: A value between0.01and1.0that determines how closely the pixel color must match the target color to be made transparent. A value of0.01matches only the exact color, while higher values match broader ranges of similar shades. The default is0.05.blend: A value between0.0and1.0that controls the softness of the keyed edges. A higher value blends the edges of the foreground object with the transparent background to prevent harsh, pixelated borders. The default is0.0.
Basic Example: Exporting to a Transparent Video
To remove a green screen from a video and save the output as a transparent WebM video (which supports the alpha channel required for transparency), use the following command:
ffmpeg -i input.mp4 -vf "colorkey=0x00FF00:0.3:0.1" -c:v libvpx-vp9 -pix_fmt yuva420p output.webmIn this command: * 0x00FF00 targets the green color. *
0.3 is the similarity threshold, allowing for slight
variations in the green screen lighting. * 0.1 applies a
slight blend to soften the edges of the subject. *
-c:v libvpx-vp9 and -pix_fmt yuva420p ensure
the output video is encoded with a transparent alpha channel.
Advanced Example: Overlaying onto a Background Video
If you want to remove a green screen from a foreground video and
immediately overlay it onto a background video in a single step, you can
use FFmpeg’s filter_complex.
ffmpeg -i background.mp4 -i greenscreen.mp4 -filter_complex "[1:v]colorkey=0x00FF00:0.3:0.1[foreground];[0:v][foreground]overlay=shortest=1[out]" -map "[out]" output.mp4Here is how this command works: 1.
-i background.mp4 is input 0
(background). 2. -i greenscreen.mp4 is
input 1 (foreground with green screen). 3.
[1:v]colorkey=0x00FF00:0.3:0.1[foreground]
applies the colorkey filter to the foreground video and labels the
transparent output as [foreground]. 4.
[0:v][foreground]overlay=shortest=1[out]
overlays the transparent [foreground] video on top of the
[0:v] background video. The shortest=1
parameter stops the output when the shortest input video ends. 5.
-map "[out]" tells FFmpeg to use the final
composited stream for the output file.