IOPaint/iopaint/plugins/remove_bg.py

72 lines
2.2 KiB
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
2024-02-08 09:49:54 +01:00
from loguru import logger
2023-03-26 07:39:09 +02:00
from torch.hub import get_dir
2023-03-22 05:57:18 +01:00
2024-01-05 08:19:23 +01:00
from iopaint.plugins.base_plugin import BasePlugin
2024-02-08 09:49:54 +01:00
from iopaint.schema import RunPluginRequest, RemoveBGModel
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"
support_gen_mask = True
support_gen_image = True
2023-03-22 05:57:18 +01:00
2024-02-08 09:49:54 +01:00
def __init__(self, model_name):
2023-03-26 06:37:58 +02:00
super().__init__()
2024-02-08 09:49:54 +01:00
self.model_name = model_name
2023-03-22 05:57:18 +01:00
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
2024-02-08 09:49:54 +01:00
self._init_session(model_name)
2023-03-22 05:57:18 +01:00
2024-02-08 09:49:54 +01:00
def _init_session(self, model_name: str):
if model_name == RemoveBGModel.briaai_rmbg_1_4:
from iopaint.plugins.briarmbg import (
create_briarmbg_session,
briarmbg_process,
)
self.session = create_briarmbg_session()
self.remove = briarmbg_process
else:
from rembg import new_session, remove
self.session = new_session(model_name=model_name)
self.remove = remove
2023-03-22 05:57:18 +01:00
2024-02-08 09:49:54 +01:00
def switch_model(self, new_model_name):
if self.model_name == new_model_name:
return
logger.info(
f"Switching removebg model from {self.model_name} to {new_model_name}"
)
self._init_session(new_model_name)
self.model_name = new_model_name
def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray:
bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR)
2023-03-22 05:57:18 +01:00
# return BGRA image
2024-02-08 09:49:54 +01:00
output = self.remove(bgr_np_img, session=self.session)
2023-05-09 13:07:12 +02:00
return cv2.cvtColor(output, cv2.COLOR_BGRA2RGBA)
2023-03-26 06:37:58 +02:00
def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray:
bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR)
# return BGR image, 255 means foreground, 0 means background
2024-02-08 09:49:54 +01:00
output = self.remove(bgr_np_img, session=self.session, only_mask=True)
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"
)