Datasets:
File size: 8,622 Bytes
07f5340 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | """Dense instance tracks for the whole video with SAM 3.1 (runs on a CUDA machine).
Usage:
python 08_sam31_propagate.py extract <video> <frames_root>
python 08_sam31_propagate.py run <frames_root> <instances_coco_v2.json> <checkpoint.pt> <out_dir> <clip_ids>
clip_ids: "all", "3", "0-9" or "0,5,7"; append ":i/n" to take the clips with id % n == i
Each clip (250 source frames; the last has 120) is one SAM 3.1 session, run the
way the official video example does it:
1. text prompt TEXT on frame 0, then full propagation. The detector+tracker
finds and follows instruments anywhere in the clip ("text" tracks).
2. the clip's annotated keyframe (its middle frame) gets three positive clicks
per object from instances_coco_v2.json, then propagation in both directions
("click" tracks). These carry the appearance class and also cover gauze,
which the text prompt does not find.
Click-only prompting returns masks on the keyframe alone, because the pipeline
merges click results into the text pass; hence step 1 always runs first.
Where a click track and a text track cover the same pixels the model keeps the
click track. A text track that lay on a clicked instrument in the keyframe (at
least half of its pixels) is treated as the same object and dropped for the whole
clip; masks under MIN_AREA pixels are dropped. Track ids are local to a clip:
click tracks 101.. (100 + keyframe instance index), text tracks 1.. (model id + 1).
Outputs per clip: masks/clip_XX/<source frame>.png (pixel value = track id,
0 = background) and tracks/clip_XX.json (per-track class, source, per-frame
area / bbox / score).
"""
import json
import sys
import time
from pathlib import Path
import cv2
import numpy as np
CLIP, TOTAL, W, H = 250, 17370, 720, 576
TEXT, MIN_AREA = "metal tool", 150
mode = sys.argv[1]
if mode == "extract":
video, root = sys.argv[2], Path(sys.argv[3])
cap = cv2.VideoCapture(video)
i = 0
while True:
ok, f = cap.read()
if not ok:
break
d = root / f"clip_{i // CLIP:02d}"
if i % CLIP == 0:
d.mkdir(parents=True, exist_ok=True)
cv2.imwrite(str(d / f"{i % CLIP:05d}.jpg"), f, [cv2.IMWRITE_JPEG_QUALITY, 95])
i += 1
print("frames written", i)
sys.exit(0 if i == TOTAL else 1)
root, coco_path, ckpt, out_dir, spec = Path(sys.argv[2]), sys.argv[3], sys.argv[4], Path(sys.argv[5]), sys.argv[6]
n_clips = (TOTAL + CLIP - 1) // CLIP
shard = None
if ":" in spec:
spec, sh = spec.split(":")
shard = tuple(int(x) for x in sh.split("/"))
if spec == "all":
clips = list(range(n_clips))
elif "-" in spec:
a, b = spec.split("-")
clips = list(range(int(a), int(b) + 1))
else:
clips = [int(x) for x in spec.split(",")]
if shard:
clips = [c for c in clips if c % shard[1] == shard[0]]
coco = json.load(open(coco_path))
cat = {c["id"]: c["name"] for c in coco["categories"]}
by_frame = {}
for a in coco["annotations"]:
by_frame.setdefault(a["image_id"], []).append(a)
import torch # noqa: E402
from sam3.model_builder import build_sam3_multiplex_video_predictor # noqa: E402
predictor = build_sam3_multiplex_video_predictor(checkpoint_path=ckpt, use_fa3=False, async_loading_frames=False)
# Upstream start_session passes a keyword the SAM 3.1 init_state does not accept; drop it.
_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"})
(out_dir / "masks").mkdir(parents=True, exist_ok=True)
(out_dir / "tracks").mkdir(parents=True, exist_ok=True)
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 = np.asarray(o["out_binary_masks"])
probs = 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 c in clips:
t0 = time.time()
start = c * CLIP
n = min(TOTAL, start + CLIP) - start
key_src = 17310 if c == n_clips - 1 else start + CLIP // 2
key_local = key_src - start
anns = by_frame.get(key_src, [])
mdir = out_dir / "masks" / f"clip_{c:02d}"
mdir.mkdir(exist_ok=True)
meta = {"clip_id": c, "start_frame": start, "num_frames": n, "keyframe_source_index": key_src,
"model": "SAM 3.1 (sam3.1_multiplex.pt)", "text_prompt": TEXT, "tracks": {}, "status": "ok"}
per_frame, text_key = {}, {}
sid = predictor.handle_request(dict(type="start_session", resource_path=str(root / f"clip_{c:02d}")))["session_id"]
try:
predictor.handle_request(dict(type="add_prompt", session_id=sid, frame_index=0, text=TEXT))
per_frame = propagate(sid)
text_key = {mid + 1: v[0] for mid, v in per_frame.get(key_local, {}).items()}
if anns:
for a in anns:
tid = 100 + a["instance_index_in_mask_png"]
meta["tracks"][tid] = {"source": "click", "category": cat[a["category_id"]],
"keyframe_confidence": a["confidence"],
"keyframe_needs_review": a["needs_review"], "clicks": a["sam31_clicks"],
"frames": {}}
predictor.handle_request(dict(
type="add_prompt", session_id=sid, frame_index=key_local, obj_id=tid,
points=[[x / W, y / H] for x, y in a["sam31_clicks"]], point_labels=[1] * len(a["sam31_clicks"])))
per_frame = propagate(sid, propagation_direction="both", start_frame_index=key_local)
except Exception as e: # record and keep going with the other clips
meta["status"] = f"failed: {type(e).__name__}: {str(e)[:200]}"
predictor.handle_request(dict(type="close_session", session_id=sid))
torch.cuda.empty_cache()
# A text track that sat on a clicked instrument in the keyframe is the same object: drop it.
duplicates = set()
if anns and meta["status"] == "ok":
clicked = np.zeros((H, W), bool)
for mid, (m, _) in per_frame.get(key_local, {}).items():
if mid >= 100 and meta["tracks"][mid]["category"] != "gauze":
clicked |= m.astype(bool)
for tid, m in text_key.items():
if m.sum() and (m.astype(bool) & clicked).sum() / m.sum() >= 0.5:
duplicates.add(tid)
meta["text_tracks_dropped_as_duplicates"] = sorted(duplicates)
def order_key(tid): # gauze first, then text tracks, click instruments on top
t = meta["tracks"][tid]
return (t["category"] != "gauze", t["source"] == "click")
for t in range(n):
for mid in per_frame.get(t, {}):
tid = mid if mid >= 100 else mid + 1
if tid not in meta["tracks"] and tid not in duplicates:
meta["tracks"][tid] = {"source": "text", "category": "instrument_text_detected", "frames": {}}
for t in range(n):
inst = np.zeros((H, W), np.uint8)
got_t = {(mid if mid >= 100 else mid + 1): v for mid, v in per_frame.get(t, {}).items()}
got_t = {k: v for k, v in got_t.items() if k not in duplicates}
for tid in sorted(got_t, key=order_key):
m, score = got_t[tid]
if m.shape != (H, W):
m = cv2.resize(m, (W, H), interpolation=cv2.INTER_NEAREST)
if m.sum() < MIN_AREA:
continue
inst[m == 1] = tid
for tid in np.unique(inst)[1:]:
ys, xs = np.nonzero(inst == tid)
if len(xs) < MIN_AREA:
inst[inst == tid] = 0
continue
meta["tracks"][int(tid)]["frames"][start + t] = {
"area": int(len(xs)), "score": round(got_t[int(tid)][1], 3),
"bbox": [int(xs.min()), int(ys.min()), int(xs.max() - xs.min() + 1), int(ys.max() - ys.min() + 1)]}
cv2.imwrite(str(mdir / f"{start + t:05d}.png"), inst)
meta["tracks"] = {k: v for k, v in meta["tracks"].items() if v["frames"]}
meta["seconds"] = round(time.time() - t0, 1)
json.dump(meta, open(out_dir / "tracks" / f"clip_{c:02d}.json", "w"))
print(f"clip {c:02d} {meta['status']} keyframe_objs={len(anns)} "
f"tracks={[(k, v['source'][0], len(v['frames'])) for k, v in meta['tracks'].items()]} sec={meta['seconds']}",
flush=True)
|