Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

simple background remover with no error checks #522

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions background-remover.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import io

import numpy as np
import rembg
from PIL import Image


class ImageProcessor:
def __init__(self, input_path: str, output_filename: str):
self.input_path = input_path
self.output_filename = output_filename

def remove_background(self):
image = Image.open(self.input_path)

output = rembg.remove(image)

if isinstance(output, bytes):
transparent_image = Image.open(io.BytesIO(output))
elif isinstance(output, np.ndarray):
transparent_image = Image.fromarray(output)
elif isinstance(output, Image.Image):
transparent_image = output
else:
raise TypeError(f"Unexpected type from rembg.remove(): {type(output)}")

# By default I expect output_filename to be {name}.png
transparent_image = transparent_image.convert("RGB")
transparent_image.save(self.output_filename)


processor = ImageProcessor(
input_path="test.jpg", output_filename="removed-background.png"
)
processor.remove_background()