Meta SAM 3 Playground

Guide · SAM 3 / 3.1 · mask quality

How to Improve Meta SAM Mask Edges Blocky outlines, halos, pinholes and lost hair each have a different cause. Diagnose the edge first, then apply the matching fix: better prompts, the threshold, zoom-and-rerun, clean-up, edge snapping or matting.

edge, zoomed in
Animation of a SAM mask edge being improvedA zoomed-in head-and-shoulders mask shows a stepped, blocky outline. Next the outline becomes smooth after zoom-and-rerun and clean-up. Finally fine hair strands appear with soft transparency after matting. raw: low-res mask enlarged → stepped edge zoom + rerun + clean: smooth outline matting: soft alpha for hair same object, zoomed to the edge
Illustration: raw, refined and matted edges.

Start here

What’s Wrong With Your Edge?

Zoom to 100% and view the mask over a dark and a light background. Match what you see to a fix.

edge problems
Animation of four common edge problemsFour zoomed tiles appear in turn: a stepped edge, a halo of background around the object, holes and stray specks, and missing fine detail such as hair strands that the mask leaves out. stepped edgehaloholes & specksmissing detail check at 100% zoom, on both a dark and a light background
Illustration of four common edge problems.
You seeGo to
Whole parts missing or extra1 · Prompts
Edge slightly too loose or tight; halo2 · Threshold
Stepped, blobby outline on big photos or small objects3 · Zoom & rerun
Pinholes, stray specks, ragged outline4 · Clean up
Edge doesn’t follow the object’s real outline5 · Snap to edges
Hair, fur, glass, smoke6 · Matting

Background

Why SAM Mask Edges Go Soft

SAM 3 predicts each mask on a small fixed grid, then enlarges it to your image.

mask resolution
Animation of a small mask enlarged to a large photoA small grid mask of 12 by 12 cells is enlarged to fill a big photo. Each mask cell becomes a large block, so the round object gets a stepped outline. A smaller crop around the object gives the same grid more detail. mask grid enlarged to a 12 MP photo more image pixels per mask cell = softer, blockier edge
Illustration of a small mask enlarged to a large photo.
  • Fixed mask grid: the Transformers SAM 3 image processor sets the mask size to 288 × 288. Every mask is then resized to your photo’s size.
  • Big photo, small object: the object covers few mask cells, so its edge is coarse once enlarged.
  • On/off pixels: after thresholding, each pixel is in or out, so hair and glass can’t be partly transparent.
  • The fix follows: give the object more mask cells (zoom), keep soft values longer (threshold), or add a model built for fine edges (matting).

Method 1

Fix the Prompt First

If whole parts are wrong, no filter will fix it. Correct the selection, then refine the edge.

Method 1
  • Missing part (an arm, a wheel, a handle): add a positive click on it.
  • Extra part (a held bag, the chair behind): add a negative click on it.
  • Text prompt too broad: tighten the words or add a negative box. Prompt examples
  • Clicks don’t sharpen an edge that’s already in the right place; use methods 3–5 for that.
  • Click-by-click workflow: select specific objects

Method 2

Keep the Soft Mask and Set the Threshold

SAM produces a soft mask (0 to 1) before it becomes on/off. Where you cut it decides the edge.

threshold
Animation of the mask threshold moving the edgeA soft mask fades from certain in the centre to uncertain at the rim. A threshold line moves outward at 0.3, sits at 0.5, and moves inward at 0.7, growing or shrinking the final mask. mask_threshold 0.5default mask_threshold 0.3grows: keeps thin parts mask_threshold 0.7shrinks: drops halo keep the soft mask,choose the edge later
Illustration of the threshold moving the edge.
Method 2
  • mask_threshold=0.5 is the default in Transformers’ post-processing.
  • Lower (0.3–0.4): keeps thin parts like straps and stems; can add a halo.
  • Higher (0.6–0.7): removes halos; can thin the object.
  • Keep the soft mask for later steps: filtering and matting work better on soft values.
  • Code: the soft-mask snippet below.

Method 3

Zoom In and Rerun SAM 3

