SAM2
Use Meta's SAM2 model through our Serverless Hosted API
Code sample
curl --location 'https://serverless.roboflow.com/sam2/segment_image' \
--header 'Content-Type: application/json' \
--data '{
"api_key": "YOUR_API_KEY",
"image": {"type": "url", "value": "https://storage.googleapis.com/com-roboflow-marketing/notebooks/examples/bicycle.png"},
"prompts": {"prompts": [{"points": [{"x": 300, "y": 250, "positive": true}]}]},
"sam2_version_id": "hiera_tiny"
}'pip install inference-sdk supervision opencv-pythonimport os
import urllib.request
import cv2
import numpy as np
import supervision as sv
from inference_sdk import InferenceHTTPClient
IMAGE_URL = "https://storage.googleapis.com/com-roboflow-marketing/notebooks/examples/bicycle.png"
IMAGE_PATH = "bicycle.png"
OUTPUT_PATH = "bicycle_annotated.png"
urllib.request.urlretrieve(IMAGE_URL, IMAGE_PATH)
image = cv2.imread(IMAGE_PATH)
height, width = image.shape[:2]
client = InferenceHTTPClient(
api_url="https://serverless.roboflow.com",
api_key=os.getenv("API_KEY"),
)
result = client.sam2_segment_image(
inference_input=IMAGE_PATH,
prompts=[
{"points": [{"x": 300, "y": 250, "positive": True}]}
],
sam2_version_id="hiera_tiny",
)
masks, xyxys, confidences = [], [], []
for pred in result["predictions"]:
contours = [np.array(poly, dtype=np.int32) for poly in pred.get("masks", []) if poly]
if not contours:
continue
mask = np.zeros((height, width), dtype=np.uint8)
cv2.fillPoly(mask, contours, 1)
ys, xs = np.where(mask > 0)
if xs.size == 0:
continue
masks.append(mask.astype(bool))
xyxys.append([xs.min(), ys.min(), xs.max(), ys.max()])
confidences.append(pred.get("confidence", 1.0))
detections = sv.Detections(
xyxy=np.array(xyxys, dtype=float),
mask=np.stack(masks, axis=0),
class_id=np.zeros(len(masks), dtype=int),
confidence=np.array(confidences, dtype=float),
)
annotated = sv.MaskAnnotator().annotate(scene=image.copy(), detections=detections)
cv2.imwrite(OUTPUT_PATH, annotated)
Last updated
Was this helpful?