Meta SAM 3 Playground

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.

one mask, many formats
Animation of one mask exported in three formatsA small pixel mask on the left. On the right, the same mask cycles through three representations: a PNG of white and black pixels, a run-length encoding listing counts of zeros and ones, and a polygon of x, y points around the shape. SAM 3 mask (bool) PNG · pixelsedit in any image tool COCO RLE · counts{"size": [5, 8], "counts": "…"}runs: 6×0, 3×1, 2×0, …compact, lossless, datasets Polygon · x,y points[330,100, 380,100, …]labelling tools, YOLO
Illustration: the same mask as pixels, run lengths and a polygon.

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.

The 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.txt

Compare

Which Format Should You Use?

FormatLossless?Multiple objectsBest forRead by
Binary PNGYesOne file eachViewing, editing, compositingAny image tool, PIL, OpenCV
Cut-out PNG (RGBA)YesMergedDesign, e-commerce, slidesPhotoshop, Figma, browsers
NumPy .npzYesStacked arrayPython pipelines, cachingNumPy only
COCO RLEYesPer annotationDatasets, storage, APIspycocotools, Detectron2, MMDet, SAM trainer
COCO polygonsNo (approx.)Per annotationLabelling tools, reviewCVAT, Label Studio, Roboflow
YOLO-seg .txtNo (approx.)One line eachTraining YOLO modelsUltralytics, YOLO tooling
Indexed PNG (video)YesIDs as pixel valuesVideo datasets, VOSDAVIS-style tools, PIL
JPEGNo—Never for masks—
size per format
Animated chart of file size per mask formatApproximate size of one simple object mask on a 1920 by 1080 image, on a log scale: a raw boolean array is 2,025 kilobytes, PNG about 20, compressed NumPy about 15, COCO RLE about 2 to 4, and a polygon about 1 kilobyte. raw bool array2,025 KBPNG (1-bit-ish)~20 KBNumPy .npz~15 KBCOCO RLE~2–4 KBPolygon~1 KB one simple mask, 1920×1080, log scale · raw is exact, others approximate
Approximate file sizes for one mask.
  • 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.

run-length encoding
Animation of run-length encodingA strip of 16 mask pixels is scanned left to right. Each run of identical values is grouped and counted, producing the counts 3, 5, 2, 3, 3. A note explains that COCO RLE scans down columns, not across rows, and always starts with a count of zeros. 0001111100111000 35233 counts = [3, 5, 2, 3, 3] COCO RLE: column-major order, first count is zeros,then compressed to a string. Use pycocotools.
Illustration of run-length encoding.
  • 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) to encode.
  • Hosted: fal has a dedicated image-rle endpoint, 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.

mask → polygon
Animation of tracing a mask into a polygonA smooth white mask shape. An orange contour line traces around its edge, then a handful of vertex points appear, turning the outline into a polygon. A note says polygons are approximate and fewer points means smaller but rougher shapes. cv2.findContours→ 9 points CHAIN_APPROX_SIMPLEfewer points,smaller files,rougher edges
Illustration of contour tracing.
  • COCO polygons: segmentation: [[x1, y1, x2, y2, …], …] in pixels; one list per part.
  • Holes: RETR_EXTERNAL drops holes (a donut becomes a disc); use RLE if holes matter.
  • Detail vs size: simplify with cv2.approxPolyDP for 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.yaml names.
  • 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 frames
Animation of indexed PNG frames for video masksFour frames of a video stored as indexed PNGs. In each, pixel value 0 is background and values 1, 2 and 3 are object IDs, shown as colours. Object 3 appears from the third frame. Frame files are numbered 00000.png onward. 1200000.png1200001.png12300002.png12300003.png one file per frame · pixel value = object ID (0 = background)compact, lossless, DAVIS-style; palette makes IDs visible
Illustration of indexed PNG frames.
  • 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 tutorial

APIs 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.

SourceMasks come asBoxesNotes
sam3 (official)Boolean tensors out["masks"]out["boxes"]Scores in out["scores"]; export as above
Transformersresults["masks"] after post_process_instance_segmentationresults["boxes"]Thresholds set in post-processing
Ultralyticsresults[0].masks.data; polygons in masks.xy / masks.xynresults[0].boxesmasks.xyn is already YOLO-style normalized
fal sam-3/imageMask image URLs (PNG, JPEG or WebP)Normalized [cx, cy, w, h] if requestedChoose PNG; up to 32 masks
fal sam-3/image-rleRun-length encoded masks—Compact for pipelines
Roboflow concept_segmentPolygons or RLE (format)Per predictionSeveral prompts per call
Replicate modelsVaries: overlay images, ZIPs of PNGs, some raw .npyVariesRead 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 approximate

Pitfalls

Common Export Mistakes

SymptomCauseFix
Grey, fuzzy mask edgesSaved as JPEGUse PNG
Mask looks transposed or scrambledRLE decoded row-majorUse pycocotools; pass Fortran-ordered arrays
JSON dump fails on RLEcounts is bytes.decode("ascii") before saving
Boxes in the wrong placeMixed box formats (xyxy, xywh, normalized cx,cy,w,h)Derive boxes from masks, or convert explicitly
Mask size ≠ image sizeLow-res masks or resized inputResize with nearest-neighbour to the original size
Holes disappear in polygonsRETR_EXTERNALKeep 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.

Keep reading