Datasets:
File size: 6,968 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 | """Re-segment the hand-prompted frames with SAM 3.1 (runs on a CUDA machine).
Usage: python 06_sam31_refine_frames.py <images_dir> <instances_coco.json> <checkpoint.pt> <out_dir> [limit]
Every instance in instances_coco.json (AI-drafted polygon, GrabCut-snapped) is
turned into three positive click prompts placed deep inside its mask, one per
third of the object's long axis. SAM 3.1 (official facebookresearch/sam3 code,
checkpoint sam3.1_multiplex.pt) returns one mask per instance. Frames are fed
one at a time, each as its own one-image session; nothing is propagated between
frames here.
Outputs: sam31_masks/<frame>_instances.png, sam31_instances.json (per-instance
IoU against the draft mask) and overlays.
"""
import json
import shutil
import sys
from pathlib import Path
import cv2
import numpy as np
import torch
img_dir, coco_path, ckpt, out_dir = Path(sys.argv[1]), sys.argv[2], sys.argv[3], Path(sys.argv[4])
limit = int(sys.argv[5]) if len(sys.argv) > 5 else None
coco = json.load(open(coco_path))
cat = {c["id"]: c["name"] for c in coco["categories"]}
images = sorted(coco["images"], key=lambda i: i["id"])[:limit]
H, W = 576, 720
jpg_dir = out_dir / "frames_jpg"
if jpg_dir.exists():
shutil.rmtree(jpg_dir)
jpg_dir.mkdir(parents=True)
(out_dir / "sam31_masks").mkdir(exist_ok=True)
(out_dir / "sam31_overlays").mkdir(exist_ok=True)
for k, im in enumerate(images):
(jpg_dir / f"{k:05d}").mkdir()
cv2.imwrite(str(jpg_dir / f"{k:05d}" / "00000.jpg"), cv2.imread(str(img_dir / Path(im["file_name"]).name)),
[cv2.IMWRITE_JPEG_QUALITY, 98])
def draft_mask(a):
m = np.zeros((H, W), np.uint8)
for seg in a["segmentation"]:
cv2.fillPoly(m, [np.array(seg, np.int32).reshape(-1, 2)], 1)
return m
def click_points(m, n=3):
"""n clicks: deepest interior point in each third of the object's long axis."""
dt = cv2.distanceTransform(m, cv2.DIST_L2, 5)
ys, xs = np.nonzero(m)
pts = np.stack([xs, ys], 1).astype(np.float32)
axis = cv2.PCACompute(pts, mean=None)[1][0]
proj = pts @ axis
edges = np.quantile(proj, np.linspace(0, 1, n + 1))
out = []
for i in range(n):
sel = (proj >= edges[i]) & (proj <= edges[i + 1])
if sel.any():
j = np.argmax(dt[ys[sel], xs[sel]])
out.append([int(xs[sel][j]), int(ys[sel][j])])
return out
from sam3.model_builder import build_sam3_multiplex_video_predictor
predictor = build_sam3_multiplex_video_predictor(checkpoint_path=ckpt, use_fa3=False, async_loading_frames=False)
# Upstream start_session passes offload_state_to_cpu, which the SAM 3.1 multiplex
# init_state does not accept (TypeError at repo HEAD of 2026-11-15). Drop that one
# keyword; no model code is changed.
_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"})
THRESH = 0.0 # keep every returned mask; the score is recorded per instance instead
COLORS = {"white_insulated_jawed": (255, 200, 0), "dark_rod": (0, 165, 255), "fenestrated_grasper": (0, 255, 0),
"gauze": (255, 0, 255)}
results = []
for k, im in enumerate(images):
anns = [a for a in coco["annotations"] if a["image_id"] == im["id"]]
frame = cv2.imread(str(img_dir / Path(im["file_name"]).name))
vis, inst = frame.copy(), np.zeros((H, W), np.uint8)
sid = predictor.handle_request(dict(type="start_session", resource_path=str(jpg_dir / f"{k:05d}")))["session_id"]
clicks, got = {}, {}
def collect(out):
ids = [int(i) for i in np.asarray(out["out_obj_ids"]).reshape(-1)]
masks, probs = np.asarray(out["out_binary_masks"]), np.asarray(out["out_probs"]).reshape(-1)
for j, oid in enumerate(ids):
got[oid] = (masks[j].astype(np.uint8).reshape(masks.shape[-2], masks.shape[-1]), float(probs[j]))
for n, a in enumerate(anns):
dm = draft_mask(a)
oid = a["instance_index_in_mask_png"]
clicks[oid] = click_points(dm)
# The reply to the very first add_prompt of a session comes back empty (observed
# with repo HEAD of 2026-11-15); sending the same clicks again returns the mask.
for _ in range(2 if n == 0 else 1):
resp = predictor.handle_request(dict(
type="add_prompt", session_id=sid, frame_index=0, obj_id=oid, output_prob_thresh=THRESH,
points=[[x / W, y / H] for x, y in clicks[oid]], point_labels=[1] * len(clicks[oid])))
collect(resp["outputs"])
predictor.handle_request(dict(type="close_session", session_id=sid))
# paint gauze first so instruments, which lie in front of it, win overlapping pixels
for a in sorted(anns, key=lambda a: cat[a["category_id"]] != "gauze"):
dm, oid = draft_mask(a), a["instance_index_in_mask_png"]
pts = clicks[oid]
base = {"image_id": im["id"], "annotation_id": a["id"], "category": cat[a["category_id"]],
"draft_confidence": a["confidence"], "clicks": pts, "instance_index_in_mask_png": oid}
if oid not in got or got[oid][0].sum() == 0:
results.append({**base, "status": "no_mask_returned"})
continue
m, prob = got[oid]
if m.shape != (H, W):
m = cv2.resize(m, (W, H), interpolation=cv2.INTER_NEAREST)
iou = float((m & dm).sum() / max(1, (m | dm).sum()))
inst[m == 1] = oid
ys, xs = np.nonzero(m)
results.append({**base, "status": "ok", "sam31_score": round(prob, 3), "iou_vs_draft": round(iou, 3),
"area": int(m.sum()), "draft_area": int(dm.sum()),
"bbox": [int(xs.min()), int(ys.min()), int(xs.max() - xs.min() + 1), int(ys.max() - ys.min() + 1)]})
col = COLORS[cat[a["category_id"]]]
vis[m == 1] = (0.55 * vis[m == 1] + 0.45 * np.array(col)).astype(np.uint8)
cnts, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(vis, cnts, -1, col, 2)
dc, _ = cv2.findContours(dm, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(vis, dc, -1, (255, 255, 255), 1) # draft outline in white
for x, y in pts:
cv2.circle(vis, (x, y), 4, (0, 0, 255), -1)
cv2.imwrite(str(out_dir / "sam31_masks" / f"f{im['id']:05d}_instances.png"), inst)
cv2.imwrite(str(out_dir / "sam31_overlays" / f"f{im['id']:05d}_sam31.jpg"), vis, [cv2.IMWRITE_JPEG_QUALITY, 90])
json.dump({"model": "SAM 3.1 (sam3.1_multiplex.pt)", "prompt": "3 positive clicks per instance from the draft mask",
"instances": results}, open(out_dir / "sam31_instances.json", "w"), indent=1)
ok = [r for r in results if r["status"] == "ok"]
ious = np.array([r["iou_vs_draft"] for r in ok])
print("instances", len(results), "ok", len(ok), "IoU vs draft: median", round(float(np.median(ious)), 3),
"mean", round(float(ious.mean()), 3), "<0.5:", int((ious < 0.5).sum()))
|