Meta SAM 3 Playground

Guide · SAM 3 / 3.1 · cut-outs

How to Remove Backgrounds with Meta SAM Tell SAM 3 what to keep, by typing a word or clicking, and turn it into a clean transparent cut-out. Covers single images, product batches, new backgrounds and video, with or without code.

mask → cut-out → new background
Animation of removing and replacing a backgroundA sneaker photographed on a cluttered table. The prompt “sneaker” masks the shoe, the background turns into a transparent checkerboard, then a clean gradient studio background is placed behind the cut-out. keep › “sneaker” 1 · mask2 · transparent PNG3 · new background
Illustration: keep the sneaker, drop the clutter.

How it works

How SAM Background Removal Works

SAM 3 doesn’t erase backgrounds itself; it gives you a precise mask of what to keep. The mask becomes the transparency.

pipeline
Animated background removal pipelineFive steps light up in order: the text prompt, SAM 3 masks for every match, merging them or keeping the best, cleaning the edge, and applying the mask as alpha to export a transparent PNG. prompt“sneaker”masksevery matchmergeunion / bestclean edgeshrink + softenalphaRGBA PNG the same pipeline works for one image, a folder, or every video frame
Illustration of the cut-out pipeline.
  1. 1Choose what to keepType a short noun such as “sneaker” or “person”, or click the subject.
  2. 2Get the maskSAM 3 returns a mask for every match; merge them or keep the best one.
  3. 3Clean the edgeShrink by a pixel and soften slightly to remove halos.
  4. 4Apply as alphaUse the mask as the transparency channel of the image.
  5. 5ExportSave as PNG or WebP with transparency, or place on a new background.

Why SAM instead of a one-click remover? You choose the subject (“sneaker”, not the box), get every product in a group shot, and the same method works on video.

No code

Remove a Background Without Coding

For a few images, a browser is enough.

  1. 1Open the playgroundSee Meta SAM playground for where to try SAM 3 online.
  2. 2Upload your photoGood light and a clear subject give the cleanest edges.
  3. 3Select the subjectType a short noun (“person”, “sneaker”) or click it; add negative clicks to drop extras.
  4. 4Check the edgeZoom in on hair, straps and thin parts; add clicks where it’s wrong.
  5. 5ExportSave the cut-out or mask, then finish in your editor if needed.

Prompt tips: SAM 3 prompt examples · Pick one object: select specific objects

ComfyUI

Background Removal in ComfyUI

ComfyUI’s native SAM 3.1 image template already outputs a cut-out.

  1. 1Set upUpdate ComfyUI and add sam3.1_multiplex_fp16.safetensors to models/checkpoints/.
  2. 2TemplateWorkflow → Browse Templates → Utility → “SAM3: Image Segmentation”.
  3. 3PromptType what to keep, e.g. person or sneaker.
  4. 4RunThe preview is an RGBA image: subject kept, background transparent.
  5. 5Save or reuseSave the image, or feed the mask into compositing and inpainting nodes.

Full setup and the community ComfyUI-SAM3 pack: ComfyUI setup guide

Python

Background Removal Script

One file, three outputs: a transparent PNG, a tightly cropped PNG, and a JPEG on white. Requires SAM 3 installed locally.

remove_bg.py

import sys
import numpy as np
from PIL import Image, ImageFilter
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor

# usage: python remove_bg.py photo.jpg "sneaker" [--best]
path, prompt = sys.argv[1], sys.argv[2]
best_only = "--best" in sys.argv

processor = Sam3Processor(build_sam3_image_model())

def cutout(image, prompt, best_only=False, shrink=1, soften=1.2):
    out = processor.set_text_prompt(state=processor.set_image(image), prompt=prompt)
    masks = [m.squeeze().cpu().numpy().astype(bool) for m in out["masks"]]
    if not masks:
        return None
    if best_only:
        masks = [masks[int(np.argmax([float(s) for s in out["scores"]]))]]
    alpha = Image.fromarray(np.any(masks, axis=0).astype(np.uint8) * 255)
    if shrink:                                   # remove the 1-px halo of old background
        alpha = alpha.filter(ImageFilter.MinFilter(2 * shrink + 1))
    if soften:                                   # gentle anti-aliasing
        alpha = alpha.filter(ImageFilter.GaussianBlur(soften))
    rgba = image.convert("RGBA")
    rgba.putalpha(alpha)
    return rgba