The single most effective fix for blocky edges: crop around the object and segment the crop.

zoom and rerun
Animation of zoom and rerunA small bird in a large photo gets a blocky mask. A box with margin is traced around it and the crop is enlarged. SAM 3 runs again on the crop, giving a smooth mask that is pasted back into the full image. 1 · crop object + margin 2 · rerun SAM 3 on the crop 3 · paste the sharper mask back at the crop position
Illustration of crop, rerun and paste back.
Method 3
  • Why it works: the object now fills the mask grid instead of a corner of it.
  • Margin: 20–30% around the box keeps context so SAM still recognises the object.
  • Same prompt: reuse the text, or move clicks into crop coordinates.
  • Very large objects: split into overlapping tiles along the edge.
  • Cost: one extra forward pass per object.

Method 4

Remove Specks, Fill Holes, Smooth

Simple image operations fix most ragged masks in milliseconds.

clean-up
Animation of hole and speck clean-upA car mask has holes in the windows and stray specks around it. After clean-up the specks are removed, the small holes are filled and the outline is smoothed. raw: 2 holes, 3 specks clean: keep main part · fill small holes · smooth large holes (real windows) are kept
Illustration of speck removal and hole filling.
Method 4
  • Keep the main part: drop pieces smaller than about 2% of the object.
  • Fill pinholes: only holes smaller than about 1%; real gaps (windows, the space between arms) stay open.
  • Smooth lightly: an open then close with a 2–3 px radius rounds jagged steps.
  • Don’t over-smooth: large radii round off corners and fingers.

Method 5

Snap the Edge to the Photo

A guided filter reshapes the soft mask so its edge follows real colour boundaries in the image.

Method 5
  • Best for: clear outlines against contrasting backgrounds: products, furniture, cars.
  • Settings: radius 4–16 px (larger for larger photos); eps 1e-4 (sharper) to 1e-2 (softer).
  • No extra packages: the guided() function below uses plain OpenCV.
  • Not for hair: it follows edges, but can’t create strands the mask never had. Use matting.

Method 6

Hair, Fur and Glass: Use Matting

Turn the SAM mask into a trimap and let a matting model compute soft alpha in the uncertain band.

matting
Animation of mask to trimap to alpha matteA hard SAM mask of a head becomes a trimap with a white sure-foreground core, a black sure-background area and a grey unknown band around the edge. A matting model fills the band with soft alpha, recovering hair strands. SAM mask trimap alpha matte white = sure object · grey = model decides · black = sure background
Illustration of mask, trimap and alpha matte.
Method 6
  • Trimap: white where the object is certain, black where it’s certainly background, grey in between.
  • Model: ViTMatte in Transformers takes the image and the trimap together.
  • Band width: about 20 px outward is a good start; widen to 32+ for loose hair.
  • Memory: matting large photos uses a lot of GPU memory; downscale the long edge to about 2048 px, matte, then upscale the alpha.
  • Limits: smoke and heavy motion blur stay hard for any model.

Video

Steadier Edges in Video

Edges flicker because each frame is thresholded on its own. Average the soft masks over neighbouring frames first.

steady_video_edges.py

import numpy as np

def steady(soft_frames, radius=1, t=0.5):
    """soft_frames: list of soft masks (0..1) for one object, in frame order."""
    out = []
    for i in range(len(soft_frames)):
        lo, hi = max(i - radius, 0), min(i + radius + 1, len(soft_frames))
        out.append(np.mean(soft_frames[lo:hi], axis=0) > t)
    return out

Code

Full Edge-Refinement Pipeline

Soft masks, zoom-and-rerun, clean-up and edge snapping, then optional matting.

1 · soft masks (Transformers)

# Transformers: keep SAM 3's soft masks instead of 0/1 masks
import torch
import torch.nn.functional as F
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("portrait.jpg").convert("RGB")
inputs = processor(images=image, text="person", return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)

# the 0/1 masks, with your own threshold
r = processor.post_process_instance_segmentation(
    outputs, threshold=0.5, mask_threshold=0.5,  # try 0.4 to grow, 0.6 to tighten
    target_sizes=inputs.get("original_sizes").tolist())[0]

