Rembg is a tool to remove images background
feat: add opt-in color decontamination for soft edges (#843)
Daniel Gatis1dd1ad4a6c42
diff --git a/README.md b/README.mdindex 923a8d4..7c91ef6 100644--- a/README.md+++ b/README.md@@ -155,6 +155,14 @@ rembg i -om path/to/input.png path/to/output.pngrembg i -a path/to/input.png path/to/output.png```+**Remove color fringing from soft edges:**++```shell+rembg i -dc path/to/input.png path/to/output.png+```++See [Color decontamination](#color-decontamination) for what this does.+**Pass extra parameters (SAM example):**```shell@@ -335,6 +343,92 @@ with open('input.png', 'rb') as i:For more examples, see the [examples](USAGE.md) page.+## Choosing an edge mode++Rembg has three ways to turn a mask into a cutout. They differ only in how they+treat the *soft* pixels along an edge — hair, fur, fabric, motion blur.++| Mode | Flag | Fixes edge color | Refines the mask | Cost |+| --- | --- | --- | --- | --- |+| Naive | *(default)* | No | No | Free |+| Decontaminate | `-dc` | Yes | No | Negligible |+| Alpha matting | `-a` | Yes | Yes | Slow |++They are alternatives, not layers — `-a` already decontaminates internally, so+passing both changes nothing. Pick one:++**Use the default (naive)** when the subject has hard edges — products, cars,+logos, screenshots — or when the background was already close in color to the+subject. There is nothing to correct, so the extra work buys nothing.++**Use `-dc`** when the cutout has a colored halo: the subject was shot against+a strongly colored background (green grass, blue sky, a painted wall) and that+color survives as a rim around hair or fine detail. This is the common case,+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 — the+model 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.++### Which model to pair it with++The newer models (`birefnet-*`, `isnet-general-use`, `bria-rmbg`) already+produce a soft, well-shaped alpha, so their masks rarely need `-a` — reach for+`-dc` first and only try `-a` if the edge shape itself is wrong.++The older models (`u2net`, `u2netp`, `silueta`) tend to produce firmer, blockier+edges. They benefit most from `-a` on hair-heavy portraits, and are also where+its 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.++> 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`+> is pointless — there is nothing left to correct. Use one or the other.++## Color decontamination++On a soft edge — hair, fur, motion blur — a pixel is not purely foreground or+purely background. The camera captured a blend of the two:++```+captured = alpha * foreground + (1 - alpha) * background+```++Making that pixel semi-transparent does not undo the blend, so the background+color stays mixed into it and shows up as a colored halo around fine detail.+A subject shot against green grass keeps a green rim; against a blue wall, a+blue one. This is the same operation Photoshop calls *Decontaminate Colors*+and Nuke calls *decontamination*.++Rembg can estimate the true foreground color and write that instead. This is+opt-in:++```python+from rembg import remove++output = remove(input, decontaminate=True)+```++```shell+rembg i -dc path/to/input.png path/to/output.png # single file+rembg p -dc path/to/input path/to/output # folder+```++```shell+curl -s "http://localhost:7000/api/remove?url=...&dc=true" > output.png+```++Notes:++- It only changes color, never coverage — the alpha channel is untouched.+- The cost is negligible next to model inference, which dominates runtime.+- `--alpha-matting` already does this internally, so the flag is ignored there.+## Usage with Docker### CPU Onlydiff --git a/rembg/bg.py b/rembg/bg.pyindex 68de0cd..6814857 100644--- a/rembg/bg.py+++ b/rembg/bg.py@@ -111,6 +111,37 @@ def naive_cutout(img: PILImage, mask: PILImage) -> PILImage:return cutout+def decontaminate_cutout(img: PILImage, mask: PILImage) -> PILImage:+ """+ Estimate the true foreground color and apply the mask as alpha.++ Unlike naive_cutout, this recovers the unblended foreground color for+ semi-transparent pixels. A pixel on a soft edge was captured as a mix of+ the foreground and the background behind it, so simply making it+ transparent leaves the background color behind as fringing, which is most+ visible around fine details such as hair.++ Args:+ img (PILImage): The image to be modified.+ mask (PILImage): The mask to be applied as alpha.++ Returns:+ PILImage: The cutout with the background color fringing removed.+ """+ if img.mode != "RGB":+ img = img.convert("RGB")++ img_normalized = np.asarray(img) / 255.0+ alpha = np.asarray(mask.convert("L")) / 255.0++ foreground = estimate_foreground_ml(img_normalized, alpha)+ cutout = stack_images(foreground, alpha)++ cutout = np.clip(cutout * 255, 0, 255).astype(np.uint8)++ return Image.fromarray(cutout)++def putalpha_cutout(img: PILImage, mask: PILImage) -> PILImage:"""Apply the specified mask to the image as an alpha cutout.@@ -234,6 +265,7 @@ def remove(session: Optional[BaseSession] = None,only_mask: bool = False,post_process_mask: bool = False,+ decontaminate: bool = False,bgcolor: Optional[Tuple[int, int, int, int]] = None,force_return_bytes: bool = False,*args: Optional[Any],@@ -253,6 +285,7 @@ def remove(session (Optional[BaseSession], optional): A session object for the 'u2net' model. Defaults to None.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.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.@@ -305,13 +338,17 @@ def remove(alpha_matting_erode_size,)except ValueError:+ # Alpha matting already unmixes the foreground color, so fall+ # back to the decontaminated cutout to keep the edges usable.if putalpha:cutout = putalpha_cutout(img, mask)else:- cutout = naive_cutout(img, mask)+ cutout = decontaminate_cutout(img, mask)else:if putalpha:cutout = putalpha_cutout(img, mask)+ elif decontaminate:+ cutout = decontaminate_cutout(img, mask)else:cutout = naive_cutout(img, mask)diff --git a/rembg/commands/i_command.py b/rembg/commands/i_command.pyindex b840e3d..cc9fe99 100644--- a/rembg/commands/i_command.py+++ b/rembg/commands/i_command.py@@ -68,6 +68,13 @@ from ..sessions import sessions_namesshow_default=True,help="post process the mask",)+ "-dc",+ "--decontaminate",+ is_flag=True,+ show_default=True,+ help="remove the background color fringing left on soft edges",+)@click.option("-bgc","--bgcolor",diff --git a/rembg/commands/p_command.py b/rembg/commands/p_command.pyindex 77fc5ec..4dcd462 100644--- a/rembg/commands/p_command.py+++ b/rembg/commands/p_command.py@@ -137,6 +137,13 @@ def _confirm_usage_cost(show_default=True,help="post process the mask",)+ "-dc",+ "--decontaminate",+ is_flag=True,+ show_default=True,+ help="remove the background color fringing left on soft edges",+)@click.option("-w","--watch",diff --git a/rembg/commands/s_command.py b/rembg/commands/s_command.pyindex 1d7897d..f3e2e3a 100644--- a/rembg/commands/s_command.py+++ b/rembg/commands/s_command.py@@ -133,6 +133,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"),bgc: Optional[str] = Query(default=None, description="Background Color"),extras: Optional[str] = Query(default=None, description="Extra parameters as JSON"@@ -145,6 +146,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -self.ae = aeself.om = omself.ppm = ppm+ self.dc = dcself.extras = extrasself.bgc = (cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))@@ -178,6 +180,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"),bgc: Optional[str] = Query(default=None, description="Background Color"),extras: Optional[str] = Query(default=None, description="Extra parameters as JSON"@@ -190,6 +193,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -self.ae = aeself.om = omself.ppm = ppm+ self.dc = dcself.extras = extrasself.bgc = (cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))@@ -224,6 +228,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -alpha_matting_erode_size=commons.ae,only_mask=commons.om,post_process_mask=commons.ppm,+ decontaminate=commons.dc,bgcolor=commons.bgc,**kwargs,),@@ -388,7 +393,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, cmd_args = args+ a, af, ab, ae, om, ppm, dc, cmd_args = argskwargs = {"alpha_matting": a,@@ -397,6 +402,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -"alpha_matting_erode_size": ae,"only_mask": om,"post_process_mask": ppm,+ "decontaminate": dc,}extras = {}@@ -432,6 +438,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.Textbox(label="Arguments"),],gr.components.Image(type="pil", label="Output"),diff --git a/tests/test_decontaminate.py b/tests/test_decontaminate.pynew file mode 100644index 0000000..91279c0--- /dev/null+++ b/tests/test_decontaminate.py@@ -0,0 +1,96 @@+import numpy as np+from PIL import Image++from rembg.bg import decontaminate_cutout, naive_cutout++# The foreground color the decontamination has to recover, and the background+# it was composited over. Building the fixture instead of shipping a photo keeps+# the ground truth exact: we know what every soft pixel should look like.+FG_COLOR = np.array([200, 90, 60], dtype=np.float64)+BG_COLOR = np.array([0, 220, 40], dtype=np.float64)+++def make_fringed_image(size=256):+ """Composite thin strands over a saturated background.++ Returns the captured image, its mask, and the soft-edge selector. The+ strands are sub-pixel wide, so most of their pixels are partially+ transparent -- exactly where background color bleeds in.+ """+ rng = np.random.default_rng(0)+ yy, xx = np.mgrid[0:size, 0:size]+ alpha = np.zeros((size, size), dtype=np.float64)++ body = (+ ((xx - size / 2) / (size * 0.3)) ** 2+ + ((yy - size * 0.78) / (size * 0.25)) ** 2+ ) <= 1.0+ alpha[body] = 1.0++ for i in range(40):+ x0 = size / 2 + rng.normal(0, size * 0.11)+ length = rng.uniform(size * 0.35, size * 0.6)+ width = rng.uniform(0.7, 1.8)+ for t in np.linspace(0, 1, int(length * 2)):+ y = size * 0.72 - t * length+ x = x0 + np.sin(t * 5 + i) * 6+ if not (0 <= y < size and 0 <= x < size):+ continue+ yi, xi = int(y), int(x)+ lo_y, hi_y = max(0, yi - 3), min(size, yi + 4)+ lo_x, hi_x = max(0, xi - 3), min(size, xi + 4)+ d2 = (yy[lo_y:hi_y, lo_x:hi_x] - y) ** 2 + (+ xx[lo_y:hi_y, lo_x:hi_x] - x+ ) ** 2+ contrib = np.exp(-d2 / (2 * width**2)) * (1 - t * 0.5)+ alpha[lo_y:hi_y, lo_x:hi_x] = np.maximum(+ alpha[lo_y:hi_y, lo_x:hi_x], contrib+ )++ alpha = np.clip(alpha, 0, 1)+ a3 = alpha[:, :, None]+ composite = np.clip(a3 * FG_COLOR + (1 - a3) * BG_COLOR, 0, 255).astype(np.uint8)++ img = Image.fromarray(composite)+ mask = Image.fromarray((alpha * 255).astype(np.uint8))+ soft = (alpha > 0.05) & (alpha < 0.95)+ return img, mask, soft+++def test_decontaminate_removes_background_color_fringing():+ img, mask, soft = make_fringed_image()++ naive = np.asarray(naive_cutout(img, mask).convert("RGBA")).astype(np.float64)+ decontaminated = np.asarray(decontaminate_cutout(img, mask).convert("RGBA")).astype(+ np.float64+ )++ naive_err = np.linalg.norm(naive[soft][:, :3] - FG_COLOR, axis=1).mean()+ decontaminate_err = np.linalg.norm(+ decontaminated[soft][:, :3] - FG_COLOR, axis=1+ ).mean()++ # The naive cutout leaves the blended color in place; decontamination+ # recovers something very close to the true foreground.+ assert decontaminate_err < naive_err / 10+ assert decontaminate_err < 10+++def test_decontaminate_preserves_alpha():+ img, mask, _ = make_fringed_image()++ cutout = decontaminate_cutout(img, mask).convert("RGBA")+ alpha_out = np.asarray(cutout)[:, :, 3]++ # The mask is used as-is: decontamination only changes color, never coverage.+ assert np.array_equal(alpha_out, np.asarray(mask))+++def test_decontaminate_leaves_opaque_pixels_alone():+ img, mask, _ = make_fringed_image()++ cutout = decontaminate_cutout(img, mask).convert("RGBA")+ arr = np.asarray(cutout).astype(np.float64)+ opaque = np.asarray(mask) == 255++ assert np.abs(arr[opaque][:, :3] - FG_COLOR).max() <= 2