yayalong's picture
Add files using upload-large-folder tool
21e1acb verified
Raw
History Blame Contribute Delete
3.87 kB
"""Run local SAM3 on a saved RGB image and write a binary mask.
This script is intentionally small and dependency-isolated: Task-E/Isaac can
call it from the SAM3 virtualenv without installing SAM3 into the Isaac env.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
import numpy as np
from PIL import Image
PROMPT_INPAINT = Path("/home/ubuntu/Documents/01Proj/sam3d_gs/submodule/Prompt-Inpaint")
if not PROMPT_INPAINT.exists():
raise SystemExit(f"Prompt-Inpaint not found: {PROMPT_INPAINT}")
sys.path.insert(0, str(PROMPT_INPAINT))
from src.sam3_predictor import SAM3Predictor # noqa: E402
def _bbox_area(mask: np.ndarray) -> int:
ys, xs = np.nonzero(mask)
if len(xs) == 0:
return 0
return int((xs.max() - xs.min() + 1) * (ys.max() - ys.min() + 1))
def main() -> None:
parser = argparse.ArgumentParser(description="Segment one image with local SAM3.")
parser.add_argument("--image", required=True, help="Input RGB image path.")
parser.add_argument("--out_mask", required=True, help="Output .npy binary mask path.")
parser.add_argument("--out_meta", default=None, help="Optional JSON metadata output.")
parser.add_argument("--out_candidates", default=None, help="Optional .npz with all candidate masks.")
parser.add_argument("--prompt", action="append", required=True, help="Text prompt. Can repeat.")
parser.add_argument("--threshold", type=float, default=0.35)
parser.add_argument("--mask_threshold", type=float, default=0.5)
parser.add_argument(
"--model",
default="/home/ubuntu/Documents/01Proj/sam3d_gs/submodule/Prompt-Inpaint/checkpoints/sam3.pt",
)
args = parser.parse_args()
image = np.asarray(Image.open(args.image).convert("RGB"))
predictor = SAM3Predictor(
model_id=args.model,
device="cuda",
threshold=args.threshold,
mask_threshold=args.mask_threshold,
)
predictor.set_image(image)
detections = []
for prompt in args.prompt:
detections.extend(predictor.detect(prompt))
candidates = []
image_area = image.shape[0] * image.shape[1]
for det in detections:
if det.mask is None:
continue
mask = det.mask.astype(bool)
area = int(mask.sum())
if area < 40 or area > int(image_area * 0.35):
continue
candidates.append(
{
"prompt": det.label,
"score": float(det.score),
"bbox": [int(v) for v in det.bbox],
"area": area,
"bbox_area": _bbox_area(mask),
"mask": mask,
}
)
if not candidates:
raise SystemExit("SAM3 produced no usable mask")
# Prefer confident, compact object masks. This avoids selecting the table or
# a merged scene-sized region when prompts are broad.
best = max(candidates, key=lambda c: (c["score"], -c["bbox_area"]))
out_mask = Path(args.out_mask)
out_mask.parent.mkdir(parents=True, exist_ok=True)
np.save(out_mask, best["mask"].astype(np.bool_))
if args.out_meta:
meta = {k: v for k, v in best.items() if k != "mask"}
meta["num_candidates"] = len(candidates)
Path(args.out_meta).parent.mkdir(parents=True, exist_ok=True)
Path(args.out_meta).write_text(json.dumps(meta, indent=2), encoding="utf-8")
if args.out_candidates:
cand_path = Path(args.out_candidates)
cand_path.parent.mkdir(parents=True, exist_ok=True)
masks = np.stack([c["mask"].astype(np.bool_) for c in candidates], axis=0)
metas = [
{k: v for k, v in c.items() if k != "mask"}
for c in candidates
]
np.savez_compressed(cand_path, masks=masks, metas=json.dumps(metas))
if __name__ == "__main__":
main()