How Do Green Screens Work? Key a Clip in FFmpeg and Resolve

How do green screens work? The short answer · Why the screen is green, and when blue is the better pick · What you need before you start · Shoot the plate so the key has an easy job · Steps 1 and 2: check your FFmpeg build and make a test plate · Steps 3 and 4: pull the first key and read the matte · Steps 5 and 6: clean the matte and remove green spill · Steps 7 and 8: composite on a new background and export · Steps 9 to 11: the same key in DaVinci Resolve 21.2 · Step 12: the complete working project, a batch keyer script · Common pitfalls that wreck a key · Troubleshooting: 10 problems and their fixes · Advanced tips for harder footage · Common questions
A green screen works by giving software an easy color to find. The camera films a subject in front of a flat, saturated green backdrop, a keyer measures how close each pixel sits to that green, and it turns the distance into transparency. Whatever you place behind the subject then shows through. That is the whole trick, and the rest of this tutorial is about doing each part cleanly.
You will build the effect twice with current tools. First on the command line with FFmpeg 9.1 “Gauss”, released November 20, 2026. Then in DaVinci Resolve 21.2, the build named in Blackmagic’s own 21.2 readme. The FFmpeg route exposes the math, because every parameter maps to one stage. The Resolve route shows how an editor wraps the same stages in sliders.
If you want a start-to-finish workflow for a finished video, our guide to green screening with free software covers that. This article answers the question underneath it: how do green screens work at the pixel level, so you can fix a bad key instead of dragging sliders at random. You finish with a working batch script, a transparent export and a checklist for when the edges go wrong.
How do green screens work? The short answer
A keyer is a color-distance calculator. For every pixel in every frame, it asks how different that pixel is from the key color you picked. Pixels that match the key color become fully transparent. Pixels that look nothing like it stay fully opaque. Pixels in between, such as a strand of hair or a motion-blurred hand, become partly transparent.
The output of that calculation is called a matte, or alpha channel. It is a grayscale image the same size as the video. White means keep, black means remove, gray means blend. Every green screen tool you will ever use, from a phone app to a film-grade compositor, produces this matte somewhere in its pipeline. Once you have it, the final composite is one line of arithmetic.
alpha = how far the pixel sits from the key color, scaled to a 0 to 1 range
output = foreground * alpha + background * (1 - alpha)
Note what a keyer does not do. It does not blindly delete green pixels. Summaries of chroma keying describe selection by hue, saturation and brightness, not a blanket remove-green command. That distinction explains most failures. A green shirt gets removed because it sits near the key color. A pale blonde edge goes green because the screen’s light bounced onto it. A fuzzy edge appears because the camera’s compression smeared the boundary.
| Stage | What happens | Where you control it |
|---|---|---|
| 1. Capture | Camera records the subject over a flat, evenly lit green backdrop | Lighting, distance, shutter, codec |
| 2. Key | Software measures each pixel’s distance from the key color | Key color, similarity |
| 3. Matte | Distance becomes a grayscale alpha, white keeps and black removes | Blend or softness |
| 4. Clean | Garbage mask, erode and blur tidy the matte, despill fixes edge color | Mask, erode, blur, despill mix |
| 5. Composite | Foreground is laid over the new background using the matte | Overlay, color match, export |
Stages 2 to 4 decide most of the quality, and they are also where cheap tools cut corners. The steps below walk through all five in order, first with FFmpeg, then in Resolve.
Why the screen is green, and when blue is the better pick
Green wins for two practical reasons. First, people rarely have naturally green skin or hair, so the key color stays far from the subject. Second, most camera sensors carry the most detail in the green channel, so a green backdrop tends to produce cleaner, less noisy edges than other saturated colors. Neither reason is a law of physics. They are defaults that work for most shoots, and you should drop them when your subject says otherwise.

