File size: 2,835 Bytes
a0a7bcd
 
af4674b
42948d1
 
af4674b
 
 
 
 
 
 
 
 
 
a0a7bcd
42948d1
a0a7bcd
05cc77e
 
 
 
 
 
42948d1
 
05cc77e
 
a0a7bcd
 
05cc77e
a0a7bcd
 
 
 
 
 
 
05cc77e
 
a0a7bcd
 
 
05cc77e
a0a7bcd
 
 
 
 
6ad4c05
 
 
 
42948d1
05cc77e
 
6ad4c05
 
 
 
 
 
a0a7bcd
 
 
6ad4c05
 
 
 
 
 
 
a0a7bcd
6ad4c05
a0a7bcd
05cc77e
a0a7bcd
42948d1
05cc77e
 
 
a0a7bcd
 
42948d1
af4674b
42948d1
05cc77e
a0a7bcd
 
42948d1
 
 
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
import argparse
import json
import numpy as np
import torch


def json_default(obj):
    if isinstance(obj, (np.integer,)):
        return int(obj)
    if isinstance(obj, (np.floating,)):
        return float(obj)
    if isinstance(obj, np.ndarray):
        return obj.tolist()
    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")

from sam3.model_builder import build_sam3_video_predictor


def main():
    parser = argparse.ArgumentParser(description="Detect objects in video first frame using SAM 3 text prompt")
    parser.add_argument("--video_path", required=True, help="Path to video (MP4 or JPEG folder)")
    parser.add_argument("--text", required=True, help="Text prompt for detection")
    parser.add_argument("--frame_index", type=int, default=0, help="Frame index to prompt on")
    parser.add_argument("--output_json", required=True, help="Output JSON path")
    args = parser.parse_args()

    # Build model (downloads from HF automatically if not cached)
    video_predictor = build_sam3_video_predictor()

    # Start session
    response = video_predictor.handle_request(
        request=dict(
            type="start_session",
            resource_path=args.video_path,
        )
    )
    session_id = response["session_id"]

    # Add text prompt on the specified frame
    response = video_predictor.handle_request(
        request=dict(
            type="add_prompt",
            session_id=session_id,
            frame_index=args.frame_index,
            text=args.text,
        )
    )

    outputs = response["outputs"]
    obj_ids = outputs["out_obj_ids"]
    probs = outputs["out_probs"]
    boxes_xywh = outputs["out_boxes_xywh"]
    binary_masks = outputs["out_binary_masks"]

    # Collect results
    instances = []
    for i in range(len(obj_ids)):
        obj_id = obj_ids[i]
        if torch.is_tensor(obj_id):
            obj_id = int(obj_id.detach().cpu())

        box = boxes_xywh[i]
        if torch.is_tensor(box):
            box = box.detach().cpu().tolist()

        # Convert xywh to xyxy
        x, y, w, h = box
        bbox_xyxy = [x, y, x + w, y + h]

        prob = probs[i]
        if torch.is_tensor(prob):
            prob = float(prob.detach().cpu().max()) if prob.numel() > 1 else float(prob.detach().cpu())

        instances.append(dict(id=obj_id, bbox_xyxy=bbox_xyxy, bbox_xywh=box, score=prob))

    result = dict(
        video_path=args.video_path,
        text=args.text,
        frame_index=args.frame_index,
        num_instances=len(instances),
        instances=instances,
    )

    with open(args.output_json, "w") as f:
        json.dump(result, f, indent=2, default=json_default)

    print(f"Found {len(instances)} objects for prompt '{args.text}'")
    print(f"Saved to {args.output_json}")


if __name__ == "__main__":
    main()