Vanilla JavaScript Projects

Project 07, AI in the browser

Background Remover

Cut the subject out of any photo without uploading it anywhere. Drag the slider to compare, pick a new background, and save a PNG.

Runs on
Your CPU (WebAssembly)
Model
RMBG 1.4 by BRIA AI
First download
About 44 MB
Your browser
Checking

Remove a background

The model downloads on the first photo (about 44 MB) and is cached after that.

Drop a photo here
or click to choose. Paste works too.

Or try a sample:

New background

Waiting for a photo

Your result shows here. Drag the slider to compare with the original.

How it works

  1. Find the subjectThe image is resized to 1024 by 1024 and the model returns a mask: white for the subject, black for the background.
  2. Apply the maskThe mask is scaled back to full size and copied into the alpha channel of the original pixels.
  3. ComposeThe cut-out is drawn over the background you picked, then exported as a PNG.
import { AutoModel, AutoProcessor, RawImage } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";

const model = await AutoModel.from_pretrained("briaai/RMBG-1.4", { config: { model_type: "custom" } });
const processor = await AutoProcessor.from_pretrained("briaai/RMBG-1.4", { config: {
  do_normalize: true, do_resize: true, do_rescale: true, rescale_factor: 1 / 255,
  image_mean: [0.5, 0.5, 0.5], image_std: [1, 1, 1], size: { width: 1024, height: 1024 },
  feature_extractor_type: "ImageFeatureExtractor", resample: 2, do_pad: false } });

const image = await RawImage.fromURL(url);
const { pixel_values } = await processor(image);
const { output } = await model({ input: pixel_values });

// Grayscale mask, same size as the photo: use it as the alpha channel
const mask = await RawImage.fromTensor(output[0].mul(255).to("uint8")).resize(image.width, image.height);