image = Image.open(path).convert("RGB")
result = cutout(image, prompt, best_only)
if result is None:
    sys.exit(f"No “{prompt}” found. Try a simpler noun.")
result.save("cutout.png")                                   # transparent
result.crop(result.getbbox()).save("cutout_trimmed.png")    # tight crop
white = Image.new("RGB", result.size, "white")
white.paste(result, mask=result.getchannel("A"))
white.save("on_white.jpg", quality=95)                     # shop-ready JPEG
print("saved cutout.png, cutout_trimmed.png, on_white.jpg")

example run

$ python remove_bg.py sneaker.jpg "sneaker" --best
saved cutout.png, cutout_trimmed.png, on_white.jpg
  • --best: keep only the highest-scoring match (one product). Without it, every match is kept (group shots).
  • shrink / soften: 1 px and 1.2 px work for most product photos; set both to 0 for pixel-exact masks.
  • Not installed yet? Install SAM 3 · Python tutorial

Clean edges

Get Clean Edges

SAM masks are binary, so edges can show a thin halo of the old background. Two fixes cover almost everything.

edge treatments
Animated comparison of edge treatmentsThree zoomed cut-out edges appear in turn. A hard binary edge shows a thin green halo of old background. A shrunk and softened edge blends cleanly. A trimap marks an uncertain grey band around the edge for a matting model, used for hair and fur. hard mask · haloshrink + softentrimap → matting edge zoomillustrative · hair and fur need the trimap route
Illustration of edge clean-up options.
  • Shrink 1 px, soften ~1 px: built into the script; removes halos on products, furniture and cars.
  • Hair, fur, smoke, glass: build a trimap from the mask and let an image-matting model compute soft alpha.
  • Wrong parts included? Add a negative click, or tighten the prompt.
  • More: improve mask quality

trimap for matting

import cv2, numpy as np

def trimap(mask, band=12):
    # 255 = sure subject, 0 = sure background, 128 = let a matting model decide
    m = mask.astype(np.uint8)
    k = np.ones((band, band), np.uint8)
    t = np.full(m.shape, 128, np.uint8)
    t[cv2.erode(m, k) > 0] = 255
    t[cv2.dilate(m, k) == 0] = 0
    return t
# feed image + trimap to an image-matting model (e.g. ViTMatte) for fine hair and fur

Batch

Batch Product Photos

Load the model once, then loop over a folder. Ideal for e-commerce catalogues.

batch cut-outs
Animation of batch product cut-outsSix product photos on busy backgrounds turn, one after another, into clean cut-outs on white with a soft shadow, ready for an online shop.
Illustration of a product batch.
  • One prompt per catalogue: “sneaker”, “handbag”, “bottle”; or the generic “product” if it works on your images.
  • Check skips: files with no match are listed; fix them by hand or with clicks.
  • Big jobs: a GPU server or hosted API.

batch

# append to remove_bg.py: process a whole folder with the model loaded once
from pathlib import Path
src, dst = Path("products"), Path("cutouts")
dst.mkdir(exist_ok=True)
for p in sorted(src.glob("*.jpg")):
    r = cutout(Image.open(p).convert("RGB"), prompt, best_only=True)
    if r is None:
        print("skip", p.name); continue
    r.crop(r.getbbox()).save(dst / (p.stem + ".png"))
    print("ok  ", p.name)

New background

Replace the Background

Add this after the cut-out to place the subject on a studio shot, a colour or a scene.

replace background

