Jonny001 commited on
Commit
d5e9e6d
·
verified ·
1 Parent(s): 279e55f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -0
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from loadimg import load_img
3
+ import spaces
4
+ from transformers import AutoModelForImageSegmentation
5
+ import torch
6
+ from torchvision import transforms
7
+ from typing import Union, Tuple
8
+ from PIL import Image
9
+
10
+ torch.set_float32_matmul_precision(["high", "highest"][0])
11
+
12
+ birefnet = AutoModelForImageSegmentation.from_pretrained(
13
+ "ZhengPeng7/BiRefNet", trust_remote_code=True
14
+ )
15
+ birefnet.to("cpu")
16
+
17
+ transform_image = transforms.Compose(
18
+ [
19
+ transforms.Resize((1024, 1024)),
20
+ transforms.ToTensor(),
21
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
22
+ ]
23
+ )
24
+
25
+ def fn(image: Union[Image.Image, str]) -> Tuple[Image.Image, Image.Image]:
26
+ """
27
+ Remove the background from an image and return both the transparent version and the original.
28
+ This function performs background removal using a BiRefNet segmentation model. It is intended for use
29
+ with image input (either uploaded or from a URL). The function returns a transparent PNG version of the image
30
+ with the background removed, along with the original RGB version for comparison.
31
+ Args:
32
+ image (PIL.Image or str): The input image, either as a PIL object or a filepath/URL string.
33
+ Returns:
34
+ tuple:
35
+ - processed_image (PIL.Image): The input image with the background removed and transparency applied.
36
+ - origin (PIL.Image): The original RGB image, unchanged.
37
+ """
38
+ im = load_img(image, output_type="pil")
39
+ im = im.convert("RGB")
40
+ origin = im.copy()
41
+ processed_image = process(im)
42
+ return (origin, processed_image)
43
+
44
+ @spaces.GPU
45
+ def process(image: Image.Image) -> Image.Image:
46
+ """
47
+ Apply BiRefNet-based image segmentation to remove the background.
48
+ This function preprocesses the input image, runs it through a BiRefNet segmentation model to obtain a mask,
49
+ and applies the mask as an alpha (transparency) channel to the original image.
50
+ Args:
51
+ image (PIL.Image): The input RGB image.
52
+ Returns:
53
+ PIL.Image: The image with the background removed, using the segmentation mask as transparency.
54
+ """
55
+ image_size = image.size
56
+ input_images = transform_image(image).unsqueeze(0).to("cpu")
57
+ # Prediction
58
+ with torch.no_grad():
59
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
60
+ pred = preds[0].squeeze()
61
+ pred_pil = transforms.ToPILImage()(pred)
62
+ mask = pred_pil.resize(image_size)
63
+ image.putalpha(mask)
64
+ return image
65
+
66
+ def process_file(f: str) -> str:
67
+ """
68
+ Load an image file from disk, remove the background, and save the output as a transparent PNG.
69
+ Args:
70
+ f (str): Filepath of the image to process.
71
+ Returns:
72
+ str: Path to the saved PNG image with background removed.
73
+ """
74
+ name_path = f.rsplit(".", 1)[0] + ".png"
75
+ im = load_img(f, output_type="pil")
76
+ im = im.convert("RGB")
77
+ transparent = process(im)
78
+ transparent.save(name_path)
79
+ return name_path
80
+
81
+ slider1 = gr.ImageSlider(label="Processed Image", type="pil", format="png")
82
+ slider2 = gr.ImageSlider(label="Processed Image from URL", type="pil", format="png")
83
+ image_upload = gr.Image(label="Upload an image")
84
+ image_file_upload = gr.Image(label="Upload an image", type="filepath")
85
+ url_input = gr.Textbox(label="Paste an image URL")
86
+ output_file = gr.File(label="Output PNG File")
87
+
88
+ tab1 = gr.Interface(fn, inputs=image_upload, outputs=slider1, api_name="image")
89
+ tab2 = gr.Interface(fn, inputs=url_input, outputs=slider2, api_name="text")
90
+ tab3 = gr.Interface(process_file, inputs=image_file_upload, outputs=output_file, api_name="png")
91
+
92
+ demo = gr.TabbedInterface(
93
+ [tab1, tab2, tab3], ["Image Upload", "URL Input", "File Output"], title="✂ Image Background Removar ✂"
94
+ )
95
+
96
+ if __name__ == "__main__":
97
+ demo.launch(show_error=True, mcp_server=True)