Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""Composite side-scrolling shots: one wide background plate + green-screen foregrounds.
Video models morph a background that differs between keyframes. Instead, each side-scroller gets ONE wide plate(previz/plates/<plate>.png, ~1.5-2 screens wide) that only ever pans, and the moving action is generated on chroma greenand keyed on top. World-fixed props (walls, signs, fences) belong on the plate; only moving characters and flyingdebris go in the foreground.
uv run --with pillow --with numpy python previz/comp.py frames [SHOT ...] Build keyframes: key previz/plates/fg_<frame>.png, lay it over the plate window at that frame's scroll position, write previz/keyframes/<frame>.png (1920x1080).
uv run --with pillow --with numpy python previz/comp.py video SHOT [SHOT ...] Given a green-screen clip previz/clips/green/<SHOT>.mp4 (generate it from the fg_ frames, i.e. on green), render previz/clips/<SHOT>.mp4: every frame keyed with key_video(), a per-column contact shadow, over the plate panning from the shot's first to last scroll position, exactly the shot's duration from previz/shots.json. (For hair, fur, motion blur and green-tinted shadows, key with CorridorKey instead: ck_key.py.)
uv run --with pillow --with numpy python previz/comp.py preview SHOT Plate-only pan (no foreground) for checking the scroll speed: previz/plates/preview_<SHOT>.mp4.
Shots are configured in previz/plates/plates.json: {"S21": {"plate": "street_plate.png", "frames": {"S21": 0.0, "S21_end": 1.0}}, "S44": {"plate": "hall_plate.png", "frames": {"S44": 0.25, "S44_m1": 0.5, "S44_end": 1.0}, "pan": [0.2, 0.85]}, "S50": {"plate": "road_plate.png", "frames": {"S50": 0.0}, "accel": true}}- frames: frame id -> scroll position, a fraction of the plate's scrollable width (0 = window at the left edge, 1 = at the right edge). Several frames = a start->end move (the green clip is speed-fitted to the shot); one frame = the clip plays at natural speed and is trimmed.- pan (optional): the part of the shot (fractions) in which the plate moves, eased; outside it the plate holds. Match it to when the green clip's props move, else props standing still in the clip glide over the floor.- accel (optional, ck_key.py): an accelerating ride — see ck_key.py."""import json, pathlib, subprocess, sysimport numpy as npfrom PIL import Image, ImageDraw, ImageFilter
ROOT = pathlib.Path(__file__).resolve().parentPLATES = ROOT / "plates"W, H, FPS = 1920, 1080, 30GREEN = (0, 177, 64) # #00B140: pick a screen colour far from the costumes_cfg = PLATES / "plates.json"SHOTS = json.load(open(_cfg)) if _cfg.exists() else {}
def plate_for(shot): im = Image.open(PLATES / SHOTS[shot]["plate"]).convert("RGB") return im.resize((round(im.width * H / im.height), H), Image.LANCZOS)
def window(plate, pos): x = round((plate.width - W) * pos) return plate.crop((x, 0, x + W, H))
def key(fg): """Soft chroma-green matte with spill suppression -> RGBA (for clean generated stills on #00B140).""" a = np.asarray(fg.convert("RGB")).astype(np.float32) / 255 r, g, b = a[..., 0], a[..., 1], a[..., 2] greenness = g - np.maximum(r, b) # >0 on the screen, <=0 on the subject alpha = np.clip(1 - (greenness - 0.08) / 0.18, 0, 1) # soft edge band # choke 1 px so the green/subject blend pixels (teal fringe after despill) drop out, then soften alpha = Image.fromarray((alpha * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(3)) alpha = np.asarray(alpha.filter(ImageFilter.GaussianBlur(0.8))) / 255 g2 = np.minimum(g, np.maximum(r, b) + 0.02) # despill: clamp green to the other channels out = np.dstack([r, g2, b, alpha]) return Image.fromarray((out * 255).astype(np.uint8), "RGBA")
def key_video(fg): """Key for generated green-screen clips. Their green is darker and less even than #00B140 and grey props pick up green spill, so key() makes spill-tinted greys half transparent. Here: a linear colour-difference matte against the local backdrop greenness (median per 16x9 cell of confident backdrop, smoothly upsampled), clipped so spill-tinted greys stay solid, combined with a brightness-independent term (greenness / green) so dark green shadows on the backdrop drop out.""" a = np.asarray(fg.convert("RGB")).astype(np.float32) / 255 r, g, b = a[..., 0], a[..., 1], a[..., 2] gr = g - np.maximum(r, b) ng = gr / np.maximum(g, 1e-3) back = ng > 0.5 h, w = gr.shape; gy, gx = 9, 16 glob = float(np.median(gr[back])) if back.any() else 0.3 cells = np.full((gy, gx), glob, np.float32) for i in range(gy): for j in range(gx): sl = np.s_[i * h // gy:(i + 1) * h // gy, j * w // gx:(j + 1) * w // gx] c = gr[sl][back[sl]] if c.size > 200: cells[i, j] = np.median(c) ref = np.asarray(Image.fromarray(cells, "F").resize((w, h), Image.BILINEAR)) lin = 1 - gr / np.maximum(ref, 0.05) alpha = np.minimum(np.clip((lin - 0.15) / 0.35, 0, 1), np.clip((0.5 - ng) / 0.12, 0, 1)) alpha = Image.fromarray((alpha * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(3)) alpha = np.asarray(alpha.filter(ImageFilter.GaussianBlur(0.8))) / 255 g2 = np.minimum(g, np.maximum(r, b) + 0.02) return Image.fromarray((np.dstack([r, g2, b, alpha]) * 255).astype(np.uint8), "RGBA")
def contact_shadow(fgk, strength=0.45): """Stills: a soft dark ellipse under the lowest opaque pixels of the foreground.""" a = np.asarray(fgk)[..., 3] ys, xs = np.nonzero(a > 200) sh = Image.new("L", fgk.size, 0) if len(ys): bottom, x0, x1 = ys.max(), xs.min(), xs.max() d = ImageDraw.Draw(sh) cx, wdt = (x0 + x1) / 2, (x1 - x0) * 0.45 d.ellipse([cx - wdt, bottom - 18, cx + wdt, bottom + 22], fill=int(255 * strength)) sh = sh.filter(ImageFilter.GaussianBlur(22)) return sh
def floor_shadow(fgk, floor=0.55, strength=0.4): """Video: a soft dark band along the lowest solid pixel of every column whose bottom lies in the floor zone (below floor*H), so the character and each prop get their own shadow and flying debris none.""" a = np.asarray(fgk)[..., 3] > 180 h, w = a.shape rows = np.arange(h)[:, None] bottom = np.where(a.any(0), (a * rows).max(0), -1) band = (rows >= bottom - 10) & (rows <= bottom + 12) & (bottom > floor * h)[None, :] return Image.fromarray((band * 255 * strength).astype(np.uint8)).filter(ImageFilter.GaussianBlur(9))
def build_frame(shot, fid, pos, plate): bg = window(plate, pos).convert("RGBA") fg = Image.open(PLATES / f"fg_{fid}.png").convert("RGB").resize((W, H), Image.LANCZOS) fgk = key(fg) black = Image.new("RGBA", (W, H), (0, 0, 0, 255)) bg = Image.composite(black, bg, contact_shadow(fgk)) return Image.alpha_composite(bg, fgk).convert("RGB")
def frames(shots): for shot in shots: plate = plate_for(shot) for fid, pos in SHOTS[shot]["frames"].items(): if not (PLATES / f"fg_{fid}.png").exists(): print("missing", PLATES / f"fg_{fid}.png"); continue build_frame(shot, fid, pos, plate).save(ROOT / "keyframes" / f"{fid}.png") print("wrote keyframes/%s.png (scroll %.2f)" % (fid, pos))
def shot_dur(shot): s = {x["id"]: x for x in json.load(open(ROOT / "shots.json"))}[shot] return (round(s["t1"] * FPS) - round(s["t0"] * FPS)) / FPS
def pan_filter(shot, plate_w, dur): ps = list(SHOTS[shot]["frames"].values()) x0, x1 = (plate_w - W) * ps[0], (plate_w - W) * ps[-1] return f"crop={W}:{H}:x='{x0:.1f}+({x1 - x0:.1f})*min(t/{dur:.4f},1)':y=0"
def video(shots): """Key every frame of the green clip, add a per-frame contact shadow, and lay it over the panning plate. Start->end shots (several frames) are speed-fitted to the shot length; single-frame shots are trimmed.""" for shot in shots: clip = ROOT / "clips" / "green" / f"{shot}.mp4" plate = plate_for(shot) dur = shot_dur(shot); n = round(dur * FPS) ps = list(SHOTS[shot]["frames"].values()) fit = len(ps) > 1 clen = probe(clip) speed = clen / dur if fit else 1.0 src = subprocess.run(["ffmpeg", "-v", "error", "-i", str(clip), "-vf", f"fps={FPS},scale={W}:{H}", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True, check=True).stdout frames_in = np.frombuffer(src, np.uint8).reshape(-1, H, W, 3) pw = plate.width; parr = np.asarray(plate) out = ROOT / "clips" / 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 k = min(int(round(t * speed * FPS)), len(frames_in) - 1) fgk = key_video(Image.fromarray(frames_in[k])) a0, a1 = SHOTS[shot].get("pan", (0.0, 1.0)) u = min(max((t / dur - a0) / (a1 - a0), 0.0), 1.0) if "pan" in SHOTS[shot]: u = u * u * (3 - 2 * u) x = round((pw - W) * (ps[0] + (ps[-1] - ps[0]) * u)) bg = Image.fromarray(parr[:, x:x + W]).convert("RGBA") black = Image.new("RGBA", (W, H), (0, 0, 0, 255)) bg = Image.composite(black, bg, floor_shadow(fgk)) enc.stdin.write(np.asarray(Image.alpha_composite(bg, fgk).convert("RGB")).tobytes()) enc.stdin.close(); enc.wait() print("wrote", out, f"({dur:.3f}s, {'speed-fit x%.2f' % speed if fit else 'trimmed'})")
def preview(shot): plate = plate_for(shot); tmp = PLATES / f"_{shot}_plate.png"; plate.save(tmp) dur = shot_dur(shot) subprocess.run(["ffmpeg", "-v", "error", "-y", "-loop", "1", "-framerate", str(FPS), "-i", str(tmp), "-vf", pan_filter(shot, plate.width, dur) + ",format=yuv420p", "-frames:v", str(round(dur * FPS)), "-c:v", "libx264", "-crf", "20", str(PLATES / f"preview_{shot}.mp4")], check=True) print("wrote", PLATES / f"preview_{shot}.mp4")
def probe(p): return float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(p)], capture_output=True, text=True).stdout)
if __name__ == "__main__": cmd, args = sys.argv[1], sys.argv[2:] {"frames": lambda: frames(args or list(SHOTS)), "video": lambda: video(args), "preview": lambda: preview(args[0])}[cmd]()