Skip to main content

nobg

Open-source background removal & image matting, with first-class HuggingFace Hub integration.

PyPI PyPI Downloads Python License

Input Output

Table of Contents

Installation

uv add nobg
From source (with uv)
git clone https://github.com/feyninc/nobg.git
cd nobg
uv sync

Requires Python ≥ 3.10 and torch ≥ 2.0. See pyproject.toml for the full dependency set.

Quick Start

Remove a background in ten lines:

import torch
from loadimg import load_img
from nobg import AutoModel, AutoProcessor

model = AutoModel.from_pretrained("feyninc/FeyNobg").eval()
processor = AutoProcessor.from_pretrained("feyninc/FeyNobg")

image = load_img("input.jpg").convert("RGB")
inputs = processor(image, return_tensors="pt")

with torch.no_grad():
    outputs = model(pixel_values=inputs["pixel_values"])

alpha = processor.post_process_alpha_matting(
    outputs, target_sizes=[(image.height, image.width)]
)[0]
processor.cutout(image, alpha).save("output.png")

Or try it in the browser first: 🤗 FeyNobg Space.

Model Zoo

Model Repo Params Resolution Task Notes
FeyNobg feyninc/FeyNobg 0.3 B 1024 × 1024 Background removal / matting Strongest published model, start here

Usage

AutoModel & AutoProcessor

AutoModel reads the repo tags and returns the concrete class. AutoProcessor reads preprocessor_config.json (or falls back to the model config) and returns the matching image processor.

from nobg import AutoModel, AutoProcessor

model = AutoModel.from_pretrained("feyninc/FeyNobg")
processor = AutoProcessor.from_pretrained("feyninc/FeyNobg")

Concrete classes work too, if you'd rather be explicit:

from nobg import BiRefNet, BiRefNetImageProcessor

model = BiRefNet.from_pretrained("feyninc/FeyNobg")
processor = BiRefNetImageProcessor.from_pretrained("feyninc/FeyNobg")

Constructing from scratch (random init) uses the config dataclass:

from nobg import BiRefNet
from nobg.birefnet.modeling_birefnet import BiRefNetConfig

model = BiRefNet(BiRefNetConfig(image_size=512, embed_dim=128))

Batched inference

Pass a list of images; post_process_alpha_matting takes one target size per image, so mattes come back at each original resolution.

images = [load_img(p).convert("RGB") for p in ("a.jpg", "b.jpg", "c.jpg")]
inputs = processor(images, return_tensors="pt")

with torch.no_grad():
    outputs = model(pixel_values=inputs["pixel_values"])

mattes = processor.post_process_alpha_matting(
    outputs, target_sizes=[(im.height, im.width) for im in images]
)
for im, alpha, path in zip(images, mattes, ("a.png", "b.png", "c.png")):
    processor.cutout(im, alpha).save(path)

The same pattern handles video: decode to frames, batch them, composite back.

GPU & half precision

model = AutoModel.from_pretrained("feyninc/FeyNobg").eval().to("cuda")
inputs = processor(image, return_tensors="pt").to("cuda")

with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
    outputs = model(pixel_values=inputs["pixel_values"])

Fine-tuning on custom data

NoBg provides the model, processor, and loss needed to train BiRefNet on your own image and mask pairs. Because the model plugs into the Hugging Face Trainer, you get its full training loop, checkpointing, and evaluation for free.

from transformers import Trainer, TrainingArguments
from nobg import AutoProcessor, AutoModel

model = AutoModel.from_pretrained("nobg/FeyNobg")
processor = AutoProcessor.from_pretrained("nobg/FeyNobg")


def collate(examples):
    batch = processor(
        images=[ex["image"] for ex in examples],
        segmentation_maps=[ex["mask"].convert("L") for ex in examples],
        return_tensors="pt",
    )
    return {"pixel_values": batch["pixel_values"], "labels": batch["labels"]}


trainer = Trainer(
    model=model,
    args=TrainingArguments(output_dir="outputs", learning_rate=2e-5),
    train_dataset=dataset,
    data_collator=collate,
)
trainer.train()
Swapping the loss

model.criterion is a plain function attribute, not a submodule, so it never enters the state dict and you can replace it outright:

from nobg.loss import birefnet_loss, iou_loss, ssim_loss


def my_loss(scaled_preds, gt):
    return birefnet_loss(scaled_preds, gt) + 5 * iou_loss(
        scaled_preds[-1].sigmoid(), gt
    )


model.criterion = my_loss

Re-parameterizing a checkpoint

BiRefNet.from_origin builds a new model from an existing one, injecting every weight whose key and shape still match and freshly initializing the rest. Handy for changing resolution, growing the decoder, or migrating pre-0.2.0 checkpoints.

from nobg import BiRefNet

model = BiRefNet.from_origin("feyninc/FeyNobg", image_size=2048)

origin may be a Hub repo id, a local directory with config.json + model.safetensors, or a live nn.Module.

Push to HuggingFace Hub

model.push_to_hub("your-username/model-name")
processor.push_to_hub("your-username/model-name")

A bare name is auto-prefixed with your Hub username, and a model card is generated from the shared template.

Acknowledgement

  • BiRefNet by Peng Zheng et al., the architecture and training recipe this library builds on.
  • transformers and huggingface_hub for the backbone, processor base and Hub integration.

Citation

@software{nobg,
  title={nobg: Open Source Background Removal Models for Image and Video Matting},
  author={Hichri, Hafedh},
  year={2026},
  url={https://github.com/feyninc/nobg},
  license={Apache-2.0},
}

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nobg-0.2.4.tar.gz (346.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nobg-0.2.4-py3-none-any.whl (26.6 kB view details)

Uploaded Python 3

File details

Details for the file nobg-0.2.4.tar.gz.

File metadata

  • Download URL: nobg-0.2.4.tar.gz
  • Upload date:
  • Size: 346.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for nobg-0.2.4.tar.gz
Algorithm Hash digest
SHA256 1d2c2be6fa99fc478fbc0fe19e61ba1fa9f52ffbf6f11e0108c77a90ddc558f5
MD5 c30b63ff0c272c765042aa77c6e36f21
BLAKE2b-256 c96b7ddc638d00911a509f2e1a4b6528ea855ce26cf7c9e3de33edc3f4e4ed3c

See more details on using hashes here.

File details

Details for the file nobg-0.2.4-py3-none-any.whl.

File metadata

  • Download URL: nobg-0.2.4-py3-none-any.whl
  • Upload date:
  • Size: 26.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for nobg-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 2c34d111ca505549b456bf66cd2fa384bb8383e069e05109cbdae8517ed454a6
MD5 6803618dc5d949398bd75a04a03f03bc
BLAKE2b-256 b2c518ad1798aef02d98597b773e78604ebc7f7ce9298f036cd174b8f83fa7df

See more details on using hashes here.

Release history Release notifications | RSS feed

0.3.1

2 files

0.3.0

2 files

0.2.5

2 files

This release

0.2.4 This release

2 files

0.2.3

2 files

0.2.2

2 files

0.2.1

2 files

0.2.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page