bg_remover / bg_remover.py
nexusbert's picture
push
cb4555d
from PIL import Image
from rembg import remove, new_session
import logging
import os
from typing import Tuple
class BackgroundRemover:
def __init__(self, model_name: str = "isnet-general-use"):
self.model = model_name
self.session = new_session(model_name)
logging.basicConfig(level=logging.INFO)
def remove_background(self, input_image: Image.Image) -> Image.Image:
return remove(
input_image,
session=self.session,
alpha_matting=True,
alpha_matting_foreground_threshold=270,
alpha_matting_background_threshold=20,
alpha_matting_erode_size=11
)
def process_image(self, input_path: str, output_path: str) -> Tuple[bool, str]:
try:
with Image.open(input_path) as input_image:
output = self.remove_background(input_image)
if not output_path.lower().endswith('.png'):
output_path = os.path.splitext(output_path)[0] + '.png'
output.save(output_path, 'PNG')
return True, "Background removed successfully"
except Exception as e:
logging.error(f"Error processing image: {str(e)}")
return False, f"Error processing image: {str(e)}"