Segment Anything (SAM): A Comprehensive Tutorial
Table of Contents
Introduction
Segment Anything Model (SAM), developed by Meta AI, is a foundational model for image segmentation. It introduces zero-shot segmentation capability, meaning it can segment any object in any image without being specifically trained on that object class. SAM was trained on the SA-1B dataset containing over 1 billion masks from 11 million images, making it one of the most versatile segmentation models available.
This tutorial provides a comprehensive guide to using SAM, from basic prompting to advanced integration, fine-tuning, and production deployment.
Prerequisites
pip install segment-anything
pip install torch torchvision
pip install opencv-python numpy matplotlib
pip install Pillow
pip install onnxruntime # For ONNX-based deployment
System requirements:
- Python 3.8 or higher
- GPU with at least 8 GB VRAM (for ViT-H model; smaller models need less)
- CUDA 11.7 or higher
Download model checkpoints:
# ViT-H (default, highest quality) - 2.4 GB
wget https://dl.fbaipublicfiles.com/segmentanything/samvith4b8939.pth
ViT-L (large) - 1.2 GB
wget https://dl.fbaipublicfiles.com/segmentanything/samvitl0b3195.pth
ViT-B (base, smallest) - 375 MB
wget https://dl.fbaipublicfiles.com/segmentanything/samvitb01ec64.pth
Understanding SAM Architecture
SAM consists of three components:
The key insight of SAM's architecture is the decoupled design: the heavy image encoder runs once, while the lightweight prompt encoder and mask decoder can run many times for different prompts on the same image.
Installation and Setup
import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
from segmentanything import sammodelregistry, SamPredictor, SamAutomaticMaskGenerator
def loadsammodel(checkpointpath, modeltype="vith", device="cuda"):
"""
Load the SAM model.
modeltype options: 'vith', 'vitl', 'vitb'
"""
sam = sammodelregistrymodeltype
sam.to(device=device)
return sam
def displaymask(mask, ax, randomcolor=False):
"""Utility function to display a segmentation mask."""
if randomcolor:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])
h, w = mask.shape[-2:]
maskimage = mask.reshape(h, w, 1) color.reshape(1, 1, -1)
ax.imshow(maskimage)
def displaypoints(coords, labels, ax, markersize=375):
"""Display prompt points on the image."""
pospoints = coords[labels == 1]
negpoints = coords[labels == 0]
ax.scatter(pospoints[:, 0], pospoints[:, 1], color="green",
marker="", s=markersize, edgecolor="white", linewidth=1.25)
ax.scatter(negpoints[:, 0], negpoints[:, 1], color="red",
marker="", s=markersize, edgecolor="white", linewidth=1.25)
def displaybox(box, ax):
"""Display a bounding box on the image."""
x0, y0 = box[0], box[1]
w, h = box[2] - box[0], box[3] - box[1]
ax.addpatch(plt.Rectangle((x0, y0), w, h,
edgecolor="green", facecolor=(0, 0, 0, 0), lw=2))
Load model and create predictor
sam = loadsammodel("samvith4b8939.pth", modeltype="vith")
predictor = SamPredictor(sam)
Point-based Prompting
Point prompts are the simplest way to interact with SAM. You provide one or more points with labels (foreground=1 or background=0).
def segmentwithpoints(predictor, imagepath, points, labels):
"""
Segment an object using point prompts.
Args:
predictor: SamPredictor instance
image
path: Path to the input image
points: numpy array of shape (N, 2) with [x, y] coordinates
labels: numpy array of shape (N,) with 1=foreground, 0=background
Returns:
masks, scores, logits
"""
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
# Set the image (computes embeddings once)
predictor.setimage(imagergb)
# Predict masks
masks, scores, logits = predictor.predict(
pointcoords=points,
pointlabels=labels,
multimaskoutput=True, # Returns 3 masks for ambiguity
)
return masks, scores, logits
Example: Segment an object with a single foreground point
imagepath = "photo.jpg"
points = np.array([[500, 375]]) # [x, y] coordinate
labels = np.array([1]) # 1 = foreground
masks, scores, logits = segmentwithpoints(predictor, imagepath, points, labels)
Display results
image = cv2.cvtColor(cv2.imread(imagepath), cv2.COLORBGR2RGB)
for i, (mask, score) in enumerate(zip(masks, scores)):
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.imshow(image)
displaymask(mask, ax)
displaypoints(points, labels, ax)
ax.settitle(f"Mask {i + 1}, Score: {score:.3f}")
plt.savefig(f"maskpoint{i}.png")
plt.close()
Multi-point Prompting for Precision
def refinewithmultiplepoints(predictor, imagepath):
"""Use multiple points to precisely segment an object."""
image = cv2.imread(image
path)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
predictor.setimage(imagergb)
# Foreground points on the object, background points outside
points = np.array([
[500, 375], # foreground - center of object
[550, 400], # foreground - another point on object
[100, 100], # background - clearly outside
])
labels = np.array([1, 1, 0]) # 1=foreground, 0=background
masks, scores, logits = predictor.predict(
pointcoords=points,
pointlabels=labels,
multimaskoutput=False, # Single best mask
)
return masks[0], scores[0]
Box-based Prompting
Bounding box prompts are useful when you have object detection results and want to generate precise segmentation masks.
def segmentwithbox(predictor, imagepath, box):
"""
Segment an object using a bounding box prompt.
Args:
box: numpy array [x1, y1, x2, y2]
"""
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
predictor.setimage(imagergb)
masks, scores, logits = predictor.predict(
box=box,
multimaskoutput=False,
)
return masks[0], scores[0]
Example
box = np.array([200, 150, 600, 500]) # [x1, y1, x2, y2]
mask, score = segmentwithbox(predictor, "photo.jpg", box)
Combining box and point prompts
def segmentwithboxandpoints(predictor, imagepath, box, points, labels):
"""Combine box and point prompts for maximum precision."""
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
predictor.setimage(imagergb)
masks, scores, logits = predictor.predict(
pointcoords=points,
pointlabels=labels,
box=box,
multimaskoutput=False,
)
return masks[0], scores[0]
Use box to set the region, points to refine
box = np.array([200, 150, 600, 500])
points = np.array([[400, 300]]) # Additional foreground point
labels = np.array([1])
mask, score = segmentwithboxandpoints(predictor, "photo.jpg", box, points, labels)
Batch Box Prompting
def segmentmultipleboxes(predictor, imagepath, boxes):
"""Segment multiple objects using multiple box prompts."""
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
predictor.setimage(imagergb)
inputboxes = torch.tensor(boxes, device=predictor.device)
transformedboxes = predictor.transform.applyboxestorch(
inputboxes, imagergb.shape[:2]
)
masks, scores, = predictor.predicttorch(
pointcoords=None,
pointlabels=None,
boxes=transformedboxes,
multimaskoutput=False,
)
return masks.cpu().numpy(), scores.cpu().numpy()
Segment three objects
boxes = np.array([
[100, 100, 300, 300],
[400, 200, 600, 500],
[50, 400, 250, 600],
])
masks, scores = segmentmultipleboxes(predictor, "photo.jpg", boxes)
Text-based Prompting with Grounding
SAM does not natively support text prompts, but you can combine it with a grounding model like Grounding DINO.
# pip install groundingdino-py
from groundingdino.util.inference import loadmodel, predict
import groundingdino.datasets.transforms as T
def textpromptedsegmentation(imagepath, textprompt, sampredictor):
"""
Segment objects described by text using Grounding DINO + SAM.
"""
# Load Grounding DINO
groundingmodel = loadmodel(
"groundingdino/config/GroundingDINOSwinTOGC.py",
"weights/groundingdinoswintogc.pth"
)
# Detect objects with text prompt
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
transform = T.Compose([
T.RandomResize([800], maxsize=1333),
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
from PIL import Image
pilimage = Image.open(imagepath).convert("RGB")
transformedimage, = transform(pilimage, None)
boxes, logits, phrases = predict(
model=groundingmodel,
image=transformedimage,
caption=textprompt,
boxthreshold=0.3,
textthreshold=0.25,
)
# Convert normalized boxes to pixel coordinates
h, w = imagergb.shape[:2]
boxespixel = boxes np.array([w, h, w, h])
# Convert from cx, cy, bw, bh to x1, y1, x2, y2
boxesxyxy = np.zeroslike(boxespixel)
boxesxyxy[:, 0] = boxespixel[:, 0] - boxespixel[:, 2] / 2
boxesxyxy[:, 1] = boxespixel[:, 1] - boxespixel[:, 3] / 2
boxesxyxy[:, 2] = boxespixel[:, 0] + boxespixel[:, 2] / 2
boxesxyxy[:, 3] = boxespixel[:, 1] + boxespixel[:, 3] / 2
# Use SAM to segment each detected box
sampredictor.setimage(imagergb)
allmasks = []
for box in boxesxyxy:
masks, scores, = sampredictor.predict(
box=box,
multimaskoutput=False,
)
allmasks.append(masks[0])
return allmasks, boxesxyxy, phrases
Usage
masks, boxes, labels = textpromptedsegmentation(
"streetscene.jpg",
"car . person . traffic light",
predictor
)
Automatic Mask Generation
SAM can automatically segment everything in an image without any prompts.
def generateallmasks(sammodel, imagepath, params=None):
"""
Automatically generate masks for all objects in an image.
"""
defaultparams = {
"pointsperside": 32,
"prediouthresh": 0.88,
"stabilityscorethresh": 0.95,
"cropnlayers": 1,
"cropnpointsdownscalefactor": 2,
"minmaskregionarea": 100,
}
if params:
defaultparams.update(params)
maskgenerator = SamAutomaticMaskGenerator(sammodel, *defaultparams)
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
masks = maskgenerator.generate(imagergb)
# Sort by area (largest first)
masks = sorted(masks, key=lambda x: x["area"], reverse=True)
return masks
def visualizeautomaticmasks(imagepath, masks):
"""Visualize all automatically generated masks."""
image = cv2.cvtColor(cv2.imread(imagepath), cv2.COLORBGR2RGB)
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
ax.imshow(image)
for maskdata in masks:
mask = maskdata["segmentation"]
color = np.concatenate([np.random.random(3), [0.35]])
h, w = mask.shape
maskimage = mask.reshape(h, w, 1) color.reshape(1, 1, -1)
ax.imshow(maskimage)
ax.axis("off")
plt.tightlayout()
plt.savefig("allmasks.png", dpi=150, bboxinches="tight")
plt.close()
return len(masks)
Usage
masks = generateallmasks(sam, "complexscene.jpg")
nummasks = visualizeautomaticmasks("complexscene.jpg", masks)
print(f"Generated {nummasks} masks")
Access mask properties
for i, maskdata in enumerate(masks[:5]):
print(f"Mask {i}: area={maskdata['area']}, "
f"score={maskdata['predictediou']:.3f}, "
f"stability={maskdata['stabilityscore']:.3f}")
Integration with Other Models
SAM + YOLO for Instance Segmentation
from ultralytics import YOLO
def yolosamsegmentation(imagepath, sampredictor):
"""
Use YOLO for detection and SAM for precise segmentation.
This gives you both class labels and high-quality masks.
"""
# Detect with YOLO
yolomodel = YOLO("yolov8n.pt")
results = yolomodel(imagepath)
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
sampredictor.setimage(imagergb)
segmentedobjects = []
for result in results:
for box in result.boxes:
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
classid = int(box.cls[0])
classname = result.names[classid]
confidence = float(box.conf[0])
# Get SAM mask for this detection
sambox = np.array([x1, y1, x2, y2])
masks, scores, = sampredictor.predict(
box=sambox,
multimaskoutput=False,
)
segmentedobjects.append({
"class": classname,
"confidence": confidence,
"box": (x1, y1, x2, y2),
"mask": masks[0],
"maskscore": float(scores[0]),
})
return segmentedobjects
objects = yolosamsegmentation("photo.jpg", predictor)
for obj in objects:
print(f"{obj['class']}: conf={obj['confidence']:.2f}, "
f"maskscore={obj['maskscore']:.3f}")
Fine-tuning SAM
Fine-tuning SAM on domain-specific data can significantly improve performance for specialized tasks like medical imaging or satellite imagery.
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from segmentanything import sammodelregistry
class CustomSegmentationDataset(Dataset):
"""Dataset for fine-tuning SAM."""
def init(self, imagedir, maskdir, transform=None):
self.imagedir = imagedir
self.maskdir = maskdir
self.transform = transform
self.imagefiles = sorted(os.listdir(imagedir))
def len(self):
return len(self.imagefiles)
def getitem(self, idx):
imgname = self.imagefiles[idx]
image = cv2.imread(os.path.join(self.imagedir, imgname))
image = cv2.cvtColor(image, cv2.COLORBGR2RGB)
maskname = imgname.replace(".jpg", ".png")
mask = cv2.imread(
os.path.join(self.maskdir, maskname), cv2.IMREADGRAYSCALE
)
# Resize to SAM input size
image = cv2.resize(image, (1024, 1024))
mask = cv2.resize(mask, (256, 256))
image = torch.fromnumpy(image).permute(2, 0, 1).float() / 255.0
mask = torch.fromnumpy(mask).float() / 255.0
return image, mask
def finetunesam(samcheckpoint, dataset, numepochs=10, lr=1e-5):
"""
Fine-tune SAM's mask decoder (freeze the image encoder).
"""
sam = sammodelregistry"vitb"
sam.to("cuda")
# Freeze image encoder and prompt encoder
for param in sam.imageencoder.parameters():
param.requiresgrad = False
for param in sam.promptencoder.parameters():
param.requiresgrad = False
# Only train the mask decoder
optimizer = torch.optim.Adam(
sam.maskdecoder.parameters(),
lr=lr,
weightdecay=1e-4,
)
lossfn = nn.BCEWithLogitsLoss()
dataloader = DataLoader(dataset, batchsize=2, shuffle=True)
for epoch in range(numepochs):
sam.maskdecoder.train()
totalloss = 0
for images, gtmasks in dataloader:
images = images.to("cuda")
gtmasks = gtmasks.to("cuda")
# Get image embeddings (no grad needed)
with torch.nograd():
imageembeddings = sam.imageencoder(images)
# Use a center point as prompt
b, , h, w = images.shape
pointcoords = torch.tensor(
[[[512, 512]]], device="cuda"
).repeat(b, 1, 1).float()
pointlabels = torch.ones(b, 1, device="cuda")
sparseembeddings, denseembeddings = sam.promptencoder(
points=(pointcoords, pointlabels),
boxes=None,
masks=None,
)
# Predict masks
maskpredictions, ioupredictions = sam.maskdecoder(
imageembeddings=imageembeddings,
imagepe=sam.promptencoder.getdensepe(),
sparsepromptembeddings=sparseembeddings,
densepromptembeddings=denseembeddings,
multimaskoutput=False,
)
# Compute loss
maskpredictions = maskpredictions.squeeze(1)
loss = lossfn(maskpredictions, gtmasks.unsqueeze(1))
optimizer.zerograd()
loss.backward()
optimizer.step()
totalloss += loss.item()
avgloss = totalloss / len(dataloader)
print(f"Epoch {epoch + 1}/{numepochs}, Loss: {avgloss:.4f}")
# Save fine-tuned model
torch.save(sam.statedict(), "samfinetuned.pth")
return sam
Deployment
ONNX Export for Fast Inference
def exportsamtoonnx(sammodel, outputdir="samonnx"):
"""Export SAM components to ONNX for deployment."""
import os
os.makedirs(output
dir, existok=True)
# Export image encoder
dummy
image = torch.randn(1, 3, 1024, 1024).to("cuda")
torch.onnx.export(
sammodel.imageencoder,
dummyimage,
os.path.join(outputdir, "imageencoder.onnx"),
exportparams=True,
opsetversion=17,
inputnames=["image"],
outputnames=["imageembeddings"],
)
print("SAM exported to ONNX successfully")
def runonnxinference(onnxdir, imagepath, pointcoords, pointlabels):
"""Run SAM inference using ONNX Runtime."""
import onnxruntime as ort
# Load sessions
encodersession = ort.InferenceSession(
os.path.join(onnxdir, "imageencoder.onnx"),
providers=["CUDAExecutionProvider", "CPUExecutionProvider"]
)
# Preprocess image
image = cv2.imread(imagepath)
imagergb = cv2.cvtColor(image, cv2.COLORBGR2RGB)
imageresized = cv2.resize(imagergb, (1024, 1024))
inputtensor = imageresized.astype(np.float32).transpose(2, 0, 1)[None] / 255.0
# Get embeddings
embeddings = encodersession.run(None, {"image": inputtensor})[0]
return embeddings
FastAPI Deployment
from fastapi import FastAPI, File, UploadFile
from pydantic import BaseModel
import io
from PIL import Image
app = FastAPI()
Load SAM at startup
sam = loadsammodel("samvitb01ec64.pth", modeltype="vitb")
predictor = SamPredictor(sam)
class SegmentRequest(BaseModel):
points: list[list[int]] = []
labels: list[int] = []
box: list[int] = []
@app.post("/segment")
async def segmentimage(file: UploadFile = File(...), request: SegmentRequest = None):
"""Endpoint for image segmentation."""
imagebytes = await file.read()
image = np.array(Image.open(io.BytesIO(imagebytes)).convert("RGB"))
predictor.setimage(image)
kwargs = {"multimaskoutput": False}
if request and request.points:
kwargs["pointcoords"] = np.array(request.points)
kwargs["pointlabels"] = np.array(request.labels)
if request and request.box:
kwargs["box"] = np.array(request.box)
masks, scores, = predictor.predict(*kwargs)
mask = masks[0].astype(np.uint8) 255
maskimage = Image.fromarray(mask)
buffer = io.BytesIO()
maskimage.save(buffer, format="PNG")
return {"mask": buffer.getvalue().hex(), "score": float(scores[0])}
Best Practices
setimage() once and reuse the embeddings.multimaskoutput=True for ambiguous prompts (e.g., single point) and False when the prompt is unambiguous (e.g., detailed box).pointsperside for denser masks, adjust prediou_thresh to filter low-quality predictions.Conclusion
SAM represents a paradigm shift in image segmentation. Its zero-shot capability eliminates the need for task-specific training in many scenarios, while its promptable interface makes it highly flexible. By combining SAM with detection models, you get the best of both worlds: accurate class labels from the detector and precise pixel-level masks from SAM.
Whether you are building annotation tools, medical imaging systems, or autonomous driving perception modules, SAM provides a robust foundation. Fine-tuning the mask decoder on domain-specific data further unlocks performance gains for specialized applications.