nadermx / backgroundremover

Background Remover lets you Remove Background from images and video using AI with a simple command line interface that is free and open source.
https://www.backgroundremoverai.com
MIT License
6.45k stars 535 forks source link

How to use as a library? #95

Closed BanKeTang closed 2 months ago

BanKeTang commented 10 months ago

How to use as a library to use python to remove the background from a given image path.

Sourland commented 8 months ago

To use it as a package take the bg.py and the u2net folder. Delete the utilities.py imports and replace remove() with

def remove(
    data,
    model_name="u2net",
    alpha_matting=False,
    alpha_matting_foreground_threshold=240,
    alpha_matting_background_threshold=10,
    alpha_matting_erode_structure_size=10,
    alpha_matting_base_size=1000,
):
    model = get_model(model_name)
    img = Image.fromarray(data.astype('uint8'), 'RGB')
    mask = detect.predict(model, np.array(img)).convert("L")

    if alpha_matting:
        cutout = alpha_matting_cutout(
            img,
            mask,
            alpha_matting_foreground_threshold,
            alpha_matting_background_threshold,
            alpha_matting_erode_structure_size,
            alpha_matting_base_size,
        )
    else:
        cutout = naive_cutout(img, mask)

    # Convert the PIL Image back to ndarray
    cutout_array = np.array(cutout)

    return cutout_array
Sourland commented 8 months ago

@BanKeTang

Tatsh commented 6 months ago

There is currently a circular import between bg.py and utilities.py:

(ins)>>> from backgroundremover.bg import remove
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.11/site-packages/backgroundremover/bg.py", line 15, in <module>
    from .u2net import detect, u2net
  File "/usr/lib/python3.11/site-packages/backgroundremover/u2net/detect.py", line 11, in <module>
    from .. import utilities
  File "/usr/lib/python3.11/site-packages/backgroundremover/utilities.py", line 9, in <module>
    from .bg import DEVICE, Net, iter_frames, remove_many
ImportError: cannot import name 'DEVICE' from partially initialized module 'backgroundremover.bg' (most likely due to a circular import) (/usr/lib/python3.11/site-packages/backgroundremover/bg.py)

It is possible to import from the cli module, but this should not be necessary.

(ins)>>> from backgroundremover.cmd.cli import remove
(ins)>>> remove
<function remove at 0x7f27dd192ca0>
ahmad88me commented 2 months ago

I ran into the same problem. I created a pull request with the fix here: https://github.com/nadermx/backgroundremover/pull/138

nadermx commented 2 months ago

Fixed in https://github.com/nadermx/backgroundremover/commit/123d4445808c25521d06611e6e7e3aa9bb426b2f read ReadMe to on how to. Tx @ahmad88me