# soft masks (0..1) at full size, mirroring what post-processing does internally
h, w = inputs["original_sizes"][0].tolist()
scores = outputs.pred_logits.sigmoid()[0]
if outputs.presence_logits is not None:
    scores = scores * outputs.presence_logits.sigmoid()[0]
keep = scores > 0.5
probs = outputs.pred_masks[0, keep].sigmoid()[None].float()
soft = F.interpolate(probs, size=(h, w), mode="bilinear", align_corners=False)[0].cpu().numpy()

2 · refine_edges.py

import cv2
import numpy as np

def clean(mask, min_part=0.02, max_hole=0.01, smooth=2):
    """Remove specks, fill small holes, smooth the outline. Sizes are fractions of the object."""
    m = mask.astype(np.uint8)
    area = max(int(m.sum()), 1)
    n, lab, st, _ = cv2.connectedComponentsWithStats(m, connectivity=8)
    if n > 1:
        biggest = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA]))
        keep = [i for i in range(1, n) if i == biggest or st[i, cv2.CC_STAT_AREA] >= min_part * area]
        m = np.isin(lab, keep).astype(np.uint8)
    n, lab, st, _ = cv2.connectedComponentsWithStats(1 - m, connectivity=4)
    for i in range(1, n):  # background pieces not touching the border are holes
        x, y, bw, bh, a = st[i]
        inside = x > 0 and y > 0 and x + bw < m.shape[1] and y + bh < m.shape[0]
        if inside and a <= max_hole * area:
            m[lab == i] = 1
    if smooth:
        k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * smooth + 1, 2 * smooth + 1))
        m = cv2.morphologyEx(cv2.morphologyEx(m, cv2.MORPH_OPEN, k), cv2.MORPH_CLOSE, k)
    return m.astype(bool)

def guided(image, soft, r=8, eps=1e-3):
    """Edge-aware smoothing: pulls a soft mask onto the photo's real edges (no extra packages)."""
    I = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2GRAY).astype(np.float32) / 255
    p = soft.astype(np.float32)
    box = lambda x: cv2.boxFilter(x, -1, (2 * r + 1, 2 * r + 1))
    mI, mp = box(I), box(p)
    a = (box(I * p) - mI * mp) / (box(I * I) - mI * mI + eps)
    b = mp - a * mI
    return np.clip(box(a) * I + box(b), 0, 1)

def zoom_refine(image, mask, segment, margin=0.25):
    """Crop around the object, run SAM 3 again on the crop, paste the soft result back.
    segment(crop_image) must return a soft mask (0..1) the size of the crop."""
    ys, xs = np.nonzero(mask)
    H, W = mask.shape
    x0, x1, y0, y1 = xs.min(), xs.max() + 1, ys.min(), ys.max() + 1
    mx, my = int((x1 - x0) * margin), int((y1 - y0) * margin)
    x0, y0, x1, y1 = max(x0 - mx, 0), max(y0 - my, 0), min(x1 + mx, W), min(y1 + my, H)
    crop = image.crop((x0, y0, x1, y1))
    soft = mask.astype(np.float32)
    soft[y0:y1, x0:x1] = segment(crop)
    return soft

3 · put it together

from PIL import Image

image = Image.open("portrait.jpg").convert("RGB")
mask = soft[0] > 0.5                                     # from the soft-mask snippet

def segment(crop):                                       # SAM 3 on the crop, best match only
    inp = processor(images=crop, text="person", return_tensors="pt").to(model.device)
    with torch.no_grad():
        out = model(**inp)
    s = out.pred_logits.sigmoid()[0]
    p = out.pred_masks[0, s.argmax()].sigmoid()[None, None].float()
    return F.interpolate(p, size=crop.size[::-1], mode="bilinear", align_corners=False)[0, 0].cpu().numpy()

