VIATEUR-AI commited on
Commit
643f829
·
verified ·
1 Parent(s): dbb6640

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -32
app.py CHANGED
@@ -1,37 +1,32 @@
1
- import requests
 
 
2
  from PIL import Image
3
- from io import BytesIO
4
- import torch
5
- from transformers import DPTForDepthEstimation, DPTFeatureExtractor
6
 
7
- # Example: Load an image
8
- image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/image_classification.png"
9
- response = requests.get(image_url)
10
- image = Image.open(BytesIO(response.content)).convert("RGB")
 
 
 
 
 
 
11
 
12
- # Load Hugging Face DPT depth estimation model (can be used to segment background)
13
- model_name = "Intel/dpt-large"
14
- feature_extractor = DPTFeatureExtractor.from_pretrained(model_name)
15
- model = DPTForDepthEstimation.from_pretrained(model_name)
16
 
17
- # Preprocess image
18
- inputs = feature_extractor(images=image, return_tensors="pt")
19
- with torch.no_grad():
20
- outputs = model(**inputs)
21
- predicted_depth = outputs.predicted_depth
 
 
 
22
 
23
- # Convert to numpy and normalize
24
- depth = predicted_depth.squeeze().cpu().numpy()
25
- depth_min, depth_max = depth.min(), depth.max()
26
- normalized_depth = (depth - depth_min) / (depth_max - depth_min)
27
-
28
- # Simple threshold to create mask (background = 1)
29
- import numpy as np
30
- mask = (normalized_depth < 0.6).astype(np.uint8) * 255
31
-
32
- # Apply mask to image
33
- image_np = np.array(image)
34
- image_rgba = np.dstack([image_np, mask]) # add alpha channel
35
- result = Image.fromarray(image_rgba)
36
- result.save("output.png")
37
- print("Background removed and saved as output.png")
 
1
+ # app.py
2
+ import gradio as gr
3
+ from rembg import remove
4
  from PIL import Image
5
+ import io
 
 
6
 
7
+ # Function to remove background
8
+ def remove_background(image):
9
+ # Convert uploaded image to PIL
10
+ pil_image = Image.fromarray(image).convert("RGBA")
11
+
12
+ # Remove background
13
+ result = remove(pil_image)
14
+
15
+ # Convert result to displayable format
16
+ return result
17
 
18
+ # Gradio UI
19
+ title = "AI Background Remover"
20
+ description = "Upload an image and remove its background instantly! Made by Viateur Irasubiza."
 
21
 
22
+ iface = gr.Interface(
23
+ fn=remove_background,
24
+ inputs=gr.Image(type="numpy", label="Upload Your Image"),
25
+ outputs=gr.Image(type="pil", label="Result"),
26
+ title=title,
27
+ description=description,
28
+ allow_flagging="never"
29
+ )
30
 
31
+ # Launch the app
32
+ iface.launch()