Meta SAM 3 Playground

Guide · SAM 3 / 3.1 · export

How to Export SAM Masks and Transparent PNGs Turn SAM output into files that work everywhere: clean mask PNGs, one ID map for all objects, transparent cutouts with soft edges, and a manifest that records what’s in each file.

photo → mask → PNG
Animation of exporting a mask and a transparent PNGA photo of an orange mug on a table becomes a black-and-white mask PNG, then a transparent PNG where only the mug remains on a checkerboard that stands for transparency. photo.jpg · SAM 3 prompt “mug” mug_mask.png · 0 = background, 255 = object mug.png · RGBA, background transparent one result → two kinds of file
Illustration: one result, two file types.

Overview

What to Export From a SAM Result

SAM returns masks in memory. Decide which files the next tool needs, then write all of them in one pass.

export folder
Animation of a full export folderOne SAM result fans out into six files that appear in turn: a mask PNG per object, an ID map holding all objects, a transparent cutout, an overlay preview and a JSON manifest. SAM resultmasks · scores mask_00.pngobject 1 maskmask_01.pngobject 2 maskids.pngall objects, 1 filecutout_00.pngtransparentoverlay.jpgpreviewmanifest.jsonlabels, scores, boxes
Illustration of a complete export folder.
FileUse it for
Mask PNG per objectPhoto editors, compositing, inpainting
ID map PNGAll objects in one file; analysis
Transparent PNGDesign, slides, product images
Overlay JPGQuick visual review
manifest.jsonLabels, scores, boxes, file names

Need COCO RLE, polygons or YOLO labels instead? Mask export formats

Basics

PNG Settings That Matter

Most export problems come from saving the right pixels in the wrong mode.

FileModeValuesWhy
MaskL (8-bit gray)0 and 255Opens correctly in every editor; 0/1 looks black
ID mapL or 16-bit0 = background, 1…N16-bit when there are more than 255 objects
Transparent cutoutRGBAalpha 0…255The fourth channel holds the mask
PreviewRGB JPG—Small, for viewing only; never for masks

PNG is lossless, so masks stay exact. JPEG blurs edges and has no transparency.

Code

One Export Script for Masks and Transparent PNGs

Pass in the image path and SAM’s masks. It writes every file from the table above and returns the manifest.

export_sam.py

import json
from pathlib import Path
import numpy as np
from PIL import Image, ImageFilter

def to_bool(m, size):
    # any SAM mask (tensor, float, 0/1, extra dims) -> bool array at image size (w, h)
    if hasattr(m, "detach"):
        m = m.detach().cpu().numpy()
    m = np.asarray(m).squeeze()
    m = m > 0.5 if m.dtype != bool else m
    if m.shape[::-1] != size:  # resize with NEAREST so edges stay hard
        m = np.array(Image.fromarray(m.astype(np.uint8) * 255).resize(size, Image.NEAREST)) > 127
    return m

def export(image_path, masks, scores=None, label="object", out="export", pad=8, feather=1.0):
    img = Image.open(image_path).convert("RGB")
    stem = Path(image_path).stem
    folder = Path(out) / stem
    folder.mkdir(parents=True, exist_ok=True)
    w, h = img.size
    masks = [to_bool(m, (w, h)) for m in masks]
    scores = [float(s) for s in scores] if scores is not None else [1.0] * len(masks)
    ids = np.zeros((h, w), np.uint16)
    overlay = np.array(img, np.float32)
    items = []
    for i, (m, s) in enumerate(zip(masks, scores)):
        if not m.any():
            continue
        name = f"{label}_{i:02d}"
        # 1) mask PNG: 8-bit grayscale, 0 or 255
        Image.fromarray(m.astype(np.uint8) * 255, "L").save(folder / f"{name}_mask.png", optimize=True)
        # 2) transparent PNG: mask as alpha, soft edge, cropped with padding
        alpha = Image.fromarray(m.astype(np.uint8) * 255, "L")
        if feather:
            alpha = alpha.filter(ImageFilter.GaussianBlur(feather))
        rgba = img.copy()
        rgba.putalpha(alpha)
        ys, xs = np.nonzero(m)
        box = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
        crop = (max(box[0] - pad, 0), max(box[1] - pad, 0), min(box[2] + pad, w), min(box[3] + pad, h))
        rgba.crop(crop).save(folder / f"{name}.png", optimize=True)
        # 3) ID map and preview
        ids[m & (ids == 0)] = len(items) + 1
        overlay[m] = overlay[m] * 0.45 + np.array([185, 242, 90]) * 0.55
        items.append(dict(id=len(items) + 1, label=label, score=round(s, 4), area=int(m.sum()),
                          box_xyxy=box, crop_xyxy=list(crop),
                          mask=f"{name}_mask.png", cutout=f"{name}.png"))
    if len(items) < 256:
        Image.fromarray(ids.astype(np.uint8), "L").save(folder / "ids.png")
    else:
        Image.fromarray(ids, "I;16").save(folder / "ids.png")  # 16-bit for 256+ objects
    Image.fromarray(overlay.astype(np.uint8)).save(folder / "overlay.jpg", quality=90)
    manifest = dict(image=Path(image_path).name, width=w, height=h, objects=items)
    (folder / "manifest.json").write_text(json.dumps(manifest, indent=2))
    return manifest

