File size: 3,870 Bytes
21e1acb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()