Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
import torchvision.transforms as transforms
|
| 6 |
+
import numpy as np
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
# Install and import (for Hugging Face environment)
|
| 10 |
+
try:
|
| 11 |
+
import pytorch_hub_examples
|
| 12 |
+
except ModuleNotFoundError: # Handle if not installed (Hugging Face)
|
| 13 |
+
import subprocess
|
| 14 |
+
subprocess.run(["git", "clone", "https://github.com/facebookresearch/pytorch_hub_examples.git"])
|
| 15 |
+
subprocess.run(["cd", "pytorch_hub_examples", "&&", "pip", "install", "-e", "."])
|
| 16 |
+
import pytorch_hub_examples
|
| 17 |
+
|
| 18 |
+
# Load the U-2-Net model
|
| 19 |
+
model = pytorch_hub_examples.u2net(pretrained=True)
|
| 20 |
+
model.eval()
|
| 21 |
+
|
| 22 |
+
# Define the transform
|
| 23 |
+
transform = transforms.Compose([
|
| 24 |
+
transforms.Resize((320, 320)), # Resize for U-2-Net
|
| 25 |
+
transforms.ToTensor(),
|
| 26 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # ImageNet stats
|
| 27 |
+
])
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def remove_background(image):
|
| 31 |
+
try:
|
| 32 |
+
img = transform(image).unsqueeze(0)
|
| 33 |
+
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
out = model(img)
|
| 36 |
+
mask = torch.sigmoid(out[0]) # Get the mask
|
| 37 |
+
|
| 38 |
+
mask = mask.squeeze().cpu().numpy()
|
| 39 |
+
mask = (mask * 255).astype(np.uint8)
|
| 40 |
+
mask = Image.fromarray(mask).convert("L")
|
| 41 |
+
|
| 42 |
+
image = image.convert("RGBA")
|
| 43 |
+
new_image = Image.new("RGBA", image.size, (255, 255, 255, 0))
|
| 44 |
+
|
| 45 |
+
for x in range(image.width):
|
| 46 |
+
for y in range(image.height):
|
| 47 |
+
if mask.getpixel((x, y)) > 0:
|
| 48 |
+
new_image.putpixel((x, y), image.getpixel((x, y)))
|
| 49 |
+
|
| 50 |
+
return new_image
|
| 51 |
+
except Exception as e:
|
| 52 |
+
return f"Error: {e}"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
with gr.Blocks() as demo:
|
| 56 |
+
image_input = gr.Image(type="pil")
|
| 57 |
+
image_output = gr.Image()
|
| 58 |
+
image_button = gr.Button("Remove Background")
|
| 59 |
+
image_button.click(remove_background, inputs=image_input, outputs=image_output)
|
| 60 |
+
|
| 61 |
+
demo.launch()
|