action-worldmodel-bench / detect_objects.py
syCen's picture
Update detect_objects.py
af4674b verified
Raw
History Blame Contribute Delete
2.84 kB
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()