Closed BanKeTang closed 7 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
@BanKeTang
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>
I ran into the same problem. I created a pull request with the fix here: https://github.com/nadermx/backgroundremover/pull/138
Fixed in https://github.com/nadermx/backgroundremover/commit/123d4445808c25521d06611e6e7e3aa9bb426b2f read ReadMe to on how to. Tx @ahmad88me
How to use as a library to use python to remove the background from a given image path.