# place the cut-out on any background, centred and scaled to 80 % of its height
bg = Image.open("studio.jpg").convert("RGB")
fg = result.crop(result.getbbox())
scale = 0.8 * bg.height / fg.height
fg = fg.resize((int(fg.width * scale), int(fg.height * scale)), Image.LANCZOS)
bg.paste(fg, ((bg.width - fg.width) // 2, (bg.height - fg.height) // 2), fg)
bg.save("composite.jpg", quality=95)

For realism, match lighting and add a soft shadow (a blurred dark ellipse under the subject). Generative tools can also use the SAM mask to repaint only the background.

Video

Remove a Video Background

Track the subject through the clip, save transparent frames, encode with alpha.

video cut-out
Animation of video background removalA strip of video frames of a dancer. Frame by frame, the background becomes transparent while the dancer stays, then the frames are combined into a WebM file with an alpha channel. dancer.webm (VP9 + alpha)
Illustration of video background removal.

Tracking script to plug this into: video segmentation with Python. For many subjects, use SAM 3.1.

video

# 1. in the video tutorial's loop, save RGBA frames instead of overlays
rgba = np.dstack([frame[..., ::-1], (np.any(masks, axis=0) * 255).astype(np.uint8)])
Image.fromarray(rgba).save(f"frames/{idx:05d}.png")

# 2. encode with transparency
ffmpeg -framerate 30 -i frames/%05d.png -c:v libvpx-vp9 -pix_fmt yuva420p dancer.webm
# or ProRes 4444 for editing apps:
ffmpeg -framerate 30 -i frames/%05d.png -c:v prores_ks -profile:v 4 -pix_fmt yuva444p10le dancer.mov

Hosted APIs

Use an API (No GPU)

  • fal SAM 3 image: send image_url and prompt; returns mask images (PNG, JPEG or WebP; choose PNG) and an optional preview overlay. Apply the mask as alpha yourself.
  • Roboflow concept_segment: returns polygons or RLE for your text prompt; rasterise to a mask, then apply.
  • Costs: per request; check current pricing. Pricing guide
  • Request examples: SAM API guide · Converting outputs: mask formats

Troubleshooting

Common Problems and Fixes

ProblemCauseFix
Thin coloured haloBinary mask edgeShrink 1–2 px, soften ~1 px
Hair looks choppedFine strands aren’t in a binary maskTrimap + matting model
Shadow or reflection keptIncluded in the subject maskNegative click on it; or prompt the object only
Two subjects, wanted oneText matches both--best, a click, or a more specific prompt
Background still visibleSaved as JPEGSave PNG or WebP
Nothing foundPrompt doesn’t matchSimpler noun. Empty masks
Video edges flickerMask changes per frameFix drift with clicks; soften slightly; consider temporal smoothing

Questions

Background Removal FAQ

Can Meta SAM remove backgrounds?

Yes. SAM 3 creates a mask of the subject you choose by text or click; using that mask as the alpha channel gives a transparent cut-out. You can then save it as a PNG or place it on a new background.

Is SAM 3 better than a one-click background remover?

It depends. One-click removers guess the main subject automatically. SAM 3 lets you choose exactly what to keep, such as “the sneaker” but not the box, or every product on a shelf, and works on video.

Why are there halos or jagged edges?

SAM masks are binary. Shrink the mask by a pixel and soften it slightly, as in the script on this page. For hair and fur, use the mask to build a trimap for a dedicated matting model.

Can I remove the background from a video?

Yes. Track the subject with SAM 3’s video predictor, save each frame as a transparent PNG, then encode with ffmpeg to a format that keeps transparency, such as WebM VP9 with alpha.

Which file format keeps transparency?

PNG and WebP keep transparency for images. JPEG does not, so use it only when you place the subject on a solid or new background.

Can I remove backgrounds without coding?

Yes. Use the playground for single images, or ComfyUI’s native “SAM3: Image Segmentation” template, which outputs an RGBA cut-out.

Can I use SAM 3 cut-outs commercially?

SAM 3 is released under the SAM License, which allows commercial use with some restrictions. Check the licence and your image rights. This is not legal advice.

Keep reading