Segment Anything (SAM)
Run Meta's original Segment Anything (SAM) API on a Dedicated Deployment or self-hosted Inference
Segment Anything is Meta's original promptable image segmentation model. You give it a point (or a box) inside an object, and it returns a mask marking that object's precise boundary.
SAM works in two steps:
Create an embedding for the image.
Prompt the model with the coordinates of the object you want to segment.
Embeddings are cached by image_id, so once an image is embedded you can send many prompts against it without re-encoding.
SAM API
Get your API Key
Create a Roboflow account, find your key on the Roboflow API settings page and make it available to your shell:
export ROBOFLOW_API_KEY="your-key-here"Embed an image
An embedding is a numeric representation of the image. SAM uses it to compute object locations. Set base_url to your Dedicated Deployment URL or a local Inference server.
import os
import requests
base_url = "http://localhost:9001"
api_key = os.environ["ROBOFLOW_API_KEY"]
payload = {
"image": {"type": "url", "value": "https://media.roboflow.com/quickstart/traffic.jpg"},
"image_id": "example_image_id",
}
response = requests.post(
f"{base_url}/sam/embed_image",
headers={"Authorization": f"Bearer {api_key}"},
json=payload,
)
embeddings = response.json()["embeddings"]The image_id caches the embedding, so later segmentation requests for the same image do not have to send it again.
Segment an object
Prompt the model with at least one point that lies on the object. point_labels marks each point as positive (1, include) or negative (0, exclude).
payload = {
"image": {"type": "url", "value": "https://media.roboflow.com/quickstart/traffic.jpg"},
"point_coords": [[380, 350]],
"point_labels": [1],
"image_id": "example_image_id",
}
response = requests.post(
f"{base_url}/sam/segment_image",
headers={"Authorization": f"Bearer {api_key}"},
json=payload,
)
masks = response.json()["masks"]The response contains segmentation masks for the object of interest.
Further reading
Last updated
Was this helpful?