Rembg is a tool to remove images background
feat: add ViTMatte edge refinement behind -vm (#846)
Daniel Gatis26d4602a50f4
diff --git a/README.md b/README.mdindex 4809160..1529a25 100644--- a/README.md+++ b/README.md@@ -355,6 +355,7 @@ treat the *soft* pixels along an edge — hair, fur, fabric, motion blur.| Naive | *(default)* | No | No | Free || Decontaminate | `-dc` | Yes | No | Negligible || Alpha matting | `-a` | Yes | Yes | Slow |+| ViTMatte | `-vm` | Yes | Yes | Slow, extra download |They are alternatives, not layers — `-a` already decontaminates internally, sopassing both changes nothing. Pick one:@@ -370,9 +371,23 @@ and it is cheap enough to leave on for a whole batch.**Use `-a`** when the *shape* of the mask is wrong, not just its color — themodel cut through strands of hair, or left a hard stair-stepped edge where the-subject is genuinely soft. This is the only mode that re-estimates coverage,-and it is much slower than the others. Its solver can also fail to converge on-some images; rembg falls back to a decontaminated cutout when that happens.+subject is genuinely soft. It re-estimates coverage with a closed-form solver,+and it is much slower than `-dc`. That solver can fail to converge on some+images; rembg falls back to a decontaminated cutout when that happens.++**Use `-vm`** for the same problem as `-a`, when you want the fine detail back.+ViTMatte predicts the alpha with a network instead of solving for it, so it+recovers more of the wispy strands `-a` tends to clip, and it cannot fail to+converge. It costs an extra ~110 MB download on first use and runs slower than+`-a`. Pick a different checkpoint with+`-x '{"vitmatte_model": "base-distinctions-646"}'`:++| Checkpoint | Download | Notes |+| --- | --- | --- |+| `small-distinctions-646` | ~110 MB | The default. Best quality per byte. |+| `small-composition-1k` | ~110 MB | Trained on synthetic composites. |+| `base-distinctions-646` | ~380 MB | Slightly more detail, ~2.5x the runtime. |+| `base-composition-1k` | ~380 MB | Larger, synthetic training set. |### Which model to pair it with@@ -386,8 +401,9 @@ edges. They benefit most from `-a` on hair-heavy portraits, and are also whereits solver is most likely to struggle.For portraits specifically, `birefnet-portrait` with `-dc` is a good starting-point. If you are batch-processing and cannot inspect each result, prefer `-dc`-over `-a`: it is faster and cannot fail.+point, and `-vm` when the hair detail matters more than the runtime. If you are+batch-processing and cannot inspect each result, prefer `-dc` over `-a`: it is+faster and cannot fail.> Note: `-ppm` (post-process mask) thresholds the mask into a fully binary one,> which leaves no partially transparent pixels at all. Combining it with `-dc`diff --git a/rembg/bg.py b/rembg/bg.pyindex 339371d..13b166d 100644--- a/rembg/bg.py+++ b/rembg/bg.py@@ -27,6 +27,7 @@ from pymatting.util.util import stack_imagesfrom scipy.ndimage import binary_erosion, gaussian_filterfrom skimage.morphology import disk, opening+from .matting import vitmatte_alphafrom .session_factory import new_sessionfrom .sessions import sessions, sessions_names, sessions_names_downloadablefrom .sessions.base import BaseSession@@ -266,6 +267,8 @@ def remove(only_mask: bool = False,post_process_mask: bool = False,decontaminate: bool = False,+ vitmatte: bool = False,+ vitmatte_model: Optional[str] = None,bgcolor: Optional[Tuple[int, int, int, int]] = None,force_return_bytes: bool = False,*args: Optional[Any],@@ -286,6 +289,8 @@ def remove(only_mask (bool, optional): Flag indicating whether to return only the binary masks. Defaults to False.post_process_mask (bool, optional): Flag indicating whether to post-process the masks. Defaults to False.decontaminate (bool, optional): Flag indicating whether to remove the background color fringing left on soft edges. Ignored when alpha_matting is on. Defaults to False.+ vitmatte (bool, optional): Flag indicating whether to refine the mask with ViTMatte, which recovers more soft edge detail than alpha matting. Takes precedence over alpha_matting. Defaults to False.+ vitmatte_model (Optional[str], optional): Which ViTMatte checkpoint to use: small-distinctions-646 (default), small-composition-1k, base-distinctions-646, or base-composition-1k. Defaults to None.bgcolor (Optional[Tuple[int, int, int, int]], optional): Background color for the cutout image. Defaults to None.force_return_bytes (bool, optional): Flag indicating whether to return the cutout image as bytes. Defaults to False.*args (Optional[Any]): Additional positional arguments.@@ -328,6 +333,24 @@ def remove(if only_mask:cutout = mask+ elif vitmatte:+ # ViTMatte predicts coverage but not colour, so the refined alpha+ # still goes through the same foreground estimation `-dc` uses.+ # Without it the recovered strands keep the old background colour.+ refined = vitmatte_alpha(+ img,+ mask,+ variant=vitmatte_model,+ foreground_threshold=alpha_matting_foreground_threshold,+ background_threshold=alpha_matting_background_threshold,+ erode_size=alpha_matting_erode_size,+ )++ if putalpha:+ cutout = putalpha_cutout(img, refined)+ else:+ cutout = decontaminate_cutout(img, refined)+elif alpha_matting:try:cutout = alpha_matting_cutout(diff --git a/rembg/commands/b_command.py b/rembg/commands/b_command.pyindex e630628..c5a1baf 100644--- a/rembg/commands/b_command.py+++ b/rembg/commands/b_command.py@@ -71,6 +71,13 @@ from ..sessions import sessions_namesshow_default=True,help="post process the mask",)+ "-vm",+ "--vitmatte",+ is_flag=True,+ show_default=True,+ help="refine the edges with ViTMatte, recovering more fine detail than -a",+)@click.option("-bgc","--bgcolor",diff --git a/rembg/commands/i_command.py b/rembg/commands/i_command.pyindex 12077b6..25eef90 100644--- a/rembg/commands/i_command.py+++ b/rembg/commands/i_command.py@@ -75,6 +75,13 @@ from ..sessions import sessions_namesshow_default=True,help="remove the background color fringing left on soft edges",)+ "-vm",+ "--vitmatte",+ is_flag=True,+ show_default=True,+ help="refine the edges with ViTMatte, recovering more fine detail than -a",+)@click.option("-bgc","--bgcolor",diff --git a/rembg/commands/p_command.py b/rembg/commands/p_command.pyindex 6bb85a2..a72b230 100644--- a/rembg/commands/p_command.py+++ b/rembg/commands/p_command.py@@ -144,6 +144,13 @@ def _confirm_usage_cost(show_default=True,help="remove the background color fringing left on soft edges",)+ "-vm",+ "--vitmatte",+ is_flag=True,+ show_default=True,+ help="refine the edges with ViTMatte, recovering more fine detail than -a",+)@click.option("-w","--watch",diff --git a/rembg/commands/s_command.py b/rembg/commands/s_command.pyindex bc7ca52..62f2aca 100644--- a/rembg/commands/s_command.py+++ b/rembg/commands/s_command.py@@ -134,6 +134,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -om: bool = Query(default=False, description="Only Mask"),ppm: bool = Query(default=False, description="Post Process Mask"),dc: bool = Query(default=False, description="Decontaminate Edges"),+ vm: bool = Query(default=False, description="Refine Edges with ViTMatte"),bgc: Optional[str] = Query(default=None, description="Background Color"),extras: Optional[str] = Query(default=None, description="Extra parameters as JSON"@@ -147,6 +148,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -self.om = omself.ppm = ppmself.dc = dc+ self.vm = vmself.extras = extrasself.bgc = (cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))@@ -181,6 +183,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -om: bool = Form(default=False, description="Only Mask"),ppm: bool = Form(default=False, description="Post Process Mask"),dc: bool = Form(default=False, description="Decontaminate Edges"),+ vm: bool = Form(default=False, description="Refine Edges with ViTMatte"),bgc: Optional[str] = Query(default=None, description="Background Color"),extras: Optional[str] = Query(default=None, description="Extra parameters as JSON"@@ -194,6 +197,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -self.om = omself.ppm = ppmself.dc = dc+ self.vm = vmself.extras = extrasself.bgc = (cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))@@ -229,6 +233,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -only_mask=commons.om,post_process_mask=commons.ppm,decontaminate=commons.dc,+ vitmatte=commons.vm,bgcolor=commons.bgc,**kwargs,),@@ -393,7 +398,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -def gr_app(app):def inference(input_image, model, *args):- a, af, ab, ae, om, ppm, dc, cmd_args = args+ a, af, ab, ae, om, ppm, dc, vm, cmd_args = argskwargs = {"alpha_matting": a,@@ -403,6 +408,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -"only_mask": om,"post_process_mask": ppm,"decontaminate": dc,+ "vitmatte": vm,}extras = {}@@ -441,6 +447,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -gr.components.Checkbox(value=False, label="Only mask"),gr.components.Checkbox(value=True, label="Post process mask"),gr.components.Checkbox(value=False, label="Decontaminate edges"),+ gr.components.Checkbox(value=False, label="ViTMatte edge refinement"),gr.components.Textbox(label="Arguments"),],gr.components.Image(type="pil", label="Output"),diff --git a/rembg/matting.py b/rembg/matting.pynew file mode 100644index 0000000..aba7da9--- /dev/null+++ b/rembg/matting.py@@ -0,0 +1,207 @@+"""Learned edge refinement with ViTMatte.++Alpha matting turns a coarse mask into a real alpha channel. The `-a` path does+this with pymatting's closed-form solver, which is fast but can leave the fine+tips of hair behind and occasionally fails to converge. ViTMatte does the same+job with a network: it takes the image plus a trimap and predicts the alpha+directly, so it recovers more of the soft detail and cannot fail to converge.++ViTMatte only predicts coverage, not colour, so the caller still has to unmix+the foreground the way `decontaminate_cutout` does. Otherwise the recovered+strands keep whatever background colour was blended into them.++The model runs at a fixed 1024x1024. That is not a simplification: the VitDet+backbone builds its relative position tables from the input dimensions, so an+export with dynamic height and width silently returns wrong alphas at any other+size. Every rembg session already runs at a fixed resolution, so the image and+trimap are resized in and the alpha is resized back out.+"""++import os+from typing import Dict, Optional++import numpy as np+import onnxruntime as ort+import pooch+from PIL import Image+from PIL.Image import Image as PILImage+from scipy.ndimage import binary_erosion++from .sessions.base import BaseSession++# The resolution the checkpoints were exported at. Fixed on purpose; see above.+INPUT_SIZE = 1024++BASE_URL = "https://github.com/danielgatis/rembg/releases/download/v0.0.0"++# Distinctions-646 is trained on more varied real imagery than Composition-1k's+# synthetic composites, which leaves noticeably less background colour in the+# soft band on photographic input. The small variant is the default because the+# base one is 3.5x the download and 2.5x the runtime for a marginal gain.+DEFAULT_VARIANT = "small-distinctions-646"++VARIANTS: Dict[str, Dict[str, str]] = {+ "small-distinctions-646": {+ "fname": "vitmatte-small-distinctions-646.onnx",+ "sha256": "d232841ac9d9657df3e62f6c92ed425ee25df18d337245cd8b903fc1ba183631",+ },+ "small-composition-1k": {+ "fname": "vitmatte-small-composition-1k.onnx",+ "sha256": "659b9bb2870f80cffbe20dae4c7f18417fbdf68c0195861d24e9082c28373a24",+ },+ "base-distinctions-646": {+ "fname": "vitmatte-base-distinctions-646.onnx",+ "sha256": "d30190833269c1bec3e37319fe67af151028d3be32f6f60f6663a51b209cc8c1",+ },+ "base-composition-1k": {+ "fname": "vitmatte-base-composition-1k.onnx",+ "sha256": "87bb10979f816061497ba6867b338c65a05cebd7d1507f6dde92a86382dec1f2",+ },+}++_sessions: Dict[str, ort.InferenceSession] = {}+++class _ViTMatteFiles(BaseSession):+ """Borrows BaseSession's download and path handling only.++ ViTMatte is not a segmentation model, so it is deliberately not registered+ as a session: it cannot answer `predict(img)` without a mask to refine.+ Subclassing keeps its weights in the same `~/.rembg/models/<name>` layout as+ everything else instead of inventing a second download path.+ """++ def __init__(self, *args, **kwargs):+ raise NotImplementedError("ViTMatte is a refiner, not a session")++ @classmethod+ def name(cls, *args, **kwargs) -> str:+ return "vitmatte"++ @classmethod+ def download_models(cls, *args, **kwargs) -> str:+ variant = kwargs.get("variant", DEFAULT_VARIANT)+ spec = VARIANTS[variant]+ fname = spec["fname"]++ existing = cls.resolve_existing(fname)+ if existing is not None:+ return existing++ pooch.retrieve(+ f"{BASE_URL}/{fname}",+ None if cls.checksum_disabled() else f"sha256:{spec['sha256']}",+ fname=fname,+ path=cls.model_dir(),+ progressbar=True,+ )++ return os.path.join(cls.model_dir(), fname)+++def _resolve_variant(variant: Optional[str]) -> str:+ if variant is None:+ return DEFAULT_VARIANT++ if variant not in VARIANTS:+ raise ValueError(+ f"unknown vitmatte_model {variant!r}. "+ f"Available: {', '.join(sorted(VARIANTS))}"+ )++ return variant+++def _get_session(variant: str) -> ort.InferenceSession:+ """Load the model once per variant; each is 110-380 MB."""+ if variant not in _sessions:+ providers = ["CPUExecutionProvider"]+ if "CUDAExecutionProvider" in ort.get_available_providers():+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]++ _sessions[variant] = ort.InferenceSession(+ _ViTMatteFiles.download_models(variant=variant),+ providers=providers,+ )++ return _sessions[variant]+++def trimap_from_mask(+ mask: PILImage,+ foreground_threshold: int = 240,+ background_threshold: int = 10,+ erode_size: int = 10,+) -> PILImage:+ """Build the three-valued map ViTMatte expects from a mask.++ 255 is definite foreground, 0 definite background, and 128 the unknown band+ the network is asked to resolve. Both certain regions are eroded so the band+ covers the whole soft edge; anything left inside it is what gets refined.+ """+ mask_array = np.asarray(mask.convert("L"))++ is_foreground = mask_array > foreground_threshold+ is_background = mask_array < background_threshold++ structure = None+ if erode_size > 0:+ structure = np.ones((erode_size, erode_size), dtype=np.uint8)++ is_foreground = binary_erosion(is_foreground, structure=structure)+ is_background = binary_erosion(is_background, structure=structure, border_value=1)++ trimap = np.full(mask_array.shape, dtype=np.uint8, fill_value=128)+ trimap[is_foreground] = 255+ trimap[is_background] = 0++ return Image.fromarray(trimap)+++def vitmatte_alpha(+ img: PILImage,+ mask: PILImage,+ variant: Optional[str] = None,+ foreground_threshold: int = 240,+ background_threshold: int = 10,+ erode_size: int = 10,+) -> PILImage:+ """Refine `mask` into an alpha matte for `img`.++ Returns the alpha alone. The caller is responsible for unmixing the+ foreground colour, which `decontaminate_cutout` already does.+ """+ variant = _resolve_variant(variant)+ session = _get_session(variant)++ trimap = trimap_from_mask(+ mask, foreground_threshold, background_threshold, erode_size+ )++ # Bilinear for the image, nearest for the trimap: interpolating the trimap+ # would invent values between the three levels the model expects.+ image_resized = np.asarray(+ img.convert("RGB").resize((INPUT_SIZE, INPUT_SIZE), Image.Resampling.BILINEAR),+ dtype=np.float32,+ )+ trimap_resized = np.asarray(+ trimap.resize((INPUT_SIZE, INPUT_SIZE), Image.Resampling.NEAREST),+ dtype=np.float32,+ )++ # ViTMatte takes the image and trimap concatenated on the channel axis, both+ # scaled to 0-1 with no mean/std shift.+ pixel_values = np.concatenate(+ [+ (image_resized / 255.0).transpose(2, 0, 1),+ (trimap_resized / 255.0)[None],+ ],+ axis=0,+ )[None].astype(np.float32)++ alphas = session.run(None, {"pixel_values": pixel_values})[0]+ alpha = np.clip(alphas[0, 0], 0.0, 1.0)++ return Image.fromarray((alpha * 255).astype(np.uint8)).resize(+ img.size, Image.Resampling.BILINEAR+ )diff --git a/tests/test_matting.py b/tests/test_matting.pynew file mode 100644index 0000000..2f2ba5e--- /dev/null+++ b/tests/test_matting.py@@ -0,0 +1,77 @@+import numpy as np+import pytest+from PIL import Image++from rembg.matting import (+ DEFAULT_VARIANT,+ VARIANTS,+ _resolve_variant,+ trimap_from_mask,+)+++def test_default_variant_is_a_known_one():+ assert DEFAULT_VARIANT in VARIANTS+++def test_every_variant_declares_a_file_and_checksum():+ for name, spec in VARIANTS.items():+ assert spec["fname"].endswith(".onnx"), name+ assert len(spec["sha256"]) == 64, name+++def test_resolve_variant_defaults_when_unset():+ assert _resolve_variant(None) == DEFAULT_VARIANT+++def test_resolve_variant_accepts_known_names():+ for name in VARIANTS:+ assert _resolve_variant(name) == name+++def test_resolve_variant_rejects_unknown_names():+ with pytest.raises(ValueError, match="unknown vitmatte_model"):+ _resolve_variant("no-such-model")+++def test_resolve_variant_error_lists_the_options():+ with pytest.raises(ValueError) as excinfo:+ _resolve_variant("nope")++ for name in VARIANTS:+ assert name in str(excinfo.value)+++def _mask_with_soft_edge():+ """A mask with a hard core and a ramp, so the trimap has all three levels."""+ arr = np.zeros((64, 64), dtype=np.uint8)+ arr[16:48, 16:48] = 255+ arr[12:16, 16:48] = 128+ return Image.fromarray(arr)+++def test_trimap_has_only_the_three_expected_levels():+ trimap = trimap_from_mask(_mask_with_soft_edge())+ assert set(np.unique(np.asarray(trimap))) <= {0, 128, 255}+++def test_trimap_marks_an_unknown_band():+ trimap = np.asarray(trimap_from_mask(_mask_with_soft_edge()))+ assert (trimap == 128).sum() > 0+++def test_trimap_keeps_the_mask_size():+ mask = _mask_with_soft_edge()+ assert trimap_from_mask(mask).size == mask.size+++def test_larger_erode_size_widens_the_unknown_band():+ mask = _mask_with_soft_edge()+ narrow = np.asarray(trimap_from_mask(mask, erode_size=2))+ wide = np.asarray(trimap_from_mask(mask, erode_size=10))+ assert (wide == 128).sum() > (narrow == 128).sum()+++def test_trimap_accepts_a_non_grayscale_mask():+ mask = _mask_with_soft_edge().convert("RGB")+ assert set(np.unique(np.asarray(trimap_from_mask(mask)))) <= {0, 128, 255}