Beginner tutorial · SAM 3 / 3.1 · ~30 minutes
SAM Python Tutorial: Your First Image Mask Install SAM 3, run a minimal working example of about 20 lines, and save a mask, an overlay and a transparent cut-out from a one-word text prompt.
Goal
What You’ll Build
One photo and one word in; three image files out.
- mask_0.png: white where the object is, black elsewhere. The building block for everything else.
- overlay.png: your photo with every match tinted, to check the result at a glance.
- cutout.png: the best match on a transparent background, ready for design tools.
- You’ll learn: the four calls every SAM 3 image app uses, and how to tune them.
Prefer no code? Try the playground first.
Step 0
Setup: Requirements and Install
SAM 3 needs Python 3.12+, PyTorch 2.7+ and an NVIDIA GPU with CUDA 12.6+. The model weights are gated.
- 1Get model accessRequest access to facebook/sam3 on Hugging Face and create a read token.
- 2Set up PythonCreate a Python 3.12 environment and install PyTorch with CUDA.
- 3Install SAM 3Clone facebookresearch/sam3 and run pip install -e .
- 4Log inRun hf auth login and paste your token.
- 5Run the scriptSave first_mask.py next to a photo and run python first_mask.py.
- 6Check the outputOpen mask_0.png, overlay.png and cutout.png.
terminal
conda create -n sam3 python=3.12 -y && conda activate sam3
pip install torch==2.10.0 torchvision --index-url https://download.pytorch.org/whl/cu128
git clone https://github.com/facebookresearch/sam3.git
pip install -e ./sam3
hf auth login # paste a token from the account approved for facebook/sam3Access help: Hugging Face access · Full install guide: install SAM 3 · Hardware: system requirements
Minimal working example
The Minimal Working Example
Save this as first_mask.py next to a photo called dog.jpg (any photo with a dog works), then run python first_mask.py.
first_mask.py
import numpy as np
from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor
# 1. Load the model (downloads the checkpoint on first run)
model = build_sam3_image_model()
processor = Sam3Processor(model)
# 2. Load your photo and encode it once
image = Image.open("dog.jpg").convert("RGB")
state = processor.set_image(image)
# 3. Ask for a concept with a short text prompt
out = processor.set_text_prompt(state=state, prompt="dog")
masks, scores = out["masks"], out["scores"]
print(f"Found {len(scores)} object(s)")
# 4. Save one black-and-white PNG per object
for i in range(len(scores)):
m = masks[i].squeeze().cpu().numpy().astype(np.uint8) * 255
Image.fromarray(m).save(f"mask_{i}.png")
print(f" {i} score={float(scores[i]):.2f} → mask_{i}.png")expected output (scores will differ)
$ python first_mask.py
Found 2 object(s)
0 score=0.94 → mask_0.png
1 score=0.91 → mask_1.pngHow it works
What the Script Actually Does
Four calls, one expensive step. Understanding this makes everything later faster.
- Encoding is the slow part:
set_image()does it once per photo. - Prompts are cheap: re-use
stateto ask for more things without re-encoding. - Every match counts: “dog” returns all dogs, each with its own mask and score.
- Outputs are tensors: masks, boxes and scores live on the GPU until you call
.cpu().
add to the script
for word in ["dog", "ball", "person"]:
out = processor.set_text_prompt(state=state, prompt=word)
print(word, len(out["scores"])) # encoder is not re-runMake it useful
Add an Overlay and a Transparent Cut-out
Append this to first_mask.py to turn masks into images people can use.
first_mask.py (continued)
# Overlay: tint every mask green on the original photo
overlay = np.array(image).copy()
for i in range(len(scores)):
m = masks[i].squeeze().cpu().numpy().astype(bool)
overlay[m] = (0.5 * overlay[m] + 0.5 * np.array([185, 242, 90])).astype(np.uint8)
Image.fromarray(overlay).save("overlay.png")
# Cut-out: use the best mask as the alpha channel
if len(scores):
best = int(scores.argmax())
alpha = Image.fromarray(masks[best].squeeze().cpu().numpy().astype(np.uint8) * 255)
cutout = image.convert("RGBA")
cutout.putalpha(alpha)
cutout.save("cutout.png")More formats (RLE, COCO, polygons): mask formats · export masks · background removal
Tune results
Tune Prompts and the Confidence Threshold
Too many matches, too few, or the wrong thing? Two knobs fix most cases.
- Threshold: current code lets you set it on the processor, e.g.
Sam3Processor(model, confidence_threshold=0.5). Raise it to drop doubtful matches; lower it if nothing is found. - Prompt wording: short, concrete nouns work best: “dog”, “red car”, “hard hat”.
- Be specific, not long: add one attribute rather than a sentence.
- Look-alikes: add negative example boxes; see the prompts guide.
- Rough edges: improve mask quality.
Troubleshooting
Common Errors and Fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 / gated repo error | No approved access or not logged in | Request access, then hf auth login. Model access |
| ModuleNotFoundError: sam3 | Package not installed in this environment | Activate the env and pip install -e ./sam3 |
| CUDA not available | CPU-only PyTorch or old driver | Reinstall PyTorch with the CUDA index URL; update the driver |
| CUDA out of memory | GPU too small or other jobs running | Close other jobs; smaller images. OOM fixes |
| Found 0 object(s) | Prompt doesn’t match or threshold too high | Simpler noun; lower threshold. Empty masks |
| Checkpoint / key errors | Old code with new weights | git pull and reinstall. Checkpoint loading |
Questions
Python Tutorial FAQ
What is the minimal code to get a SAM 3 mask in Python?
Build the model with build_sam3_image_model(), wrap it in Sam3Processor, call set_image() on a PIL image, then set_text_prompt() with a short noun like “dog”. The result holds masks, boxes and scores; save a mask with PIL.
Do I need a GPU for this tutorial?
For the official sam3 package, yes: an NVIDIA GPU with CUDA 12.6+. Without one, use a hosted API or the slower Ultralytics wrapper on CPU just to try it.
Why do I get an access or 401 error when loading the model?
The checkpoints are gated. Request access to facebook/sam3 on Hugging Face, wait for approval, then run hf auth login with a token from the same account.
Why did it find zero objects?
Use a short, concrete noun that matches what’s visible, check the photo actually contains it, and try a lower confidence threshold.
How do I save a transparent cut-out?
Convert the image to RGBA and use the mask (0 or 255) as the alpha channel with putalpha(), then save as PNG.
Can I use clicks or boxes instead of text?
Yes. SAM 3 also accepts points and boxes; see the repo’s image notebook, or use Sam3TrackerModel in Transformers or SAM("sam3.pt") in Ultralytics.
Does this work with SAM 3.1?
Yes. Pull the latest sam3 code, reinstall, and request access to facebook/sam3.1. The image steps stay the same.