Meta SAM 3 Playground

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.

first_mask.py
Animation of running the first SAM 3 scriptA terminal runs python first_mask.py. Lines appear: loading SAM 3, found 2 objects with scores 0.94 and 0.91, and saved files. On the right, a black-and-white mask image of a dog appears as mask_0.png. terminal $ python first_mask.pyLoading SAM 3 ...Found 2 object(s) 0 score=0.94 → mask_0.png 1 score=0.91 → mask_1.pngSaved overlay.png, cutout.png mask_0.png
Illustration: run the script, get a mask file per object.

Goal

What You’ll Build

One photo and one word in; three image files out.

outputs
Animation of the three files the tutorial producesA photo of a dog on grass leads to three outputs that appear in turn: a black-and-white mask, a green overlay on the photo, and the dog cut out on a transparent checkerboard background. dog.jpgmask_0.pngoverlay.pngcutout.png all three come from the same masks tensor
Illustration of the files the tutorial produces.
  • 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.

  1. 1Get model accessRequest access to facebook/sam3 on Hugging Face and create a read token.
  2. 2Set up PythonCreate a Python 3.12 environment and install PyTorch with CUDA.
  3. 3Install SAM 3Clone facebookresearch/sam3 and run pip install -e .
  4. 4Log inRun hf auth login and paste your token.
  5. 5Run the scriptSave first_mask.py next to a photo and run python first_mask.py.
  6. 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/sam3

Access 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.png
build_sam3_image_model()Loads the ~848M-parameter model onto the GPU.
set_image()Runs the image encoder once and returns a state.
set_text_prompt()Finds every match for the phrase; returns masks, boxes, scores.
.squeeze().cpu()Turns each mask tensor into a 2D array PIL can save.

How it works

What the Script Actually Does

Four calls, one expensive step. Understanding this makes everything later faster.

pipeline
Animated diagram of what the script doesFive steps light up left to right: the PIL image, set_image runs the image encoder once, set_text_prompt sends the word dog, the detector finds every match, and the output holds masks, boxes and scores. PIL imagedog.jpgset_imageencoderoncetext prompt“dog”detectorfinds matchesoutputmasksboxesscores re-use the state: new prompts skip the encoder
Illustration of the data flow in first_mask.py.
  • Encoding is the slow part: set_image() does it once per photo.
  • Prompts are cheap: re-use state to 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-run

Make 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
Animation of the confidence thresholdThree animals in a photo: two dogs and a fox-like dog. At threshold 0.3, all three are masked, including the doubtful one at 0.38. At 0.5, only the two confident dogs remain. At 0.95, only the top dog at 0.96 remains. confidence_threshold dog 0.96dog 0.91fox? 0.380.3dog 0.96dog 0.910.5dog 0.960.95
Illustration: higher thresholds keep only confident matches.
  • 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

SymptomLikely causeFix
401 / gated repo errorNo approved access or not logged inRequest access, then hf auth login. Model access
ModuleNotFoundError: sam3Package not installed in this environmentActivate the env and pip install -e ./sam3
CUDA not availableCPU-only PyTorch or old driverReinstall PyTorch with the CUDA index URL; update the driver
CUDA out of memoryGPU too small or other jobs runningClose other jobs; smaller images. OOM fixes
Found 0 object(s)Prompt doesn’t match or threshold too highSimpler noun; lower threshold. Empty masks
Checkpoint / key errorsOld code with new weightsgit 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.

Keep reading