IOPaint/lama_cleaner/plugins/remove_bg.py

40 lines
1018 B
Python
Raw Normal View History

2023-03-26 07:39:09 +02:00
import os
2023-03-22 05:57:18 +01:00
import cv2
import numpy as np
2023-03-26 07:39:09 +02:00
from torch.hub import get_dir
2023-03-22 05:57:18 +01:00
2023-03-26 06:37:58 +02:00
from lama_cleaner.plugins.base_plugin import BasePlugin
2023-03-22 05:57:18 +01:00
2023-03-26 06:37:58 +02:00
class RemoveBG(BasePlugin):
2023-03-22 05:57:18 +01:00
name = "RemoveBG"
def __init__(self):
2023-03-26 06:37:58 +02:00
super().__init__()
2023-03-22 05:57:18 +01:00
from rembg import new_session
2023-03-26 07:39:09 +02:00
hub_dir = get_dir()
model_dir = os.path.join(hub_dir, "checkpoints")
os.environ["U2NET_HOME"] = model_dir
2023-03-22 05:57:18 +01:00
self.session = new_session(model_name="u2net")
def __call__(self, rgb_np_img, files, form):
bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR)
return self.forward(bgr_np_img)
def forward(self, bgr_np_img) -> np.ndarray:
from rembg import remove
# return BGRA image
output = remove(bgr_np_img, session=self.session)
return output
2023-03-26 06:37:58 +02:00
def check_dep(self):
try:
import rembg
except ImportError:
return (
"RemoveBG is not installed, please install it first. pip install rembg"
)