Blue is the standard alternative. Choose it when the subject wears green, holds a plant or a green product, or has green in a logo you cannot change. The keyer does not care which color you pick. It only needs the key color to be far from everything you want to keep. If you are still choosing software for this job, our ranking of chroma key software compares what each tool exposes for edge control.
| Situation | Better screen | Reason |
|---|---|---|
| Presenter in neutral clothing, normal room light | Green | Skin tones sit far from green, and sensor detail is strongest there |
| Green jacket, plant, bottle or app logo in frame | Blue | Keeps the wardrobe and props out of the key |
| Blue jeans, blue eyes in tight close-ups | Green | Avoids punching holes in blue denim or irises |
| Very dim room, small sensor | Green, lit hard | Blue channels often show more noise at low light, and noise makes a matte flicker |
| Product shot with mixed colors | Whichever color the product lacks | The only rule that matters is distance from the key color |
The same logic applies to the shade of green. The test clip in this tutorial uses the hex value 00B140, a typical saturated green. Real fabric under real lights will read differently on your camera. That is why every keyer has an eyedropper. Sample your own footage, not a color chart.
Whatever color you pick, it spills. Spill is the colored light bouncing off the screen onto the subject, and it shows up first in white clothing and light hair. You manage spill with distance on set and with a despill filter in post, covered in Step 6.
What you need before you start
Everything in this tutorial runs on free software. The table lists the versions this article was written against, checked against the vendors’ pages and release notes on November 25, 2026.
| Item | Version | Cost | Used for |
|---|---|---|---|
| FFmpeg with ffprobe | 9.1 “Gauss” (released November 20, 2026) | Free, open source | Steps 1 to 8 and the batch script |
| DaVinci Resolve | 21.2 (free edition is enough) | Free, or Studio at US$295 one time | Steps 9 to 11 |
| Python | Any current 3.x | Free | Step 12 batch script |
| Shell | bash, zsh, Git Bash or WSL | Free | Multi-line commands with variables |
| A background still | PNG or JPG, 1920×1080 or larger | Free | The new scene behind the subject |
| Optional: real green plate | Any clip, 1080p or higher | Your own footage | Swap in for the synthetic test clip |
Two version notes. FFmpeg 9.1’s headline changes are GPU related, including Vulkan encoders and NVIDIA Optical Flow support, and the research behind this article surfaced no change to the keying filters. Every filter used here has shipped in FFmpeg for several major releases, so an older build from your Linux distribution or a bundled app will likely work too. Run the check in Step 1 to be sure. On the Resolve side, the free edition covers the Color and Fusion pages used in this tutorial. Blackmagic lists AI tools, camera tracking and temporal noise reduction among the extras in Studio, which our free versus Studio comparison weighs in detail.
One warning from the 21.2 readme before you open an existing project. Blackmagic kept project libraries compatible with 20.3.2, but projects created or opened in 21.2 can no longer be opened in 20.3.2. Back up the whole library first. Not sure Resolve is the right editor? Our list of the best free video editing software and the Resolve versus Premiere Pro comparison cover the alternatives. The keying concepts below transfer to any of them.
Shoot the plate so the key has an easy job
The footage you shoot, called the plate, sets a ceiling on quality that no software can lift. A clean plate keys in two minutes. A bad plate eats an afternoon. The test clip in the next steps is synthetic, so you can follow along without a camera, but read this section before you film anything real.
| Setting | Target | Why it matters |
|---|---|---|
| Subject to screen distance | About 1.5 meters (5 feet) or more | Reduces green light bouncing onto hair, shoulders and glasses |
| Screen lighting | Even across the cloth, no hot spots | An uneven screen forces a wider key and eats into the subject |
| Subject lighting | Separate lights, aimed away from the screen | Keeps the key light from washing the backdrop |
| Screen exposure | Mid-level, saturated green, not glowing | Clipped greens lose the color information the keyer needs |
| Shutter speed | About double the frame rate, such as 1/60 s at 30 fps | Heavy motion blur creates mixed pixels that key badly |
| Codec | Highest bitrate available, 4:2:2 if the camera offers it | Compression smears color edges, which is where the matte lives |
| Wrinkles | Pull the fabric tight or steam it | Creases create shadow bands the key sees as a different color |
Light the screen and the subject as two separate jobs. Put flat, soft light on the backdrop until it looks the same from corner to corner. Then light the person with their own fixtures, flagged so they do not spill back onto the cloth. If you can only afford one thing, buy distance. Moving a presenter one extra step forward from the wall does more for edge quality than any plugin.
Shooting on a phone works fine if you lock exposure, white balance and focus before you record, because an auto-adjusting camera changes the screen’s color mid-shot and the key shimmers. Our roundup of mobile video editing apps covers apps that can key on the phone itself. For the cleanest result, still record at the highest quality setting and key on a computer.
Finally, shoot a few seconds of the empty screen before the subject walks in. This is a clean plate. You will rarely need it for a basic key, but it is the raw material for the difference-matte trick in the advanced tips, and it costs nothing to record.
Steps 1 and 2: check your FFmpeg build and make a test plate
Start by confirming which FFmpeg you have and that it includes the five filters this tutorial uses. Linux package managers and bundled apps often ship older builds, so do not assume you are on 9.1.

