Skip to content

Alpha matting #10

@Mathnerd314

Description

@Mathnerd314

From what I can tell you are doing the basic "naive" cutout compositing (here). There is some code in rembg called "alpha matting" which is a little more involved (same model, just different post-processing): https://github.com/danielgatis/rembg/blob/main/rembg/bg.py#L34-L100. The projects are both MIT licensed so there is no license issue.

Comparison (try viewing at 1:1 pixel ratio in a new tab and setting the CSS background-color property to black/white/magenta with devtools):

Naive Alpha Matting
1695711470810 naive 1695711470810 alpha
1695711470819 naive 1695711470819 alpha
1695711470828 naive 1695711470828 alpha
IMG_20231212_142034673 naive IMG_20231212_142034673 alpha

Last is my image (I am making an alcohol tracker, the plan is that users will take pictures of cans and bottles). To my eyes all of the cutouts are just a little better with the alpha matting, less of a "halo". For example the junk on the left side of the bear is less prominent. I haven't timed the additional processing required but I think it is minimal compared to running the model, so even if the effect is unnoticeable for most use cases I think it is worth porting.

Here is how I generated the images in Colab:

!pip install rembg
from rembg import new_session, remove
from PIL import Image
from pathlib import Path

session = new_session("u2netp")
for file in Path('/content').glob('*.jpg'):
    input_path = str(file)
    output_path = str(file.parent / (file.stem + ".naive.png"))
    output_path2 = str(file.parent / (file.stem + ".alpha.png"))

    input = Image.open(input_path)
    output = remove(input, session=session)
    output.save(output_path)
    input2 = Image.open(input_path)
    output2 = remove(input2, session=session,
                     bgcolor=(0, 0, 0, 0),
                     alpha_matting=True, alpha_matting_foreground_threshold=270,alpha_matting_background_threshold=20, alpha_matting_erode_size=11)
    output2.save(output_path2)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions