Replace Color in Video with FFmpeg Chromakey
This article explains how to replace a specific color in a video with
another color using FFmpeg. By combining the chromakey
filter with a synthetic background generated by the color
filter, you can isolate an existing color, make it transparent, and
layer the video over a solid replacement color using the
overlay filter.
The FFmpeg Command
FFmpeg's chromakey filter removes a specified color by
converting it into an alpha channel (transparency). To replace that
color with a new one, you must generate a solid color background and
overlay the keyed video on top of it.
Run the following command in your terminal:
ffmpeg -i input.mp4 -filter_complex \
"[0:v]chromakey=color=0x00FF00:similarity=0.3:blend=0.1[keyed]; \
color=c=0xFF0000[bg]; \
[bg][keyed]scale2ref[bg][keyed]; \
[bg][keyed]overlay=shortest=1[v]" \
-map "[v]" -map 0:a? -c:a copy output.mp4How the Filtergraph Works
[0:v]chromakey=color=0x00FF00:similarity=0.3:blend=0.1[keyed]color: The hex code of the color you want to remove (in this example, pure green0x00FF00).similarity: A value between0.01and1.0that controls the tolerance. Higher values key out a wider range of similar shades.blend: A value between0.0and1.0that softens the edges of the keyed area to prevent harsh outlines.
color=c=0xFF0000[bg]- Generates a solid background canvas using the replacement color (in
this example, pure red
0xFF0000). You can specify hex codes (0xRRGGBB) or standard color names likeblue,black, oryellow.
- Generates a solid background canvas using the replacement color (in
this example, pure red
[bg][keyed]scale2ref[bg][keyed]- Dynamically scales the solid color background
[bg]to match the exact dimensions of the input video[keyed]without needing to manually specify resolutions.
- Dynamically scales the solid color background
[bg][keyed]overlay=shortest=1[v]- Places the keyed video over the solid background. The transparent
sections reveal the new color underneath.
shortest=1ensures the output ends when the main video ends.
- Places the keyed video over the solid background. The transparent
sections reveal the new color underneath.
-map "[v]" -map 0:a? -c:a copy- Maps the processed video stream
[v]and copies the existing audio stream directly without re-encoding.
- Maps the processed video stream
Fine-Tuning the Results
- Spill and Artifacts: If parts of the subject are
disappearing, lower the
similarityparameter (e.g., to0.2or0.15). If remnants of the old color remain visible, raise thesimilarityparameter slightly. - Rough Edges: Increase the
blendparameter (e.g., from0.1to0.2) to create smoother transitions along the borders of keyed objects.