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.
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.
| File | Use it for |
|---|---|
| Mask PNG per object | Photo editors, compositing, inpainting |
| ID map PNG | All objects in one file; analysis |
| Transparent PNG | Design, slides, product images |
| Overlay JPG | Quick visual review |
| manifest.json | Labels, 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.
| File | Mode | Values | Why |
|---|---|---|---|
| Mask | L (8-bit gray) | 0 and 255 | Opens correctly in every editor; 0/1 looks black |
| ID map | L or 16-bit | 0 = background, 1…N | 16-bit when there are more than 255 objects |
| Transparent cutout | RGBA | alpha 0…255 | The fourth channel holds the mask |
| Preview | RGB 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 manifestWorks 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 neededUltralytics’ 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.
- Mask files stay hard: 0 or 255 only, so they can be counted and measured.
- Cutouts get a soft edge:
feather=1.0blurs 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.
- Cropped (the script’s default): smaller files, easy to place on slides or a web page.
pad=8leaves room for the soft edge. - Full size: needed for video frames, layer stacks and before/after comparisons. Save
rgbawithout 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.
- 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.
- 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.webmNo 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
| Problem | Fix |
|---|---|
| Background is black, not transparent | Save as .png in RGBA mode, not JPEG or RGB |
| Mask PNG looks all black | Values are 0/1; multiply by 255 |
| Mask is smaller or shifted | Resize to the original size with nearest-neighbour; check the target size in post-processing |
| Grey speckles in the mask | A soft mask was saved; threshold at 0.5 first |
| Halo around the cutout | Shrink the mask 1 px, then feather. Improve mask quality |
| Wrong object or extra objects exported | Select first: select specific objects |
| ID map looks empty | Values 1, 2, 3 are nearly black; that’s expected. Read it in code or stretch the contrast |
| Files out of order | Use 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.