Works with any interface: to_bool() accepts tensors or arrays, drops extra dimensions, thresholds soft masks and resizes to the image if needed.

Inputs

Get Masks From Each Interface

Same export() call, three ways to get masks. Setup: install SAM 3.

official repo

# official facebookresearch/sam3 (image)
from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor

processor = Sam3Processor(build_sam3_image_model())
state = processor.set_image(Image.open("mug.jpg"))
out = processor.set_text_prompt(state=state, prompt="mug")
export("mug.jpg", out["masks"], out["scores"], label="mug")

Transformers

# Hugging Face Transformers
import torch
from PIL import Image
from transformers import Sam3Processor, Sam3Model

model = Sam3Model.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3Processor.from_pretrained("facebook/sam3")
image = Image.open("mug.jpg").convert("RGB")
inputs = processor(images=image, text="mug", return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)
r = processor.post_process_instance_segmentation(
    outputs, threshold=0.5, mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist())[0]
export("mug.jpg", r["masks"], r["scores"], label="mug")

Ultralytics

# Ultralytics
from ultralytics.models.sam import SAM3SemanticPredictor

predictor = SAM3SemanticPredictor(overrides=dict(model="sam3.pt", conf=0.25, save=False))
predictor.set_image("mug.jpg")
r = predictor(text=["mug"])[0]
if r.masks is not None:
    export("mug.jpg", r.masks.data, r.boxes.conf, label="mug")  # to_bool resizes if needed

Ultralytics’ own isolation guide builds transparent PNGs the same way, by stacking the image with the mask as a fourth channel. Its save_crop=True option saves box crops with the original background, not transparency.

Transparency

How Alpha and Soft Edges Work

A transparent PNG is the photo plus one more channel. Where the mask is 255 the pixel shows; where it is 0 it disappears.

alpha channel
Animation of how a transparent PNG is builtRed, green and blue layers of the photo stack up, then the SAM mask is added as a fourth alpha layer. The result shows the mug on a checkerboard. Next, a hard edge and a softened edge are compared. RGB A = mask RGB + A → RGBA PNG (4 channels) hard edge (0 or 255) feathered (0…255) masks: keep hard · cutouts: soften 1–2 px
Illustration of RGBA and edge softening.
  • Mask files stay hard: 0 or 255 only, so they can be counted and measured.
  • Cutouts get a soft edge: feather=1.0 blurs the alpha by about a pixel, hiding the stair-step outline.
  • Hair, fur and glass: feathering isn’t matting. See clean edges.
  • Coloured fringe? Shrink the mask by a pixel before feathering.

Layout

Cropped or Full-Size Cutouts?

Crop for design work. Keep full size when the file must line up with the original image.

crop vs full
Animation of full-size versus cropped cutoutsA full-size transparent PNG keeps the mug at its original position in a large canvas. A dashed box traces the mug’s bounds plus padding, and the cropped PNG keeps only that area. full size · lines up with original cropped + 8 px pad
Illustration of full-size and cropped exports.
  • Cropped (the script’s default): smaller files, easy to place on slides or a web page. pad=8 leaves room for the soft edge.
  • Full size: needed for video frames, layer stacks and before/after comparisons. Save rgba without cropping.
  • Keep the position: the manifest stores crop_xyxy, so a cropped file can be placed back exactly.

Many images

Batch Export a Folder

One subfolder per image, consistent names, and a report of images where nothing was found.

batch_export.py

from pathlib import Path

rows = []
for path in sorted(Path("photos").glob("*.jpg")):
    out = processor.set_text_prompt(state=processor.set_image(Image.open(path)), prompt="mug")
    m = export(path, out["masks"], out["scores"], label="mug", out="export")
    rows.append((path.name, len(m["objects"])))
empty = [name for name, n in rows if n == 0]
print(f"{len(rows)} images, {len(empty)} with no objects:", empty[:10])
  • Names: export/<image>/<label>_00.png, …_00_mask.png, ids.png, overlay.jpg, manifest.json.
  • Zero-padded numbers (_00, _01) keep files sorted.
  • Empty results are listed so you can re-prompt them. Ideas: prompt examples.

Quality check

Check the Exported Files

Catch the common mistakes automatically before the files go anywhere.

common mistakes
Animation of the most common export mistakesThe same cutout saved three ways: as JPEG the background turns black, as a mask with values 0 and 1 the image looks all black, and as an RGBA PNG with values 0 and 255 it is correct. ✗ saved as .jpg → black background ✗ mask values 0/1 → looks all black ✓ RGBA .png, alpha 0/255
Illustration of two mistakes and the fix.
  • Sizes match the original image.
  • Masks contain only 0 and 255.
  • Cutouts are RGBA and actually contain transparent pixels.
  • ID map holds one number per object.

check_export.py

import json
from pathlib import Path
import numpy as np
from PIL import Image

