Recreate-AAA / scripts /splat /segment_cuda.py
CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
4.17 kB
"""Follow things through a video from a patch of each (SAM 2.1), on a CUDA machine.
python segment_cuda.py FRAMES SEEDS OUT --weights sam2.1_hiera_large.pt
FRAMES holds every frame of the video as 00000.jpg, 00001.jpg, ...; SEEDS holds seeds.json, a list of
{"frame": index, "file": "N.png"} (white = a patch of something, on that frame; with "box": [x0, y0, x1, y1] in
the patch's pixels the thing is the one that fills that box, with "point": [x, y] the one at that point), largest first. Each patch is
followed forwards and backwards through the whole video; patches that fall inside a thing already followed are
dropped, so each thing is followed once: at most --people from seeds marked "person" and --most from the rest. Writes OUT/K/NNNNN.png (white = thing K on frame NNNNN, only frames it is
on), OUT/things.json ({"K": frames it is on}) and OUT/seeds.json ({"K": the seed it was followed from}). Needs torch
and the sam2 package.
"""
import argparse, json
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from sam2.build_sam import build_sam2_video_predictor
parser = argparse.ArgumentParser()
parser.add_argument("frames", type=Path); parser.add_argument("seeds", type=Path); parser.add_argument("out", type=Path)
parser.add_argument("--weights", type=Path, required=True); parser.add_argument("--config", default="configs/sam2.1/sam2.1_hiera_l.yaml")
parser.add_argument("--most", type=int, default=12); parser.add_argument("--people", type=int, default=24)
args = parser.parse_args()
seeds = json.loads((args.seeds / "seeds.json").read_text())
patch = lambda seed: np.asarray(Image.open(args.seeds / seed["file"]).convert("L")) > 127
predictor = build_sam2_video_predictor(args.config, str(args.weights), device="cuda")
things, born = {}, {}
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
state = predictor.init_state(video_path=str(args.frames), offload_video_to_cpu=True)
# (people are listed first and do not use up the patches' share: a place full of figures still has its other things followed)
while seeds and (sum(1 for s in born.values() if s.get("person")) < args.people if seeds[0].get("person") else sum(1 for s in born.values() if not s.get("person")) < args.most):
seed = seeds[0]; predictor.reset_state(state)
size = np.array([state["video_width"] / patch(seed).shape[1], state["video_height"] / patch(seed).shape[0]] * 2)
if seed.get("box"): # a whole body's box (in the patch's pixels) says more than a patch of it
predictor.add_new_points_or_box(inference_state=state, frame_idx=seed["frame"], obj_id=1, box=np.array(seed["box"], np.float32) * size)
elif seed.get("point"): # a thing pointed at: whatever is there
predictor.add_new_points_or_box(inference_state=state, frame_idx=seed["frame"], obj_id=1, points=np.array([seed["point"]], np.float32) * size[:2], labels=np.array([1], np.int32))
else:
predictor.add_new_mask(inference_state=state, frame_idx=seed["frame"], obj_id=1, mask=patch(seed))
on = {}
for backwards in (False, True):
for frame, _ids, logits in predictor.propagate_in_video(state, reverse=backwards):
mask = (logits[0, 0] > 0).cpu().numpy()
if mask.sum() >= 30:
on[frame] = mask
number = len(things) + 1; folder = args.out / str(number); folder.mkdir(parents=True, exist_ok=True)
for frame, mask in on.items():
Image.fromarray((mask * 255).astype(np.uint8)).save(folder / f"{frame:05d}.png")
things[str(number)] = sorted(on); born[str(number)] = seed
# what is left to follow: patches of which the thing just followed does not cover the larger part
seeds = [s for s in seeds[1:] if s["frame"] not in on or (patch(s) & on[s["frame"]]).sum() < 0.5 * patch(s).sum()]
print(f"thing {number}: on {len(on)} frames; {len(seeds)} patches left", flush=True)
(args.out / "things.json").write_text(json.dumps(things)); (args.out / "seeds.json").write_text(json.dumps(born))