Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,105 +1,27 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import numpy as np
|
| 3 |
-
import torch
|
| 4 |
-
import torch.nn as nn
|
| 5 |
-
from torchvision import transforms
|
| 6 |
-
from PIL import Image
|
| 7 |
import gradio as gr
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# Setup model directory
|
| 13 |
-
os.makedirs("saved_models", exist_ok=True)
|
| 14 |
-
|
| 15 |
-
# Custom image normalization
|
| 16 |
-
def normalize_image(image, mean, std):
|
| 17 |
-
"""Normalize a torch tensor image with mean and std"""
|
| 18 |
-
if image.dim() == 3:
|
| 19 |
-
image = image.unsqueeze(0)
|
| 20 |
-
image = image.clone()
|
| 21 |
-
for t, m, s in zip(image[0], mean, std):
|
| 22 |
-
t.sub_(m).div_(s)
|
| 23 |
-
return image.squeeze(0)
|
| 24 |
-
|
| 25 |
-
# Simplified model definition
|
| 26 |
-
class SegmentationModel(nn.Module):
|
| 27 |
-
def __init__(self):
|
| 28 |
-
super().__init__()
|
| 29 |
-
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
|
| 30 |
-
self.conv2 = nn.Conv2d(64, 1, kernel_size=3, padding=1)
|
| 31 |
-
|
| 32 |
-
def forward(self, x):
|
| 33 |
-
x = torch.relu(self.conv1(x))
|
| 34 |
-
return torch.sigmoid(self.conv2(x))
|
| 35 |
-
|
| 36 |
-
# Initialize model
|
| 37 |
-
model = SegmentationModel().to(device)
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
if os.path.exists(model_path):
|
| 42 |
-
try:
|
| 43 |
-
model.load_state_dict(torch.load(model_path, map_location=device))
|
| 44 |
-
print("Loaded pretrained weights")
|
| 45 |
-
except Exception as e:
|
| 46 |
-
print(f"Could not load weights: {str(e)}")
|
| 47 |
-
model.eval()
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
transforms.ToTensor(),
|
| 52 |
-
lambda x: normalize_image(x, mean=[0.5, 0.5, 0.5], std=[1.0, 1.0, 1.0])
|
| 53 |
-
])
|
| 54 |
|
| 55 |
-
|
| 56 |
-
"""Process an image through the segmentation model"""
|
| 57 |
-
try:
|
| 58 |
-
# Convert Gradio input to PIL Image
|
| 59 |
-
if isinstance(input_image, str):
|
| 60 |
-
img = Image.open(input_image).convert("RGB")
|
| 61 |
-
else:
|
| 62 |
-
img = Image.fromarray(input_image).convert("RGB")
|
| 63 |
-
|
| 64 |
-
# Preprocess
|
| 65 |
-
img_tensor = transform(img).unsqueeze(0).to(device)
|
| 66 |
-
|
| 67 |
-
# Predict
|
| 68 |
-
with torch.no_grad():
|
| 69 |
-
pred = model(img_tensor)[0]
|
| 70 |
-
pred = (pred - pred.min()) / (pred.max() - pred.min() + 1e-8)
|
| 71 |
-
mask = (pred.cpu().numpy()[0] * 255).astype(np.uint8)
|
| 72 |
-
|
| 73 |
-
# Create outputs
|
| 74 |
-
mask_img = Image.fromarray(mask).convert("L")
|
| 75 |
-
transparent_img = img.copy()
|
| 76 |
-
transparent_img.putalpha(mask_img)
|
| 77 |
-
|
| 78 |
-
# Return as numpy arrays to avoid serialization issues
|
| 79 |
-
return (
|
| 80 |
-
np.array(transparent_img),
|
| 81 |
-
np.array(mask_img)
|
| 82 |
-
)
|
| 83 |
-
|
| 84 |
-
except Exception as e:
|
| 85 |
-
raise gr.Error(f"Error processing image: {str(e)}")
|
| 86 |
|
| 87 |
-
#
|
| 88 |
-
|
| 89 |
-
fn=
|
| 90 |
-
inputs=gr.Image(),
|
| 91 |
-
outputs=
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
],
|
| 95 |
-
title="Image Background Removal",
|
| 96 |
-
description="Upload an image to automatically remove the background",
|
| 97 |
-
examples=[["robot.png"], ["ship.png"]] if all(os.path.exists(f) for f in ["robot.png", "ship.png"]) else None
|
| 98 |
)
|
| 99 |
|
| 100 |
-
# Launch with minimal configuration
|
| 101 |
if __name__ == "__main__":
|
| 102 |
-
|
| 103 |
-
server_name="0.0.0.0",
|
| 104 |
-
server_port=7860
|
| 105 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
from PIL import Image
|
| 4 |
|
| 5 |
+
# Função para remover o background da imagem
|
| 6 |
+
def remove_background(image):
|
| 7 |
+
pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Obter a máscara da imagem
|
| 10 |
+
pillow_mask = pipe(image, return_mask=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# Aplicar máscara na imagem original
|
| 13 |
+
pillow_image = pipe(image)
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
return pillow_image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Criar uma interface Gradio
|
| 18 |
+
app = gr.Interface(
|
| 19 |
+
fn=remove_background,
|
| 20 |
+
inputs=gr.components.Image(type="pil"),
|
| 21 |
+
outputs=gr.components.Image(type="pil", format="png"), # Especificar saída como PNG
|
| 22 |
+
title="Remoção de Background de Imagens",
|
| 23 |
+
description="Envie uma imagem e veja o background sendo removido automaticamente. A imagem resultante será no formato PNG."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
)
|
| 25 |
|
|
|
|
| 26 |
if __name__ == "__main__":
|
| 27 |
+
app.launch(share=True)
|
|
|
|
|
|
|
|
|