Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""Key green-screen clips with CorridorKey (neural keyer: straight foreground colour + clean linear alpha, spill andgreen-tinted shadows unmixed) instead of comp.py's colour-difference key, and composite them over comp.py's plates.
uv run --with pillow --with numpy python previz/ck_key.py prep SHOT [SHOT ...] # frames + coarse alpha hints (cd tools/CorridorKey && PYTORCH_ENABLE_MPS_FALLBACK=1 uv run python ../../previz/ck_key.py infer) uv run --with pillow --with numpy --with opencv-python-headless python previz/ck_key.py video SHOT [SHOT ...]
Setup: `git clone https://github.com/nikopueringer/CorridorKey tools/CorridorKey` (git-ignore tools/), `uv sync` in it;the model downloads on first run. Runs on Apple Silicon via MPS, ~10-20 s per 720p frame: run infer in the background.The alpha hints come from comp.key_video(), eroded and blurred: the model is trained on coarse, eroded hints and fillsthe detail back in. Keep the screen colour green even when shadows are tinted: any screen colour tints the shadows.
HD=1 (env): key the 1080p downloads in clips/hd/green/ and write to clips/hd/ (CorridorKey folders get a _hd suffix),for the final cut. Plates and shot settings come from comp.py (previz/plates/plates.json).
Accelerating rides ("accel": true in plates.json, e.g. characters on a rocket/cart that speeds up): the foregroundboomerangs at natural speed (forward then backward, so riders bounce in place and the clip never runs out), while thebackground scroll eases in as u**1.7 across a plate extended as plate | mirrored | plate | mirrored | plate, withhorizontal motion blur growing with scroll speed and a slight shake at top speed. A linear pan of one plate width readas far too slow."""import os, shutil, subprocess, sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parentCK = ROOT.parent / "tools" / "CorridorKey"HD = os.environ.get("HD") == "1"CLIPS = CK / "ClipsForInference"SRC = ROOT / "clips" / "hd" / "green" if HD else ROOT / "clips" / "green"OUTDIR = ROOT / "clips" / "hd" if HD else ROOT / "clips"SUF = "_hd" if HD else ""
def prep(shots): from PIL import Image, ImageFilter sys.path.insert(0, str(ROOT)) from comp import key_video for shot in shots: d = CLIPS / (shot + SUF) shutil.rmtree(d, ignore_errors=True) (d / "Input").mkdir(parents=True); (d / "AlphaHint").mkdir() subprocess.run(["ffmpeg", "-v", "error", "-i", str(SRC / f"{shot}.mp4"), str(d / "Input" / "%05d.png")], check=True) for f in sorted((d / "Input").iterdir()): a = key_video(Image.open(f)).getchannel("A") a = a.filter(ImageFilter.MinFilter(7)).filter(ImageFilter.GaussianBlur(4)) a.save(d / "AlphaHint" / f.name) print(shot, len(list((d / "Input").iterdir())), "frames + hints ->", d)
def infer(): sys.path.insert(0, str(CK)) os.chdir(CK) from clip_manager import InferenceSettings, run_inference, scan_clips run_inference(scan_clips(), device="mps", settings=InferenceSettings(despill_strength=1.0, screen_color="green", generate_comp=True))
def video(shots): """comp.video() with the CorridorKey matte and straight foreground, composited in linear light.""" import cv2 import numpy as np from PIL import Image sys.path.insert(0, str(ROOT)) import comp to_lin = lambda c: np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) to_srgb = lambda c: np.where(c <= 0.0031308, c * 12.92, 1.055 * np.clip(c, 0, None) ** (1 / 2.4) - 0.055) for shot in shots: cfg = comp.SHOTS[shot] out_dir = CLIPS / (shot + SUF) / "Output" fgs = sorted((out_dir / "FG").glob("*.exr")); mats = sorted((out_dir / "Matte").glob("*.exr")) plate = comp.plate_for(shot); parr = np.asarray(plate).astype(np.float32) / 255 accel = cfg.get("accel", False) if accel: # extend the plate: plate | mirrored | plate | mirrored | plate, so the scroll can go much further parr = np.concatenate([parr, parr[:, ::-1], parr, parr[:, ::-1], parr], axis=1) PW = parr.shape[1] W, H, FPS = comp.W, comp.H, comp.FPS dur = comp.shot_dur(shot); n = round(dur * FPS) ps = list(cfg["frames"].values()); fit = len(ps) > 1 clen = len(fgs) / 24.0 speed = clen / dur if fit else 1.0 out = OUTDIR / f"{shot}.mp4" enc = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}", "-r", str(FPS), "-i", "-", "-an", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", str(out)], stdin=subprocess.PIPE) for i in range(n): t = i / FPS if accel: # foreground at natural speed, played forward then backward (riders bounce in place) m = len(fgs); j = int(t * 24.0) % (2 * m - 2); k = j if j < m else 2 * m - 2 - j else: k = min(int(t * speed * 24.0), len(fgs) - 1) fg = cv2.cvtColor(cv2.imread(str(fgs[k]), cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB)[..., :3] a = cv2.imread(str(mats[k]), cv2.IMREAD_UNCHANGED) a = (a[..., 0] if a.ndim == 3 else a).astype(np.float32) fg = cv2.resize(fg, (W, H), interpolation=cv2.INTER_AREA); a = cv2.resize(a, (W, H), interpolation=cv2.INTER_AREA) fg[..., 1] = np.minimum(fg[..., 1], np.maximum(fg[..., 0], fg[..., 2]) + 0.01) # despill: green never above max(r, b) a0, a1 = cfg.get("pan", (0.0, 1.0)) u = min(max((t / dur - a0) / (a1 - a0), 0.0), 1.0) if accel: u = u ** 1.7 # accelerating scroll elif "pan" in cfg: u = u * u * (3 - 2 * u) travel = (PW - W) if accel else (plate.width - W) * (ps[-1] - ps[0]) x = round((0 if accel else (plate.width - W) * ps[0]) + travel * u) bgs = parr[:, x:x + W] if accel: # motion blur ~ scroll speed, slight shake at top speed v = travel * 1.7 * (t / dur) ** 0.7 / (dur * FPS) kw = int(min(121, max(1, v * 0.8))) | 1 bgs = cv2.blur(bgs, (kw, 1)) sh = int(round(3 * (t / dur) ** 3 * np.sin(i * 2.1))) bgs = np.roll(bgs, sh, axis=0) bg = to_lin(bgs) rgba = Image.fromarray(np.dstack([(np.clip(fg, 0, 1) * 255).astype(np.uint8), (np.clip(a, 0, 1) * 255).astype(np.uint8)]), "RGBA") sh = np.asarray(comp.floor_shadow(rgba)).astype(np.float32)[..., None] / 255 bg = bg * (1 - sh) al = np.clip(a, 0, 1)[..., None] res = to_srgb(bg * (1 - al) + to_lin(np.clip(fg, 0, 1)) * al) enc.stdin.write((np.clip(res, 0, 1) * 255 + 0.5).astype(np.uint8).tobytes()) enc.stdin.close(); enc.wait() print("wrote", out, f"({dur:.3f}s, {'speed-fit x%.2f' % speed if fit else 'trimmed'})")
if __name__ == "__main__": cmd, args = sys.argv[1], sys.argv[2:] {"prep": lambda: prep(args), "infer": infer, "video": lambda: video(args)}[cmd]()