Spaces:
Running
Running
import os | |
import gradio as gr | |
from gradio_imageslider import ImageSlider | |
from loadimg import load_img | |
import requests | |
import base64 | |
from PIL import Image | |
from io import BytesIO | |
import numpy as np | |
output_folder = 'output_images' | |
if not os.path.exists(output_folder): | |
os.makedirs(output_folder) | |
def fn(image): | |
im = load_img(image, output_type="pil") | |
im = im.convert("RGB") | |
origin = im.copy() | |
image = process(im) | |
image_path = os.path.join(output_folder, "no_bg_image.png") | |
image.save(image_path) | |
return (image, origin), image_path | |
def process(image): | |
def numpy_to_pil(image): | |
"""Convert a numpy array to a PIL Image.""" | |
if image.dtype == np.uint8: # Most common case | |
mode = "RGB" | |
else: | |
mode = "F" # Floating point | |
return Image.fromarray(image.astype('uint8'), mode) | |
image = numpy_to_pil(image) # Convert numpy array to PIL Image | |
buffered = BytesIO() | |
image.save(buffered, format="PNG") | |
img_str = base64.b64encode(buffered.getvalue()).decode('utf-8') | |
response = requests.post( | |
os.getenv('BACKEND_URL'), | |
files={"file": ("image.png", base64.b64decode(img_str), "image/png")} | |
) | |
result = response.json() | |
processed_image_b64 = result["processed_image"] | |
processed_image = Image.open(BytesIO(base64.b64decode(processed_image_b64))) | |
return processed_image # Return the original and processed images | |
def process_file(f): | |
name_path = f.rsplit(".", 1)[0] + ".png" | |
im = load_img(f, output_type="pil") | |
im = im.convert("RGB") | |
transparent = process(im) | |
transparent.save(name_path) | |
return name_path | |
slider1 = ImageSlider(label="RMBG-2.0", type="pil") | |
slider2 = ImageSlider(label="RMBG-2.0", type="pil") | |
image = gr.Image(label="Upload an image") | |
image2 = gr.Image(label="Upload an image", type="filepath") | |
text = gr.Textbox(label="Paste an image URL") | |
png_file = gr.File(label="output png file") | |
chameleon = load_img("elephant.jpg", output_type="pil") | |
url = "http://farm9.staticflickr.com/8488/8228323072_76eeddfea3_z.jpg" | |
tab1 = gr.Interface( | |
fn, inputs=image, outputs=[slider1, gr.File(label="output png file")], examples=[chameleon], api_name="image" | |
) | |
tab2 = gr.Interface(fn, inputs=text, outputs=[slider2, gr.File(label="output png file")], examples=[url], | |
api_name="text") | |
tab3 = gr.Interface(process_file, inputs=image2, outputs=png_file, examples=["elephant.jpg"], api_name="png") | |
demo = gr.TabbedInterface( | |
[tab1, tab2], ["input image", "input url"], title=" background removal" | |
) | |
if __name__ == "__main__": | |
demo.launch(show_error=True) |