forked from souravjain540/Basic-Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground-remover.py
35 lines (26 loc) · 1.02 KB
/
background-remover.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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()