"""What moves in a recording: found as what other moments see through, followed through the video, and put back as filmed. python scripts/splat/moving.py DATA RENDERS RECORDING [--build BUILD] DATA is the cameras.py and depth.py output, RENDERS a folder with every kept frame as the trained splats alone show it (train_cuda.py --renders), RECORDING the video. Splats are one still scene: a figure walking through it is drawn as a smear, and the frame differs from the render where the figure is. So it does where the splats are merely poor. What tells the two apart is geometry, not colour: where one frame saw a surface and a frame of another moment looks straight through that place to something further, the surface has gone. Such a patch is a piece of something that moves. $GBB_SPLAT_SEGMENT (scripts/splat/segment_cuda.py: SAM 2.1) then follows the whole thing through every frame of the video from that piece, and a thing is kept if other moments see through it as a whole. Where people.py has looked for people (DATA/people), their bodies are followed first and are kept whether or not other moments see through them. With controller.json's "view": "third" one of them is the player's own figure: a person there most of the time and never far from one place on the screen, which no other moment sees through and which is kept all the same. Without --build: writes DATA/moved/NAME.png for the kept frames with such things (black = leave out of training), so that a second training gives the place without them; the things' outlines on every frame stay in DATA/things. With --build (after that training, on its renders, and pack.py): a thing is dropped if the place, trained without ever seeing it, shows it all the same (a post the depths misjudged is still there, taught by the frames in which it was not followed; a walker, a door since opened or something picked up is not). For the rest it writes BUILD/moving.json and BUILD/moving/thing-K-S.png: every frame's picture of each thing (a cell of a sheet), where it stood, how large it was and from where it was seen (`from` the way the camera looked, `eye` where the camera was; `box` is where it was in the picture, 0 to 1), in the game's frame, and BUILD/moving/thing-K-ref.png, its largest whole picture at the recording's own size (what actors.py has a model made from). moving.js stands each picture up at its place at its moment: from the recording's path it shows what the recording showed. It is a flat picture, not a body: what the camera did not see is not there. """ from __future__ import annotations import argparse import json import os import subprocess from pathlib import Path import cv2 import numpy as np STRONG, WEAK = 0.12, 0.05 # a patch has a pixel that differs this much (of the range), and reaches as far as pixels that differ this much SMALLEST = 0.0005 # of the picture: smaller patches are ignored SHORTEST = 5 # kept frames a thing has to be on SHEET = 2048 # a sheet of a thing's pictures is this many pixels square THROUGH, MOST = 1.25, 0.5 # seen through: another moment sees this much further at that place; a patch moves if most of it is ABSENT = 0.2 # ... and the place, trained without the thing, lacks this much of it in half of its frames # (what the place has anyway lacked 0.01 to 0.07 of itself, the faintest real thing 0.27) FURTHER = 2.5 # ... judged only by frames at most this many times further from the place (depth from one picture is poor far off) def difference(frame, render, like=None): """How much the frame differs from the render at each pixel (of the range). With ``like``, the render is first made as light as the frame over those pixels: lighter or darker as a whole is the exposure or the place's light, not a thing.""" if like is not None and like.any(): render = render * np.clip(frame[like].mean() / max(float(render[like].mean()), 1e-3), 0.5, 2.0) differ = np.full(frame.shape[:2], 9.0, np.float32) for dy, dx in ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0)): # a render a pixel soft at an edge is not a difference differ = np.minimum(differ, np.abs(frame - np.roll(render, (dy, dx), (0, 1))).mean(2)) return cv2.GaussianBlur(differ, (0, 0), 2) def patches(frame, render, valid): """Connected patches where the frame is not the render: (mask, how much they differ).""" differ = difference(frame, render) * valid weak = cv2.morphologyEx((differ > WEAK).astype(np.uint8), cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8)) count, labels, stats, _ = cv2.connectedComponentsWithStats(weak) found = [k for k in range(1, count) if stats[k, cv2.CC_STAT_AREA] >= SMALLEST * weak.size and differ[labels == k].max() > STRONG] return [labels == k for k in found], differ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("data", type=Path); parser.add_argument("renders", type=Path); parser.add_argument("recording", type=Path) parser.add_argument("--build", type=Path, default=None) args = parser.parse_args() def every_frame() -> Path: """Every frame of the video as a picture (DATA/frames/NNNNN.jpg, counted from 0).""" if not (args.data / "frames").is_dir(): (args.data / "frames").mkdir() subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-i", str(args.recording), "-start_number", "0", "-q:v", "3", str(args.data / "frames" / "%05d.jpg")], check=True) return args.data / "frames" cameras = json.loads((args.data / "poses.json").read_text()); frames, W, H, f = cameras["poses"], cameras["width"], cameras["height"], cameras["focal"] rate = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=avg_frame_rate", "-of", "csv=p=0", str(args.recording)], capture_output=True, text=True).stdout.strip().split("/") every = max(1, round(float(rate[0]) / float(rate[1] if len(rate) > 1 else 1) / cameras["fps"])) # kept frame NNNNN.jpg is video frame (NNNNN - 1) * every video = lambda i: (int(Path(frames[i]["name"]).stem) - 1) * every far = {} # every kept frame's depths, small; the sky is further than anything for i, frame in enumerate(frames): stem = Path(frame["name"]).stem if (args.data / "depth" / (stem + ".npy")).is_file(): far[i] = np.load(args.data / "depth" / (stem + ".npy")).astype(np.float32) if (args.data / "sky" / (stem + ".png")).is_file(): far[i][cv2.resize(cv2.imread(str(args.data / "sky" / (stem + ".png")), cv2.IMREAD_GRAYSCALE), far[i].shape[::-1], interpolation=cv2.INTER_NEAREST) > 127] = np.inf def gone(i, mask): """Share of a patch of frame i (its surface, by the frame's depths) that frames of other moments look straight through.""" here = cv2.resize(np.where(np.isfinite(far[i]), far[i], 0), (W, H), interpolation=cv2.INTER_NEAREST) ys, xs = np.nonzero(mask & (here > 0)) if len(xs) < 20: return None some = np.random.default_rng(0).permutation(len(xs))[:300]; deep = here[ys[some], xs[some]] points = np.array(frames[i]["centre"]) + (np.stack([(xs[some] - W / 2) / f, (ys[some] - H / 2) / f, np.ones(len(some))], 1) * deep[:, None]) @ np.array(frames[i]["rotation"]).T through = there = 0 for j in list(far)[::max(1, len(far) // 48)]: if abs(frames[j]["t"] - frames[i]["t"]) < 1.0: continue at = (points - np.array(frames[j]["centre"])) @ np.array(frames[j]["rotation"]); z = at[:, 2]; h, w = far[j].shape u, v = (f * at[:, 0] / np.maximum(z, 1e-6) + W / 2) * w / W, (f * at[:, 1] / np.maximum(z, 1e-6) + H / 2) * h / H ok = (z > 0.1) & (z < FURTHER * deep) & (u >= 0) & (u < w - 1) & (v >= 0) & (v < h - 1) beyond = far[j][v[ok].astype(int), u[ok].astype(int)]; known = beyond > 0 through += int((beyond[known] > THROUGH * z[ok][known]).sum()); there += int((np.abs(beyond[known] - z[ok][known]) <= (THROUGH - 1) * z[ok][known]).sum()) return through / (through + there) if through + there >= 30 else None things = args.data / "things" screen = cv2.resize(cv2.imread(str(args.data / "mask.png"), cv2.IMREAD_GRAYSCALE), (W, H)) > 127 read = lambda path: cv2.resize(cv2.imread(str(path)), (W, H)).astype(np.float32) / 255 def place(i): """The pixels of frame i that show the place: not what is drawn on the screen, not the sky or its edge.""" valid = screen.copy(); stem = Path(frames[i]["name"]).stem for folder, keep in (("ignore", lambda m: m > 127), ("sky", lambda m: cv2.dilate((m > 127).astype(np.uint8), np.ones((25, 25), np.uint8)) == 0)): extra = args.data / folder / (stem + ".png") if extra.is_file(): valid &= keep(cv2.resize(cv2.imread(str(extra), cv2.IMREAD_GRAYSCALE), (W, H), interpolation=cv2.INTER_NEAREST)) return valid if not args.build: pieces = [] # (video frame, mask) of patches other moments see through people = json.loads((args.data / "people" / "seeds.json").read_text()) if (args.data / "people" / "seeds.json").is_file() else [] named = {frame["name"]: i for i, frame in enumerate(frames)} bodies = [(video(named[seed["image"]]), cv2.imread(str(args.data / "people" / seed["file"]), cv2.IMREAD_GRAYSCALE) > 127) for seed in people if seed["image"] in named] marks = [{key: seed[key] for key in ("box", "point", "named") if key in seed} for seed in people if seed["image"] in named] for i, frame in enumerate(frames): render = args.renders / (Path(frame["name"]).stem + ".jpg") if not render.is_file() or i not in far: continue for mask in patches(read(args.data / "images" / frame["name"]), read(render), place(i).astype(np.float32))[0]: if (gone(i, mask) or 0) >= MOST: pieces.append((video(i), mask)) for stale in (things, args.data / "moved", args.data / "pieces"): subprocess.run(["rm", "-rf", str(stale)]) if not pieces and not bodies: print("nothing in the recording moves"); return 0 pieces.sort(key=lambda piece: -piece[1].sum()); (args.data / "pieces").mkdir() pieces = bodies + pieces # people.py's bodies first (largest first, as it listed them): each a whole figure to follow for n, (_frame, mask) in enumerate(pieces): cv2.imwrite(str(args.data / "pieces" / f"{n}.png"), mask.astype(np.uint8) * 255) (args.data / "pieces" / "seeds.json").write_text(json.dumps([{"frame": frame, "file": f"{n}.png", "person": n < len(bodies)} | (marks[n] if n < len(bodies) else {}) for n, (frame, _mask) in enumerate(pieces)])) subprocess.run(os.environ["GBB_SPLAT_SEGMENT"].format(recording=args.recording, frames=every_frame(), seeds=args.data / "pieces", out=things), shell=True, check=True, cwd=Path(__file__).resolve().parents[2], capture_output=True) followed = json.loads((things / "things.json").read_text()); kept, marked = [], {} born = json.loads((things / "seeds.json").read_text()) if (things / "seeds.json").is_file() else {} # One thing followed twice (from a person's body, and from a patch that body's outline did not cover) is one thing: # where two outlines mostly lie in each other on the frames they share, the later is folded into the earlier. outline = lambda number, n: cv2.imread(str(things / number / f"{n:05d}.png"), cv2.IMREAD_GRAYSCALE) > 127 for a in list(followed) if bodies else []: # (only where people were looked for: a recording built without that is followed as it always was) for b in [b for b in followed if a in followed and int(b) > int(a)]: shared = sorted(set(followed[a]) & set(followed[b]) & {video(i) for i in far})[::3] inside = [(lambda p, q: (p & q).sum() / max(1, min(p.sum(), q.sum())))(outline(a, n), outline(b, n)) for n in shared] if len(inside) >= SHORTEST and np.median(inside) > 0.5: for n in followed[b]: cv2.imwrite(str(things / a / f"{n:05d}.png"), ((outline(a, n) if n in set(followed[a]) else False) | outline(b, n)).astype(np.uint8) * 255) followed[a] = sorted(set(followed[a]) | set(followed[b])); del followed[b] for flag in ("person", "named"): born.setdefault(a, {})[flag] = born.get(a, {}).get(flag) or born.get(b, {}).get(flag) (things / "things.json").write_text(json.dumps(followed)) numbers = args.data.parents[1] / "controller.json"; third = numbers.is_file() and json.loads(numbers.read_text()).get("view") == "third" player = None # a camera that follows the player's figure: a person, there most of the time, at one place on the screen for number, on in followed.items(): mine = [(i, cv2.imread(str(things / number / f"{video(i):05d}.png"), cv2.IMREAD_GRAYSCALE) > 127) for i in far if video(i) in set(on)] scores = [score for score in (gone(i, mask) for i, mask in mine) if score is not None] middles = np.array([[np.nonzero(m)[1].mean(), np.nonzero(m)[0].mean()] for _i, m in mine]) if mine else np.zeros((0, 2)) looked = np.array([np.array(frames[i]["rotation"])[:, 2] for i, _m in mine]) skies = [cv2.resize(cv2.imread(str(sky), cv2.IMREAD_GRAYSCALE), (W, H), interpolation=cv2.INTER_NEAREST) > 127 if sky.is_file() else np.zeros((H, W), bool) for sky in (args.data / "sky" / (Path(frames[i]["name"]).stem + ".png") for i, _m in mine)] sky = sum((m & s).sum() for (_i, m), s in zip(mine, skies)) / max(1, sum(m.sum() for _i, m in mine)) # the sky is behind everything: not a thing fixed = len(mine) > 1 and np.ptp(middles, 0).max() < 0.02 * W and np.degrees(np.arccos(np.clip(looked @ looked[0], -1, 1))).max() > 10 # a counter, a message person = bool(born.get(number, {}).get("person")) # (a person people.py found is taken to move whatever the depths say: where the cameras or the depths are poor, or # it walks a round and comes back, other moments do not see through it, and it is a figure all the same) moves = len(mine) >= SHORTEST and (person or (len(scores) >= 3 and np.median(scores) >= MOST)) and not fixed and sky < 0.3 told = bool(born.get(number, {}).get("named")); moves = moves or (told and len(mine) >= 2) # a thing people.py was told of (--point) is kept as told if (third and player is None and person and len(mine) >= 0.6 * len(far) and np.ptp(middles, 0).max() < 0.25 * W and abs(np.median(middles[:, 0]) - W / 2) < 0.25 * W and abs(np.median(middles[:, 1]) - H / 2) < 0.35 * H): # (not a face in a corner of the HUD) player, moves, fixed = number, True, False print(f"thing {number}: on {len(on)} frames of the video ({on[0] / (every * cameras['fps']):.1f} to {on[-1] / (every * cameras['fps']):.1f} s), " f"seen through by other moments: {np.median(scores) if scores else 0:.2f}{', named' if told else ', a person' if person else ''}{', sky' if sky >= 0.3 else ''}{', fixed on the screen' if fixed else ''}" f" -> {'the player, left out of the second training' if player == number else 'left out of the second training' if moves else 'left in the place'}") if moves: kept.append(number) for i, mask in mine: marked.setdefault(i, np.full((H, W), 255, np.uint8))[cv2.dilate(mask.astype(np.uint8), np.ones((15, 15), np.uint8)) > 0] = 0 (things / "kept.json").write_text(json.dumps(kept)); (things / "player.json").write_text(json.dumps(player)); (args.data / "moved").mkdir(exist_ok=True) (things / "named.json").write_text(json.dumps([number for number in kept if born.get(number, {}).get("named")])) for i, keep in marked.items(): cv2.imwrite(str(args.data / "moved" / (Path(frames[i]["name"]).stem + ".png")), keep) print(f"{len(kept)} things that move; {len(marked)} of {len(frames)} kept frames have something left out of training") return 0 every_frame() # to cut the things out of for stale in (args.build / "moving").glob("thing-*.png") if (args.build / "moving").is_dir() else []: stale.unlink() placed = json.loads((args.build / "splats.json").read_text()); turn, shift, scale = np.array(placed["turn"]), np.array(placed["shift"]), placed["scale"] out = args.build / "moving"; out.mkdir(exist_ok=True); listed = [] followed = json.loads((things / "things.json").read_text()) player = json.loads((things / "player.json").read_text()) if (things / "player.json").is_file() else None chosen = set(json.loads((things / "named.json").read_text())) if (things / "named.json").is_file() else set() for number in json.loads((things / "kept.json").read_text()): on = followed[number]; outline = lambda n: cv2.imread(str(things / number / f"{n:05d}.png"), cv2.IMREAD_GRAYSCALE) > 127 # The second training never saw this thing's pixels. If the place it gave shows the thing all the same, other # frames taught it: it stands there whenever it is looked at, the depths misjudged it, and its picture adds nothing. lacking = [] for i, frame in enumerate(frames): render = args.renders / (Path(frame["name"]).stem + ".jpg") if video(i) in set(on) and render.is_file(): mask = outline(video(i)) if mask.sum() >= 20: lacking.append(float((difference(read(args.data / "images" / frame["name"]), read(render), place(i) & ~mask)[mask] > STRONG).mean())) moves = (len(lacking) >= SHORTEST and np.median(lacking) >= ABSENT) or number == player or number in chosen print(f"thing {number}: the place without it lacks {np.median(lacking) if lacking else 0:.2f} of it -> {'moves' if moves else 'part of the place'}") if not moves: continue stood = {} # at the kept frames it is on: where it stood (the game's frame), how far off, when, seen from where for i in far: if video(i) in set(on): mask = outline(video(i)); here = cv2.resize(np.where(np.isfinite(far[i]), far[i], 0), (W, H), interpolation=cv2.INTER_NEAREST) deep = here[mask & (here > 0)] if len(deep) >= 20: # How far off it is: the depth of its own pixels, or of what it stands on, whichever is nearer. Depth # from one picture loses a small thing in what is behind it; the ground just under its lowest point is # a large surface and well measured. Under something in the air there is only what is further away. ys, xs = np.nonzero(mask); z = float(np.median(deep)); spin = np.array(frames[i]["rotation"]) under = here[ys.max() + 1:ys.max() + 9, (3 * xs.min() + xs.max()) // 4:(xs.min() + 3 * xs.max()) // 4 + 1] if (under > 0).sum() >= 8: z = min(z, float(np.median(under[under > 0]))) middle = np.array([((xs.min() + xs.max() + 1) / 2 - W / 2) / f, ((ys.min() + ys.max() + 1) / 2 - H / 2) / f, 1.0]) * z stood[video(i)] = (scale * turn @ (np.array(frames[i]["centre"]) + spin @ middle) + shift, scale * z, frames[i]["t"], turn @ spin[:, 2], -(turn @ spin[:, 1]), scale * turn @ np.array(frames[i]["centre"]) + shift) if len(stood) < 2: continue known = sorted(stood); cuts = []; best = ((False, 0), None) for n in on: # every frame of the video it is on, placed between the kept frames either side k = np.searchsorted(known, n); a, b = known[max(0, min(k, len(known)) - 1)], known[min(k, len(known) - 1)] if min(abs(n - a), abs(n - b)) > 0.5 * every * cameras["fps"]: continue part = 0.0 if a == b else min(1.0, max(0.0, (n - a) / (b - a))); mix = [u + (v - u) * part for u, v in zip(stood[a], stood[b])] mask = outline(n); ys, xs = np.nonzero(mask); x0, x1, y0, y1 = max(0, xs.min() - 2), min(W, xs.max() + 3), max(0, ys.min() - 2), min(H, ys.max() + 3) picture = cv2.imread(str(args.data / "frames" / f"{n:05d}.jpg"))[y0:y1, x0:x1] soft = cv2.GaussianBlur(mask[y0:y1, x0:x1].astype(np.float32), (0, 0), 1.0) cuts.append((np.dstack([picture, (soft * 255).astype(np.uint8)]), {"t": round(float(mix[2]), 4), "at": mix[0].round(3).tolist(), "size": [round((x1 - x0) * mix[1] / f, 3), round((y1 - y0) * mix[1] / f, 3)], "from": mix[3].round(4).tolist(), "up": mix[4].round(4).tolist(), "far": round(float(mix[1]), 3), "eye": mix[5].round(3).tolist(), "box": [round(float(x0) / W, 4), round(float(y0) / H, 4), round(float(x1) / W, 4), round(float(y1) / H, 4)]})) whole = x0 > 0 and y0 > 0 and x1 < W and y1 < H # the largest picture of it that the frame does not cut off: what a model of it is made from if (whole, int(mask.sum())) > best[0]: best = ((whole, int(mask.sum())), cuts[-1][0]) if not cuts: continue cell = int(min(256, max(64, 2 ** np.ceil(np.log2(np.percentile([max(c.shape[:2]) for c, _row in cuts], 90)))))); side = SHEET // cell; sheets = [] for k, (cut, row) in enumerate(cuts): if k % (side * side) == 0: sheets.append(np.zeros((SHEET, SHEET, 4), np.uint8)) fit = min(1.0, cell / max(cut.shape[:2])); small = cv2.resize(cut, (max(1, round(cut.shape[1] * fit)), max(1, round(cut.shape[0] * fit))), interpolation=cv2.INTER_AREA) cy, cx = (k % (side * side)) // side * cell, (k % side) * cell; sheets[-1][cy:cy + small.shape[0], cx:cx + small.shape[1]] = small row["sheet"] = len(sheets) - 1; row["cell"] = [cx / SHEET, cy / SHEET, small.shape[1] / SHEET, small.shape[0] / SHEET] names = [] for k, sheet in enumerate(sheets): names.append(f"moving/thing-{number}-{k}.png"); cv2.imwrite(str(args.build / names[-1]), sheet) cv2.imwrite(str(args.build / f"moving/thing-{number}-ref.png"), best[1]) listed.append({"sheets": names, "seen": [row for _cut, row in cuts], "ref": f"moving/thing-{number}-ref.png", "player": number == player, "opponent": number in chosen}) (args.build / "moving.json").write_text(json.dumps({"things": listed}) + "\n") print(f"{len(listed)} things that move, cut out of {sum(len(t['seen']) for t in listed)} frames of the video") return 0 if __name__ == "__main__": raise SystemExit(main())