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.
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.
- 1Choose what to keepType a short noun such as “sneaker” or “person”, or click the subject.
- 2Get the maskSAM 3 returns a mask for every match; merge them or keep the best one.
- 3Clean the edgeShrink by a pixel and soften slightly to remove halos.
- 4Apply as alphaUse the mask as the transparency channel of the image.
- 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.
- 1Open the playgroundSee Meta SAM playground for where to try SAM 3 online.
- 2Upload your photoGood light and a clear subject give the cleanest edges.
- 3Select the subjectType a short noun (“person”, “sneaker”) or click it; add negative clicks to drop extras.
- 4Check the edgeZoom in on hair, straps and thin parts; add clicks where it’s wrong.
- 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.
- 1Set upUpdate ComfyUI and add
sam3.1_multiplex_fp16.safetensorstomodels/checkpoints/. - 2TemplateWorkflow → Browse Templates → Utility → “SAM3: Image Segmentation”.
- 3PromptType what to keep, e.g.
personorsneaker. - 4RunThe preview is an RGBA image: subject kept, background transparent.
- 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.
- 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 furBatch
Batch Product Photos
Load the model once, then loop over a folder. Ideal for e-commerce catalogues.
- 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.
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.movHosted APIs
Use an API (No GPU)
- fal SAM 3 image: send
image_urlandprompt; 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
| Problem | Cause | Fix |
|---|---|---|
| Thin coloured halo | Binary mask edge | Shrink 1–2 px, soften ~1 px |
| Hair looks chopped | Fine strands aren’t in a binary mask | Trimap + matting model |
| Shadow or reflection kept | Included in the subject mask | Negative click on it; or prompt the object only |
| Two subjects, wanted one | Text matches both | --best, a click, or a more specific prompt |
| Background still visible | Saved as JPEG | Save PNG or WebP |
| Nothing found | Prompt doesn’t match | Simpler noun. Empty masks |
| Video edges flicker | Mask changes per frame | Fix 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.