def check(folder):
    folder = Path(folder)
    man = json.loads((folder / "manifest.json").read_text())
    size = (man["width"], man["height"])
    problems = []
    for o in man["objects"]:
        m = Image.open(folder / o["mask"])
        v = set(np.unique(np.array(m)).tolist())
        if m.size != size: problems.append(f"{o['mask']}: size {m.size} != {size}")
        if m.mode != "L" or not v <= {0, 255}: problems.append(f"{o['mask']}: mode {m.mode}, values {sorted(v)[:5]}")
        c = Image.open(folder / o["cutout"])
        if c.mode != "RGBA": problems.append(f"{o['cutout']}: no alpha channel ({c.mode})")
        elif np.array(c)[..., 3].min() == 255: problems.append(f"{o['cutout']}: alpha is fully opaque")
    ids = np.array(Image.open(folder / "ids.png"))
    if ids.max() != len(man["objects"]): problems.append(f"ids.png max {ids.max()} != {len(man['objects'])} objects")
    return problems or ["ok"]

for f in sorted(Path("export").iterdir()):
    print(f.name, check(f))

Video

Export Video Masks as PNG Sequences

Write one PNG per frame per object, at full size, with zero-padded frame numbers.

png sequence
Animation of exporting video masks as a PNG sequenceVideo frames pass through SAM 3 tracking and come out as numbered files: one mask PNG per frame per object, named with zero-padded frame numbers so they sort correctly. track obj1/00000.pngobj1/00001.pngobj1/00002.pngobj1/00003.png zero-padded names keep frames in order
Illustration of per-frame exports.
  • One folder per object: obj1/00000.png, obj1/00001.png …
  • Never crop video frames: every file must line up with its frame.
  • Need a single file? Turn the RGBA frames into WebM (VP9) with alpha; the code below shows the command.
  • Getting the masks: video segmentation with Python

Video

Video Export Code

export_video.py

from pathlib import Path
import numpy as np
from PIL import Image

# frame_masks: {frame_index: {obj_id: mask}} collected while propagating the video
def export_video(frame_masks, frames_dir, out="video_export"):
    for fi, objs in sorted(frame_masks.items()):
        frame = Image.open(Path(frames_dir) / f"{fi:05d}.jpg").convert("RGB")
        for oid, m in objs.items():
            m = to_bool(m, frame.size)
            d = Path(out) / f"obj{oid}"
            d.mkdir(parents=True, exist_ok=True)
            Image.fromarray(m.astype(np.uint8) * 255, "L").save(d / f"{fi:05d}.png")
            rgba = frame.copy()
            rgba.putalpha(Image.fromarray(m.astype(np.uint8) * 255, "L"))
            rgba.save(d / f"{fi:05d}_rgba.png")  # full size: frames must line up

# then, for a video with transparency:
# ffmpeg -framerate 30 -i video_export/obj1/%05d_rgba.png -c:v libvpx-vp9 -pix_fmt yuva420p obj1.webm

No code

Exporting Without Code

Playground and hosted APIs

  • Download from the playground, then open the file to confirm it’s a PNG with transparency.
  • Hosted SAM 3 APIs usually let you choose PNG, JPEG or WebP output. Pick PNG for masks and cutouts.
  • Compare services: SAM API guide

ComfyUI

  • Segment with the SAM 3 nodes, then use Join Image with Alpha and Save Image.
  • If the object turns transparent instead of the background, add Invert Mask before joining.
  • To save the mask itself, convert it to an image and save.
  • ComfyUI setup

Troubleshooting

Export Problems and Fixes

ProblemFix
Background is black, not transparentSave as .png in RGBA mode, not JPEG or RGB
Mask PNG looks all blackValues are 0/1; multiply by 255
Mask is smaller or shiftedResize to the original size with nearest-neighbour; check the target size in post-processing
Grey speckles in the maskA soft mask was saved; threshold at 0.5 first
Halo around the cutoutShrink the mask 1 px, then feather. Improve mask quality
Wrong object or extra objects exportedSelect first: select specific objects
ID map looks emptyValues 1, 2, 3 are nearly black; that’s expected. Read it in code or stretch the contrast
Files out of orderUse zero-padded numbers in names

Questions

Exporting Masks FAQ

Why is my transparent PNG showing a black background?

The file was saved without an alpha channel (RGB) or as JPEG. Save as PNG in RGBA mode, with the mask as the fourth channel.

Why does my mask PNG look completely black?

The mask was saved with values 0 and 1 instead of 0 and 255. Multiply by 255 before saving, or save in 1-bit mode.

Should I export one file per object or one file for all?

Both, for most workflows: one mask and cutout per object for editing, plus one ID map that holds every object in a single image.

What is an ID map?

A single grayscale PNG where each pixel stores the number of the object it belongs to: 0 for background, 1 for the first object, and so on. Use 16-bit PNG if you have more than 255 objects.

Should cutouts be cropped?

Crop with a few pixels of padding for design use. Keep full size when the cutout must line up with the original image or a video frame.

Can I save transparent images as JPEG?

No. JPEG has no transparency. Use PNG, or WebP with alpha if your tools support it.

Does SAM 3.1 change the export?

No. SAM 3.1 returns the same kind of masks, so the same export code works.

Keep reading