Developers · SAM 3 / 3.1 outputs
SAM Mask Export Formats Explained SAM 3 hands you masks as tensors. This guide shows one workflow that turns a single run into every common format, from PNG and COCO RLE to polygons and YOLO-seg, and explains when to use each.
Overview
Formats Supported by This Workflow
The demonstrated workflow is: SAM 3 in Python (text prompt) → boolean masks in memory → export. These are the formats it writes, plus the formats hosted APIs return.
mask_0.png · edit, viewCut-out PNGcutout.png · designNumPy .npzexact arrays · PythonCOCO RLEdatasets · storagePolygonslabelling toolsYOLO-seg .txtYOLO trainingVideo formatsindexed PNG · RLE per frameHosted API outputsURLs · RLE · polygonsThe starting point is the minimal example from the Python tutorial; for video, the script in video segmentation with Python.
Demonstrated workflow
One Script, Every Format
Run SAM 3 once, then write PNG masks, a cut-out, a NumPy archive, COCO RLE, COCO polygons and a YOLO-seg label file. Boxes are computed from each mask so their format is unambiguous.
export_masks.py
import json
import cv2
import numpy as np
from PIL import Image
from pycocotools import mask as mask_utils # pip install pycocotools opencv-python
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor
IMAGE, PROMPT, YOLO_CLASS = "street.jpg", "yellow taxi", 0
# --- the demonstrated workflow: one SAM 3 run ---
image = Image.open(IMAGE).convert("RGB")
W, H = image.size
processor = Sam3Processor(build_sam3_image_model())
out = processor.set_text_prompt(state=processor.set_image(image), prompt=PROMPT)
masks = [m.squeeze().cpu().numpy().astype(bool) for m in out["masks"]]
scores = [float(s) for s in out["scores"]]
print(f"{len(masks)} object(s)")
# 1. Binary PNG, one file per object (0 / 255)
for i, m in enumerate(masks):
Image.fromarray(m.astype(np.uint8) * 255).save(f"mask_{i}.png")
# 2. Transparent cut-out of all matches (RGBA PNG)
union = np.any(masks, axis=0) if masks else np.zeros((H, W), bool)
cutout = image.convert("RGBA")
cutout.putalpha(Image.fromarray(union.astype(np.uint8) * 255))
cutout.save("cutout.png")
# 3. NumPy archive (exact, Python-only)
np.savez_compressed("masks.npz", masks=np.array(masks), scores=np.array(scores))
# 4. COCO JSON with RLE and 5. COCO JSON with polygons and 6. YOLO-seg
base = {"images": [{"id": 1, "file_name": IMAGE, "width": W, "height": H}],
"categories": [{"id": 1, "name": PROMPT}]}
rle_anns, poly_anns, yolo_lines = [], [], []
for i, (m, s) in enumerate(zip(masks, scores)):
m8 = m.astype(np.uint8)
x, y, w, h = cv2.boundingRect(m8) # box from the mask itself
common = {"id": i + 1, "image_id": 1, "category_id": 1, "bbox": [x, y, w, h],
"area": int(m.sum()), "iscrowd": 0, "score": s}
rle = mask_utils.encode(np.asfortranarray(m8))
rle["counts"] = rle["counts"].decode("ascii")
rle_anns.append({**common, "segmentation": rle})
contours, _ = cv2.findContours(m8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
polys = [c.flatten().tolist() for c in contours if len(c) >= 3]
poly_anns.append({**common, "segmentation": polys})
if contours:
big = max(contours, key=cv2.contourArea).reshape(-1, 2) / [W, H]
yolo_lines.append(f"{YOLO_CLASS} " + " ".join(f"{v:.6f}" for v in big.flatten()))
json.dump({**base, "annotations": rle_anns}, open("coco_rle.json", "w"))
json.dump({**base, "annotations": poly_anns}, open("coco_polygons.json", "w"))
open("street.txt", "w").write("\n".join(yolo_lines)) # YOLO label file, same stem as the image
print("Wrote mask_*.png, cutout.png, masks.npz, coco_rle.json, coco_polygons.json, street.txt")example output
$ python export_masks.py
3 object(s)
Wrote mask_*.png, cutout.png, masks.npz, coco_rle.json, coco_polygons.json, street.txt
$ ls
coco_polygons.json coco_rle.json cutout.png mask_0.png mask_1.png mask_2.png masks.npz street.txtCompare
Which Format Should You Use?
| Format | Lossless? | Multiple objects | Best for | Read by |
|---|---|---|---|---|
| Binary PNG | Yes | One file each | Viewing, editing, compositing | Any image tool, PIL, OpenCV |
| Cut-out PNG (RGBA) | Yes | Merged | Design, e-commerce, slides | Photoshop, Figma, browsers |
| NumPy .npz | Yes | Stacked array | Python pipelines, caching | NumPy only |
| COCO RLE | Yes | Per annotation | Datasets, storage, APIs | pycocotools, Detectron2, MMDet, SAM trainer |
| COCO polygons | No (approx.) | Per annotation | Labelling tools, review | CVAT, Label Studio, Roboflow |
| YOLO-seg .txt | No (approx.) | One line each | Training YOLO models | Ultralytics, YOLO tooling |
| Indexed PNG (video) | Yes | IDs as pixel values | Video datasets, VOS | DAVIS-style tools, PIL |
| JPEG | No | — | Never for masks | — |
- Storage and transfer: RLE is typically hundreds of times smaller than a raw array and still exact.
- Humans in the loop: PNG and cut-outs open everywhere.
- Training data: COCO (RLE or polygons) for SAM and most frameworks; YOLO-seg for YOLO.
- Pipelines in Python: keep arrays in .npz until the final export.
COCO RLE
COCO RLE, Explained
Run-length encoding stores how many pixels in a row are off, then on, then off, and so on.
- Structure:
{"size": [height, width], "counts": "…"}. - Order: column-major (down each column), starting with a count of zeros.
- Compressed: pycocotools turns counts into a compact string; decode it back to bytes before saving JSON, as in the script.
- Fortran order: pass
np.asfortranarray(mask)toencode. - Hosted: fal has a dedicated
image-rleendpoint, and Roboflow can return"format": "rle".
Polygons
Polygons: Masks as Points
A polygon traces the outline of a mask as x, y vertices. Lighter and editable, but approximate.
- COCO polygons:
segmentation: [[x1, y1, x2, y2, …], …]in pixels; one list per part. - Holes:
RETR_EXTERNALdrops holes (a donut becomes a disc); use RLE if holes matter. - Detail vs size: simplify with
cv2.approxPolyDPfor fewer points. - Hosted: Roboflow’s SAM 3 endpoint returns polygons with
"format": "polygon".
YOLO-seg
YOLO Segmentation Labels
One text file per image, same name as the image, one line per object.
Line format
class x1 y1 x2 y2 … xn yn- Coordinates normalized 0–1: x ÷ width, y ÷ height.
- Class is a zero-based index into your
data.yamlnames. - The script keeps the largest contour per object.
Typical use
- Auto-label a dataset with SAM 3 text prompts.
- Review a sample, fix errors.
- Train a small, fast YOLO-seg model for edge deployment.
- Mind licences: Ultralytics is AGPL-3.0 unless you hold an Enterprise licence.
Related: alternatives such as YOLOE-26 · use cases
Video
Video Mask Formats
Video adds time and identity. Store masks per frame and keep object IDs consistent.
- Indexed PNG: one file per frame, pixel value = object ID. Compact and lossless.
- RLE per frame: one JSON line per frame with
{obj_id: rle}for analytics. - Overlay MP4 + CSV: for review and reporting; see the video tutorial.
- Limit: overlapping objects need separate masks (one pixel can hold one ID).
save_indexed.py
from PIL import Image
import numpy as np
PALETTE = [0, 0, 0] + [c for i in range(1, 256) for c in ((i * 97) % 256, (i * 57) % 256, (i * 193) % 256)]
def save_indexed(frame_idx, obj_ids, masks, h, w):
idx = np.zeros((h, w), np.uint8) # 0 = background
for oid, m in zip(obj_ids, masks):
idx[np.squeeze(m).astype(bool)] = int(oid) + 1 # IDs 1–255
im = Image.fromarray(idx, mode="P")
im.putpalette(PALETTE)
im.save(f"masks/{frame_idx:05d}.png")
# call inside the propagate_in_video loop from the video tutorialAPIs and libraries
What Hosted APIs and Libraries Return
If you don’t use the official sam3 package, your starting format differs. Convert to your target with the same steps.
| Source | Masks come as | Boxes | Notes |
|---|---|---|---|
| sam3 (official) | Boolean tensors out["masks"] | out["boxes"] | Scores in out["scores"]; export as above |
| Transformers | results["masks"] after post_process_instance_segmentation | results["boxes"] | Thresholds set in post-processing |
| Ultralytics | results[0].masks.data; polygons in masks.xy / masks.xyn | results[0].boxes | masks.xyn is already YOLO-style normalized |
fal sam-3/image | Mask image URLs (PNG, JPEG or WebP) | Normalized [cx, cy, w, h] if requested | Choose PNG; up to 32 masks |
fal sam-3/image-rle | Run-length encoded masks | — | Compact for pipelines |
Roboflow concept_segment | Polygons or RLE (format) | Per prediction | Several prompts per call |
| Replicate models | Varies: overlay images, ZIPs of PNGs, some raw .npy | Varies | Read each model’s API tab |
Request formats and keys: SAM API guide
Read back
Read Formats Back and Check Them
Round-trip a mask to make sure nothing was lost. RLE should match exactly; polygons will be close but not perfect.
check_roundtrip.py
import json, cv2, numpy as np
from pycocotools import mask as mask_utils
# RLE → mask
ann = json.load(open("coco_rle.json"))["annotations"][0]
m_rle = mask_utils.decode(ann["segmentation"]).astype(bool)
# polygons → mask
img = json.load(open("coco_polygons.json"))["images"][0]
poly = json.load(open("coco_polygons.json"))["annotations"][0]["segmentation"]
m_poly = np.zeros((img["height"], img["width"]), np.uint8)
for p in poly:
cv2.fillPoly(m_poly, [np.array(p, np.int32).reshape(-1, 2)], 1)
iou = (m_rle & m_poly.astype(bool)).sum() / (m_rle | m_poly.astype(bool)).sum()
print(f"RLE vs polygon IoU: {iou:.3f}") # can be < 1.0: polygons are approximatePitfalls
Common Export Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Grey, fuzzy mask edges | Saved as JPEG | Use PNG |
| Mask looks transposed or scrambled | RLE decoded row-major | Use pycocotools; pass Fortran-ordered arrays |
| JSON dump fails on RLE | counts is bytes | .decode("ascii") before saving |
| Boxes in the wrong place | Mixed box formats (xyxy, xywh, normalized cx,cy,w,h) | Derive boxes from masks, or convert explicitly |
| Mask size ≠ image size | Low-res masks or resized input | Resize with nearest-neighbour to the original size |
| Holes disappear in polygons | RETR_EXTERNAL | Keep RLE, or use RETR_CCOMP with hole handling |
Mask quality issues: improve mask quality · Export walkthrough: export masks guide
Questions
Mask Formats FAQ
What format does SAM 3 output masks in?
In Python, SAM 3 returns masks as boolean tensors, one per detected object, with boxes and scores. You then export them to the format you need, such as PNG, COCO RLE, polygons or YOLO-seg.
What is the best format to store SAM masks?
COCO RLE for datasets and storage: it is lossless, compact and widely supported. Use PNG for editing and design tools, and polygons for labelling tools and YOLO training.
Can I save SAM masks as JPEG?
Avoid it. JPEG compression adds grey edge artefacts to a black-and-white mask. Use PNG or WebP lossless instead.
How do I convert a SAM mask to polygons?
Use OpenCV’s findContours on the binary mask, then flatten each contour to x, y pairs. Polygons are approximate, so small holes or thin parts can be lost.
How do I convert SAM masks to YOLO segmentation labels?
Take the largest contour of each mask, divide x by image width and y by image height, and write one line per object: class index followed by the normalized x, y pairs.
Why do RLE masks look scrambled when I decode them myself?
COCO RLE counts runs in column-major order (down columns, not across rows). Use pycocotools’ encode and decode instead of hand-rolled code.
How should I store video masks?
Per-frame RLE in a JSON Lines file for analysis, or one indexed PNG per frame where each pixel value is an object ID, as in DAVIS-style datasets.