Step 1: verify the tools
ffmpeg -version
ffprobe -version
ffmpeg -hide_banner -filters | grep -E "chromakey|colorkey|despill|alphamerge|alphaextract"
Example output, trimmed. Your flags column and description wording may differ:
ffmpeg version 9.1 Copyright (c) 2000-2026 the FFmpeg developers
... alphaextract V->N Extract an alpha channel as a grayscale image component.
... alphamerge VN->V Copy the luma value of the second input into the alpha channel of the first input.
... chromakey V->V Turn a certain color into transparency. Operates in YUV colorspace.
... colorkey V->V Turns a certain color into transparency. Operates on RGB colors.
... despill V->V Despill video.
If any of the five lines is missing, your build is too old or stripped down. Download a current static build from the FFmpeg project’s download page and call it by full path. If the version line shows something other than 9.1, you can still continue, and the troubleshooting table lists the problems an older build can cause.
Step 2: generate a synthetic green plate and a background
The next command builds a six-second 1280×720 clip. A flat green field stands in for the screen. A skin-tone disc with a soft 14-pixel edge drifts left and right across it, standing in for a head with feathered hair. The clip is encoded as H.264 4:2:0 at a modest CRF so it carries the same compression smear a real camera file does. A second command writes a test-pattern background, and a third reads the plate back to confirm its format.
ffmpeg -hide_banner -y \
-f lavfi -i "color=c=0x00B140:s=1280x720:r=30:d=6" \
-f lavfi -i "color=c=0xD9A27E:s=360x360:r=30:d=6,format=yuva420p,geq=lum='p(X,Y)':cb='p(X,Y)':cr='p(X,Y)':a='255*clip((170-hypot(X-180,Y-180))/14,0,1)'" \
-filter_complex "[0][1]overlay=x='460+120*sin(2*PI*t/3)':y=180:format=auto,format=yuv420p" \
-c:v libx264 -crf 14 -pix_fmt yuv420p plate.mp4
ffmpeg -hide_banner -y -f lavfi -i "testsrc2=s=1280x720" -frames:v 1 bg.png
ffprobe -v error -show_entries stream=codec_name,width,height,pix_fmt,r_frame_rate -of default=nw=1 plate.mp4
codec_name=h264
width=1280
height=720
pix_fmt=yuv420p
r_frame_rate=30/1
Open plate.mp4 in any player. You should see a tan disc swaying over a flat green field. Note the pixel format, yuv420p. That detail comes back in the pitfalls, because 4:2:0 stores color at half resolution in each direction, and color resolution is exactly what a keyer reads.
Steps 3 and 4: pull the first key and read the matte
FFmpeg ships two basic keyers. The chromakey filter works in YUV space and judges distance by the two color components (U and V), mostly ignoring brightness. The colorkey filter works in RGB and judges distance across all three channels. For camera footage with uneven lighting, chromakey is usually the better starting point because a shadow on the screen changes brightness more than it changes color.
The two sliders that matter, similarity and blend, are easier to tune once you see what they do to one pixel. The snippet below is a simplified model of the idea, not FFmpeg’s source code, and its distance units are illustrative. A pixel whose distance from the key color is at or below the similarity value is fully removed. Between similarity and similarity plus blend, it fades from removed to kept. Beyond that band, it stays solid.
def key_alpha(pixel_uv, key_uv, similarity, blend):
du = pixel_uv[0] - key_uv[0]
dv = pixel_uv[1] - key_uv[1]
dist = (du * du + dv * dv) ** 0.5 / 255.0
if blend == 0:
return 0.0 if dist <= similarity else 1.0
return min(1.0, max(0.0, (dist - similarity) / blend))
# similarity 0.12, blend 0.06
# dist 0.10 -> alpha 0.0 (removed)
# dist 0.15 -> alpha 0.5 (half transparent)
# dist 0.20 -> alpha 1.0 (kept)
Read the example in the comments. With similarity at 0.12 and blend at 0.06, the soft band spans distances from 0.12 to 0.18. A wide blend widens that band, which gives hair a gentler fade but also makes the screen’s own noise leave faint gray specks. A blend of zero gives a hard, cut-paper edge. Most real keys sit between those extremes.
| Parameter | What it does | Start at | Effect of raising it |
|---|---|---|---|
| color | The key color, as hex such as 0x00B140 | Sampled from your plate | Not a slider, but a wrong value ruins everything |
| similarity (chromakey) | How far from the key color still counts as background | 0.10 to 0.15 | Removes more green, then starts eating the subject |
| blend (chromakey) | Width of the soft transition between removed and kept | 0.05 to 0.10 | Softer edges, more semi-transparent pixels |
| similarity (colorkey) | Same idea, measured in RGB distance | 0.25 to 0.35 | Needs a larger value than chromakey for the same result |
| yuv | Tells chromakey the color is already in YUV | Leave off | Only matters if you pass a YUV color value |
Step 3: apply chromakey and write the matte to a PNG
Looking at the matte directly teaches you more than looking at the composite, because a composite hides problems behind a busy background. This command keys the plate, pulls out only the alpha channel and saves one frame taken one second in.
ffmpeg -hide_banner -y -ss 1 -i plate.mp4 \
-vf "chromakey=color=0x00B140:similarity=0.12:blend=0.06,alphaextract,format=gray" \
-frames:v 1 matte_chromakey.png
Open matte_chromakey.png. A good result is a white disc on a black field with a thin gray ring at the edge. If the whole frame is black, similarity is far too high. If the whole frame is white, the key color is wrong or similarity is too low. If the disc has speckled gray patches inside it, the subject color is drifting near the key, which you fix in Step 5.
Step 4: compare chromakey with colorkey
ffmpeg -hide_banner -y -ss 1 -i plate.mp4 \
-vf "colorkey=color=0x00B140:similarity=0.30:blend=0.08,alphaextract,format=gray" \
-frames:v 1 matte_colorkey.png
Put the two PNGs side by side. On this flat, evenly lit plate the mattes will look close. They diverge on real footage with a shadow across the cloth, where colorkey tends to read the darker green as a different color and leave a smudge. Keep that comparison habit. Whenever a key misbehaves, switch keyers on a single frame before you touch anything else, because the answer often sits in the choice of color space.
Steps 5 and 6: clean the matte and remove green spill
A raw matte is rarely shippable. It has stray gray pixels far from the subject, a fringe of green-tinted edge pixels, and sometimes holes inside the subject. Cleaning fixes the alpha channel. Despilling fixes the color of the pixels that survive. They are separate problems that need separate tools, and mixing them up is the most common beginner mistake.
Step 5: add a garbage matte, erode the edge and blur it slightly
A garbage matte is a rough mask that throws away everything outside the area where your subject can possibly be. It removes the lamp stand, the screen frame and any stray corners without touching the key. The graph below draws a white box on a black frame, softens its edges, then multiplies it into the keyed matte. After that, erosion shrinks the matte by one pixel to pull the fringe inward, and a light Gaussian blur at sigma 1 softens the stair-stepping that erosion leaves behind.
ffmpeg -hide_banner -y -ss 1 -i plate.mp4 -filter_complex \
"color=c=black:s=1280x720:r=30:d=6,drawbox=x=100:y=0:w=1080:h=720:color=white:t=fill,gblur=sigma=6,format=gray[gm];\
[0:v]chromakey=color=0x00B140:similarity=0.12:blend=0.06,alphaextract,erosion,gblur=sigma=1,format=gray[m0];\
[m0][gm]blend=all_mode=multiply:shortest=1[m]" \
-map "[m]" -frames:v 1 matte_clean.png
Compare matte_clean.png with matte_chromakey.png. The disc should be slightly smaller, with a smoother ring. Do not overdo it. Each erosion pass shaves one pixel, and on a 720p frame two or three passes can start eating fine hair. Add passes one at a time and stop when the green fringe is gone from the matte, not when the edge looks perfect.
Step 6: despill the color
Spill survives keying because those pixels are not close enough to the key color to be removed. The despill filter pulls the excess green out of every pixel. Its main controls are type (green or blue), mix, which sets how much green is replaced, and expand, which governs how far the correction reaches into adjacent hues. Higher mix is stronger, but push it too far and skin goes magenta.
ffmpeg -hide_banner -y -ss 1 -i plate.mp4 \
-vf "despill=type=green:mix=0.5:expand=0.1" -frames:v 1 despill_check.png
This still shows the despill on the whole frame, so the backdrop changes color too, which is fine because the matte removes it anyway. Zoom in on the disc’s edge and compare it with the unprocessed frame. The faint green cast on the rim should be neutralized. On real footage, check hair, glasses frames and any white clothing, since those show spill first.
Steps 7 and 8: composite on a new background and export
Now join the pieces into one graph. The shell variable FG below holds everything up to the finished foreground, a clip with despilled color and a cleaned alpha channel. Saving it as a variable lets you reuse it for the composite and for transparent exports without retyping the graph. On Windows, run these in Git Bash or WSL, or skip to Step 12 for the Python version that builds the graph for you.
Step 7: build the foreground graph and composite it
FG="[0:v]split=2[v][k];\
[k]chromakey=color=0x00B140:similarity=0.12:blend=0.06,alphaextract,erosion,gblur=sigma=1,format=gray[m0];\
color=c=black:s=1280x720:r=30:d=6,drawbox=x=100:y=0:w=1080:h=720:color=white:t=fill,gblur=sigma=6,format=gray[gm];\
[m0][gm]blend=all_mode=multiply:shortest=1[m];\
[v]despill=type=green:mix=0.5:expand=0.1,format=yuv444p[d];\
[d][m]alphamerge[fg]"
ffmpeg -hide_banner -y -i plate.mp4 -loop 1 -framerate 30 -i bg.png \
-filter_complex "$FG;[1:v]scale=1280:720,setsar=1[bg];[bg][fg]overlay=format=auto:shortest=1,format=yuv420p[out]" \
-map "[out]" -c:v libx264 -crf 18 -preset medium -pix_fmt yuv420p -movflags +faststart composite.mp4
Play composite.mp4. You should see the tan disc swaying over the test pattern with a clean rim and no green halo. Three details in the command prevent real bugs. The format=yuv444p after despill keeps full color resolution while the alpha is attached. The shortest=1 options stop the looping background image from running forever. The final format=yuv420p makes the file playable in browsers and phones.
Step 8: export for the destination
Pick the export by where the keyed clip goes next. A finished video wants H.264. A clip you will drop onto another timeline wants an alpha channel, and H.264 in an MP4 cannot carry one. Use ProRes 4444 in a MOV for editors, or VP9 in WebM for browsers and OBS browser sources.
ffmpeg -hide_banner -y -i plate.mp4 -filter_complex "$FG;[fg]format=yuva444p10le[out]" \
-map "[out]" -c:v prores_ks -profile:v 4444 -pix_fmt yuva444p10le keyed_alpha.mov
ffmpeg -hide_banner -y -i plate.mp4 -filter_complex "$FG;[fg]format=yuva420p[out]" \
-map "[out]" -c:v libvpx-vp9 -pix_fmt yuva420p -crf 24 -b:v 0 keyed_alpha.webm
Render settings
| Destination | Container and codec | Pixel format | Keep alpha | Resolution and frame rate |
|---|---|---|---|---|
| Finished video for upload | MP4, H.264, CRF 18 | yuv420p | No | Match the plate, such as 1920×1080 at 30 fps |
| Layer for another editor | MOV, ProRes 4444 | yuva444p10le | Yes | Match the plate, never upscale |
| Browser or OBS overlay | WebM, VP9 | yuva420p | Yes | Match the plate, keep it modest for live use |
| Matte inspection | PNG, 8-bit gray | gray | Is the alpha | Single frame, same size as the plate |
From the Vipid archive: if the new background should be an animated scene instead of a still, the intro themes list their resolution, length and frame rate, which tells you what to match before you key over one.
Steps 9 to 11: the same key in DaVinci Resolve 21.2
Resolve offers two good keying routes. The Color page has a 3D keyer inside its qualifier tools, which is fast and works well for evenly lit screens. The Fusion page has a Delta Keyer built for harder footage, with separate controls for the core matte, the edge and the spill. Blackmagic positions Resolve as one application for editing, color, visual effects, motion graphics and audio, so you can do both without leaving the project. Menu names and tab layouts shift a little between builds, so check them against the manual for your install. For the surrounding edit, our walk-through of editing a YouTube video in Resolve 21.2 covers project setup.
Step 9: set up the timeline
- Create a project and set the timeline resolution and frame rate to match plate.mp4, 1280×720 at 30 fps for the test clip.
- Import plate.mp4 and bg.png into the Media Pool.
- On the Edit page, place the background on video track 1 and drag the plate onto video track 2, directly above it. Extend the still to the clip length.
- Confirm the plate covers the background in the viewer. The green field hides everything, which is correct for now.
Step 10: key with the 3D keyer on the Color page
- Select the plate on track 2 and open the Color page. Add a serial node and open the Qualifier palette.
- Switch the qualifier mode to 3D. Use the eyedropper to click and drag a short line across the green field. Sample from the middle of the screen, not a bright or shadowed corner.
- Turn on the highlight view to see the selection as a white matte. Widen or narrow the selection until the whole screen is solid white and the subject is solid black.
- Open the matte finesse controls. Use clean black and clean white to push near-black and near-white values to the extremes, and add a small amount of blur radius so the edge is soft, not stair-stepped.
- Invert the matte so the subject becomes the selection. Right-click the node graph and add an Alpha Output, then connect the node’s key output to it.
- Return to the Edit page. The background on track 1 should now show through.
Keep the first selection tight, then widen it in small steps. Dragging a huge selection on the first try grabs skin tones, and you spend the next ten minutes backing out. If the footage is noisy, Studio’s temporal noise reduction, listed on Blackmagic’s Studio page, can calm a shimmering matte before you key. The free edition handles the key itself without it.
Step 11: use the Delta Keyer in Fusion for edges and spill
- Select the plate on the timeline and open the Fusion page. You will see a MediaIn node connected to a MediaOut node.
- Add a Delta Keyer between them from the Effects Library, under the matte tools. In the Inspector, use the background color picker and drag the eyedropper onto the green in the viewer.
- View the alpha channel in the viewer. Adjust the matte controls until the core of the subject is solid white and the background solid black. Use the clean foreground and clean background style controls sparingly, because they harden the edge.
- Use the fringe and spill controls to neutralize green on the rim. Watch hair and any white clothing as you adjust.
- Use the erode and blur options to tighten and soften the edge, the same two operations as Step 5.
- Return to the Edit page. The Fusion result keeps its alpha, so the background shows through.
Which route should you use? Take the 3D keyer for clean, evenly lit footage where speed matters. Take the Delta Keyer when you see hair, motion blur or spill, because it gives you separate dials for each problem. Other editors offer their own keyers. Our comparisons of Final Cut Pro versus Resolve and CapCut versus Resolve help you decide where to spend your time.
Step 12: the complete working project, a batch keyer script
Typing a graph by hand works for one clip. For a series of episodes, you want one command that keys a folder. The script below reads each clip’s size, frame rate and duration with ffprobe, builds the same graph you just wrote with the garbage matte scaled to the frame, then writes a composite MP4 and an optional ProRes 4444 alpha file. Save it as greenkey.py.
#!/usr/bin/env python3
import argparse, json, subprocess, sys
from pathlib import Path
def probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height,r_frame_rate:format=duration",
"-of", "json", str(path)],
capture_output=True, text=True, check=True).stdout
data = json.loads(out)
s = data["streams"][0]
return int(s["width"]), int(s["height"]), s["r_frame_rate"], float(data["format"]["duration"])
def foreground_graph(a, w, h, fps, dur):
gx, gy, gw, gh = (float(v) for v in a.garbage.split(","))
box = f"x={int(gx * w)}:y={int(gy * h)}:w={int(gw * w)}:h={int(gh * h)}"
erode = ",".join(["erosion"] * a.erode) if a.erode else "null"
return ";".join([
"[0:v]split=2[v][k]",
f"[k]chromakey=color={a.key_color}:similarity={a.similarity}:blend={a.blend},"
f"alphaextract,{erode},gblur=sigma={a.blur},format=gray[m0]",
f"color=c=black:s={w}x{h}:r={fps}:d={dur:.3f},drawbox={box}:color=white:t=fill,"
"gblur=sigma=6,format=gray[gm]",
"[m0][gm]blend=all_mode=multiply:shortest=1[m]",
f"[v]despill=type={a.screen}:mix={a.despill}:expand=0.1,format=yuv444p[d]",
"[d][m]alphamerge[fg]",
])
def run(cmd):
subprocess.run(cmd, check=True)
def main():
p = argparse.ArgumentParser(description="Batch chroma key with FFmpeg")
p.add_argument("folder")
p.add_argument("--bg", required=True, help="background image (PNG or JPG)")
p.add_argument("--out", default="keyed")
p.add_argument("--screen", choices=["green", "blue"], default="green")
p.add_argument("--key-color", default="0x00B140")
p.add_argument("--similarity", type=float, default=0.12)
p.add_argument("--blend", type=float, default=0.06)
p.add_argument("--despill", type=float, default=0.5)
p.add_argument("--erode", type=int, default=1)
p.add_argument("--blur", type=float, default=1.0)
p.add_argument("--garbage", default="0.05,0,0.9,1", help="x,y,w,h as fractions of the frame")
p.add_argument("--alpha", action="store_true", help="also write a ProRes 4444 file")
a = p.parse_args()
clips = sorted(list(Path(a.folder).glob("*.mp4")) + list(Path(a.folder).glob("*.mov")))
if not clips:
sys.exit("no .mp4 or .mov files found in " + a.folder)
Path(a.out).mkdir(parents=True, exist_ok=True)
for i, clip in enumerate(clips, 1):
w, h, fps, dur = probe(clip)
print(f"[{i}/{len(clips)}] {clip.name} {w}x{h} {fps} fps {dur:.1f} s")
fg = foreground_graph(a, w, h, fps, dur)
comp = Path(a.out) / f"{clip.stem}_keyed.mp4"
graph = (fg + f";[1:v]scale={w}:{h}:force_original_aspect_ratio=increase,"
f"crop={w}:{h},setsar=1[bg];[bg][fg]overlay=format=auto:shortest=1,"
"format=yuv420p[out]")
run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-i", str(clip), "-loop", "1", "-framerate", fps, "-i", a.bg,
"-filter_complex", graph, "-map", "[out]", "-map", "0:a?",
"-c:v", "libx264", "-crf", "18", "-preset", "medium",
"-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k",
"-movflags", "+faststart", str(comp)])
print(" wrote", comp)
if a.alpha:
alpha = Path(a.out) / f"{clip.stem}_alpha.mov"
run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-i", str(clip), "-filter_complex", fg + ";[fg]format=yuva444p10le[out]",
"-map", "[out]", "-c:v", "prores_ks", "-profile:v", "4444",
"-pix_fmt", "yuva444p10le", str(alpha)])
print(" wrote", alpha)
if __name__ == "__main__":
main()
Put your plates in a folder called clips, drop a background image next to the script and run it:
mkdir clips
cp plate.mp4 clips/
python3 greenkey.py clips --bg bg.png --out keyed --similarity 0.12 --blend 0.06 --despill 0.5 --erode 1 --alpha
[1/1] plate.mp4 1280x720 30/1 fps 6.0 s
wrote keyed/plate_keyed.mp4
wrote keyed/plate_alpha.mov
Tune per shoot, not per clip. Find a similarity and blend pair that works on one frame of your studio setup, write them down, and reuse them on every episode filmed under the same lights. If the lights change, resample the key color with an eyedropper and rerun. The script also takes a blue screen. Pass --screen blue and a key color sampled from your blue cloth, and the despill filter switches to the blue channel.
Common pitfalls that wreck a key
These are the mistakes that show up again and again. Each one has a cause you can see in the matte.
- Keying from a 4:2:0 file. Most camera and phone files store color at half resolution in each direction. The matte edge can only be as sharp as that color layer, so you see blocky, stair-stepped rims. Shoot 4:2:2 or better when you can, and expect to soften and erode the matte on 4:2:0 footage.
- Sampling the key color from a highlight or shadow. The eyedropper then locks onto the wrong brightness and the rest of the screen falls outside similarity. Sample mid-screen, then widen.
- Raising similarity until the green disappears. A wide similarity removes the screen and also the subject’s cooler tones. Prefer a narrow similarity plus clean-up over a wide one.
- Fixing spill with the matte. Eroding a matte hard enough to hide a green rim also eats hair. Spill is a color problem, so solve it with despill.
- Skipping the garbage matte. A lamp stand or a fold at the edge of the cloth leaves ghost shapes that no amount of similarity tuning removes cleanly. Mask them out.
- Exporting alpha into H.264 MP4. The container cannot hold an alpha channel, so the transparency turns into black or green. Use ProRes 4444 in MOV or VP9 in WebM for alpha.
- Mismatched frame rate or size on the background. A 24 fps background under a 30 fps plate stutters. Match both before compositing.
One habit prevents most of these. Always inspect the matte as a black and white image before you judge the composite. A composite flatters a bad matte because the new background distracts the eye. A matte shows you every hole, speck and soft spot at once. Once you see how green screens work as a matte-making job, most of the sliders in any editor make sense.
Troubleshooting: 10 problems and their fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| The whole frame goes transparent | Similarity far too high, or wrong key color | Drop similarity to 0.05, resample the key color from mid-screen, then climb |
| Green halo around the subject | Spill survived the key | Raise despill mix in small steps and erode the matte by one pixel |
| Holes inside the subject | Clothing or skin sits near the key color | Lower similarity, switch keyer, or draw a mask that protects the subject |
| Edges flicker from frame to frame | Noise or compression changes the matte each frame | Denoise before keying, or in Resolve Studio use temporal noise reduction |
| Blocky, stair-stepped edges | 4:2:0 color resolution | Convert to yuv444p before keying, blur the matte by sigma 1, shoot higher color resolution next time |
| Error: No such filter despill | FFmpeg build too old or stripped | Run the Step 1 filter check and install a current build |
| Black background instead of transparency | Container or pixel format has no alpha | Export MOV ProRes 4444 with yuva444p10le, or WebM VP9 with yuva420p |
| The command never finishes | An infinite source such as a looped image | Add shortest=1 to overlay and blend, or give sources a duration with d= |
| Skin turns pink or gray after despill | Despill mix too strong | Lower mix toward 0.3, then check at 100 percent zoom |
| Resolve shows a black clip after keying | Matte not inverted, or the key output is not wired to the Alpha Output | Invert the matte and reconnect the node’s key output |
When the cause is unclear, bisect. Strip the graph back to the bare chromakey and alphaextract, confirm the matte, then add one stage at a time. The stage that breaks the picture is the one to tune.
One FFmpeg-specific caution. When a filter complains about formats, such as an error that filters could not be reinitialized, insert an explicit format= step before it. Several keying filters only accept certain pixel layouts, and the automatic conversion FFmpeg inserts is not always the one you want. Reading the full error line above the summary usually names the pixel format that was rejected.
Advanced tips for harder footage
- Try a hue-based key. FFmpeg’s hsvkey filter keys on hue, saturation and value instead of YUV or RGB distance. It can separate a green screen from a green-tinted subject when plain distance keying cannot. Check that your build lists it.
- Use the clean plate. A shot of the empty screen lets you find the screen’s real color variation across the frame. In an editor you can subtract it to build a cleaner matte, a technique often called a difference matte.
- Denoise only the matte. Run a light spatial or temporal denoise on a copy used only to generate the matte. The color footage stays sharp, and the matte stops shimmering.
- Split core and edge. Make one tight matte for the solid body and one wider, softer matte for hair, then combine them. Fusion’s Delta Keyer builds this idea into its controls.
- Match the new background. Even a perfect matte looks fake if the foreground is bright and warm while the background is cool and dark. Grade the foreground to the background’s contrast and color, and add a faint light wrap by blurring the background and blending it into the subject’s edge.
- Add matching grain and blur. Overlay the same film grain on the whole composite, and soften the foreground slightly when the background is out of focus.
- Key live. OBS Studio has a Chroma Key filter that you apply to a camera source for real-time green screen in streams and recordings. Tune it with the same logic: key color first, then similarity, then smoothness and spill.
- Skip the screen when you can. AI masking tools in editors can cut a subject without a backdrop. They are convenient for quick jobs, but a lit green screen still gives finer control over hair and glass.
For paid work, a keying workflow is only one piece of the editing stack, and our guide to professional video editing software shows where each editor fits. Browse more tutorials in the editing software category when you are ready for color grading and delivery.
Common questions
How do green screens work in simple terms?
Software compares every pixel to a key color, usually a bright green. Pixels that match become transparent, and pixels that differ stay visible. A new background is placed underneath, so it shows wherever the green was.
Why is a green screen green and not another color?
Skin and hair rarely contain strong green, so the key color stays far from most subjects, and camera sensors tend to hold good detail in green. Blue works just as well in principle. Use blue when your subject wears or holds green.
Do I need expensive software to use a green screen?
No. FFmpeg is free and open source, and the free edition of DaVinci Resolve includes the Color and Fusion tools used in this tutorial. Studio costs US$295 as a one-time purchase and adds extras such as AI tools and temporal noise reduction, but a basic key does not need them.
What is the difference between FFmpeg chromakey and colorkey?
Chromakey measures distance in YUV color space and mostly ignores brightness. Colorkey measures distance in RGB. Chromakey usually copes better with uneven lighting, so start there and switch if a matte looks wrong. The similarity values are not interchangeable between the two.
What is spill, and how do I remove it?
Spill is green light bouncing off the screen onto your subject, most visible on hair, shoulders and light clothing. Reduce it on set by moving the subject away from the screen. Remove what remains with a despill filter, such as FFmpeg’s despill or the spill controls in Resolve’s Delta Keyer.
Can I save a keyed clip with a transparent background?
Yes, but not as a standard H.264 MP4. Export ProRes 4444 in a MOV for editors, or VP9 in a WebM with a yuva420p pixel format for browsers and overlays. Both keep the alpha channel your matte created.
Why do my edges look fuzzy or blocky?
Two common reasons. Hair and motion blur contain pixels that mix subject and screen, so the matte is partly transparent there by design. Compressed 4:2:0 footage also stores color at lower resolution than brightness, which blurs the boundary the keyer reads. Better lighting, a higher bitrate and 4:2:2 footage all help.
Can I key footage shot on a phone?
Yes. Lock exposure, white balance and focus before recording, light the screen evenly and keep the subject away from the cloth. Phone files are usually 4:2:0, so plan on softening the matte slightly and despilling with care.
- Vipid intro themes resolution, length and frame rate per theme
- Promo themes product and channel promos
- Sample videos finished Vipid intros
- Vipid intro maker make a custom intro in the browser
Jonah Reyes
Jonah Reyes is the Editing & Export Editor at Vipid. He covers editing software, export settings and codecs, and the video specs of YouTube, Shorts, TikTok and Reels, plus OBS and screen recording. He builds Vipid’s spec tables from the platforms’ own documentation and re-checks them every 60 to 90 days, so the numbers in a guide match what the upload dialog actually accepts.