soft_z = zoom_refine(image, mask, segment)               # 1) more mask detail
mask_c = clean(soft_z > 0.5)                             # 2) no specks, no pinholes
alpha = guided(image, mask_c.astype("float32"))          # 3) edge follows the photo
Image.fromarray((alpha * 255).astype("uint8"), "L").save("portrait_mask_refined.png")

4 · optional: matting for hair

import cv2
import numpy as np
import torch
from PIL import Image
from transformers import VitMatteImageProcessor, VitMatteForImageMatting

def trimap(mask, inner=10, outer=20):
    m = mask.astype(np.uint8)
    t = np.full(m.shape, 128, np.uint8)  # grey: the matting model decides
    t[cv2.erode(m, np.ones((inner, inner), np.uint8)) > 0] = 255
    t[cv2.dilate(m, np.ones((outer, outer), np.uint8)) == 0] = 0
    return Image.fromarray(t, "L")

mp = VitMatteImageProcessor.from_pretrained("hustvl/vitmatte-small-composition-1k")
mm = VitMatteForImageMatting.from_pretrained("hustvl/vitmatte-small-composition-1k")

tri = trimap(mask_c, inner=10, outer=32)                 # wider outer band for loose hair
inputs = mp(images=image, trimaps=tri, return_tensors="pt")
with torch.no_grad():
    alpha = mm(**inputs).alphas[0, 0]                     # padded to a multiple of 32
w, h = image.size
alpha = alpha[:h, :w].numpy()
cut = image.copy()
cut.putalpha(Image.fromarray((alpha * 255).astype("uint8"), "L"))
cut.save("portrait_matted.png")

Setup: install SAM 3. Save the results: export masks and transparent PNGs.

No code

Better Edges Without Code

In the playground

  • Add a click on any part that’s missing or extra.
  • Upload a cropped photo of the object for a finer mask.
  • Check the cutout on a dark and a light background before downloading.
  • Open the playground

In ComfyUI

  • Grow/shrink and blur mask nodes handle halos and steps.
  • Community ViTMatte nodes (for example TS Matting in ComfyUI Timesaver Nodes) take a SAM 3 mask and matte the edge.
  • ComfyUI setup

Quick fixes

Edge Problems and Fixes

ProblemFix
Thin line of old background around the objectRaise the threshold to 0.6, or shrink the mask 1 px
Thin parts cut off (straps, antennas)Lower the threshold to 0.4, or add a positive click
Stair-step outlineZoom and rerun; then light smoothing
Edge looks right on screen, wrong when printed largeZoom and rerun at full resolution
Rounded corners after clean-upSmaller smoothing radius
Matting leaves grey patches insideNarrow the grey band (smaller inner value)
Out of GPU memory while mattingMatte at ≤2048 px long edge and upscale the alpha
Edges flicker in videoAverage soft masks over 3 frames

Removing a background? Background removal guide · Known model limits: limitations

Questions

Mask Edges FAQ

Why are SAM 3 mask edges blocky on large photos?

SAM 3 predicts each mask on a small fixed grid and then enlarges it to your image size. On a large photo each mask pixel covers many image pixels, so edges look soft or stepped. Zooming in on the object and running SAM again gives it more mask pixels.

What does mask_threshold change?

It sets where the soft mask becomes the edge. Lower values grow the mask outward; higher values tighten it. 0.5 is the default.

How do I get hair and fur right?

Segmentation masks are on/off per pixel, so fine strands can’t be represented. Build a trimap from the SAM mask and run a matting model such as ViTMatte to get soft alpha.

How do I remove small specks and holes?

Keep the largest connected region (plus any big extra parts), fill small holes, then smooth lightly with a morphological open and close.

Will more clicks improve edges?

Yes, when the mask misses or includes whole parts. Click on the problem area: positive to add, negative to remove. Clicks don’t make a correct edge sharper, though; zoom or filtering does.

Why do video mask edges flicker?

Each frame’s edge is decided separately. Averaging the soft masks over a few neighbouring frames before thresholding steadies the edge.

Is SAM 3.1 sharper than SAM 3?

SAM 3.1 mainly speeds up multi-object video tracking; the same edge fixes apply to both.

Keep reading