"""Track the tissue an action is applied to, through a whole clip, with SAM 3.1 (CUDA machine). Usage: python 11_sam31_target_tissue.py targets.json: {"": {"keyframe": , "objects": [ {"id": 201, "name": "...", "clicks": [[x, y], ...], "frame": }, ...]}} Clicks are positive points in source pixels: placed by eye for clips 5, 40 and 43 (targets_tissue.json), generated by 20_tissue_clicks.py for the other clips (targets_tissue_auto.json, each object with its own prompt frame). An optional 5th argument "i/n" runs only the clips with id % n == i, to split the work over GPUs. Same session recipe as 08_sam31_propagate.py: text prompt "metal tool" on frame 0 and full propagation first (SAM 3.1 only propagates click objects after a text pass), then the tissue clicks on the keyframe, propagated in both directions. Only the tissue objects are saved: masks/clip_XX/.png (pixel value = object id; where two tissue masks overlap the later object in the list wins) and tracks/clip_XX.json (per-object per-frame area, bbox, score). """ import json import sys from pathlib import Path import cv2 import numpy as np import torch from sam3.model_builder import build_sam3_multiplex_video_predictor CLIP, W, H, MIN_AREA = 250, 720, 576, 150 root, targets, ckpt, out = Path(sys.argv[1]), json.load(open(sys.argv[2])), sys.argv[3], Path(sys.argv[4]) targets = targets.get("clips", targets) # the auto-click file wraps clips with a "skipped" list if len(sys.argv) > 5: # shard "i/n": clips with id % n == i i, n_sh = (int(x) for x in sys.argv[5].split("/")) targets = {k: v for k, v in targets.items() if int(k) % n_sh == i} predictor = build_sam3_multiplex_video_predictor(checkpoint_path=ckpt, use_fa3=False, async_loading_frames=False) _init_state = predictor.model.init_state predictor.model.init_state = lambda **kw: _init_state(**{k: v for k, v in kw.items() if k != "offload_state_to_cpu"}) def propagate(sid, **kw): frames = {} for resp in predictor.handle_stream_request(dict(type="propagate_in_video", session_id=sid, **kw)): o = resp["outputs"] ids = [int(i) for i in np.asarray(o["out_obj_ids"]).reshape(-1)] masks, probs = np.asarray(o["out_binary_masks"]), np.asarray(o["out_probs"]).reshape(-1) frames[int(resp["frame_index"])] = { i: (masks[k].reshape(masks.shape[-2], masks.shape[-1]).astype(np.uint8), float(probs[k])) for k, i in enumerate(ids)} return frames for cid, spec in targets.items(): c = int(cid) start = c * CLIP n = len(list((root / f"clip_{c:02d}").glob("*.jpg"))) key_local = spec["keyframe"] - start sid = predictor.handle_request(dict(type="start_session", resource_path=str(root / f"clip_{c:02d}")))["session_id"] predictor.handle_request(dict(type="add_prompt", session_id=sid, frame_index=0, text="metal tool")) propagate(sid) for o in spec["objects"]: # each object may have its own prompt frame predictor.handle_request(dict(type="add_prompt", session_id=sid, frame_index=o.get("frame", spec["keyframe"]) - start, obj_id=o["id"], points=[[x / W, y / H] for x, y in o["clicks"]], point_labels=[1] * len(o["clicks"]))) frames = propagate(sid, propagation_direction="both", start_frame_index=key_local) predictor.handle_request(dict(type="close_session", session_id=sid)) torch.cuda.empty_cache() ids = [o["id"] for o in spec["objects"]] meta = {"clip_id": c, "keyframe_source_index": spec["keyframe"], "model": "SAM 3.1 (sam3.1_multiplex.pt)", "objects": {o["id"]: {"name": o["name"], "clicks": o["clicks"], "prompt_frame": o.get("frame", spec["keyframe"]), "frames": {}} for o in spec["objects"]}} (out / "masks" / f"clip_{c:02d}").mkdir(parents=True, exist_ok=True) (out / "tracks").mkdir(parents=True, exist_ok=True) for t in range(n): lab = np.zeros((H, W), np.uint8) got = frames.get(t, {}) for oid in ids: if oid not in got: continue m, score = got[oid] if m.shape != (H, W): m = cv2.resize(m, (W, H), interpolation=cv2.INTER_NEAREST) if m.sum() >= MIN_AREA: lab[m == 1] = oid for oid in ids: ys, xs = np.nonzero(lab == oid) if len(xs) >= MIN_AREA: meta["objects"][oid]["frames"][start + t] = { "area": int(len(xs)), "score": round(got[oid][1], 3), "bbox": [int(xs.min()), int(ys.min()), int(xs.max() - xs.min() + 1), int(ys.max() - ys.min() + 1)]} cv2.imwrite(str(out / "masks" / f"clip_{c:02d}" / f"{start + t:05d}.png"), lab) json.dump(meta, open(out / "tracks" / f"clip_{c:02d}.json", "w")) print("clip", c, {oid: len(v["frames"]) for oid, v in meta["objects"].items()}, flush=True)