Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import SamModel, SamProcessor
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
# Kleineres Modell (läuft stabiler auf CPU)
|
| 7 |
+
model_id = "facebook/sam-vit-base"
|
| 8 |
+
processor = SamProcessor.from_pretrained(model_id)
|
| 9 |
+
model = SamModel.from_pretrained(model_id)
|
| 10 |
+
|
| 11 |
+
def segment_image(image):
|
| 12 |
+
# Sicherstellen, dass CPU verwendet wird
|
| 13 |
+
device = torch.device("cpu")
|
| 14 |
+
model.to(device)
|
| 15 |
+
inputs = processor(images=image, return_tensors="pt").to(device)
|
| 16 |
+
|
| 17 |
+
with torch.no_grad():
|
| 18 |
+
outputs = model(**inputs)
|
| 19 |
+
|
| 20 |
+
# Masken ausgeben
|
| 21 |
+
masks = processor.post_process_masks(
|
| 22 |
+
outputs,
|
| 23 |
+
original_sizes=[image.size[::-1]],
|
| 24 |
+
reshaped_input_sizes=[image.size[::-1]]
|
| 25 |
+
)[0]
|
| 26 |
+
|
| 27 |
+
mask_array = (masks[0][0].cpu().numpy() * 255).astype("uint8")
|
| 28 |
+
mask_image = Image.fromarray(mask_array)
|
| 29 |
+
return mask_image
|
| 30 |
+
|
| 31 |
+
demo = gr.Interface(
|
| 32 |
+
fn=segment_image,
|
| 33 |
+
inputs=gr.Image(type="pil"),
|
| 34 |
+
outputs=gr.Image(type="pil"),
|
| 35 |
+
title="FishBoost Segment Anything (Meta SAM 2 Demo)",
|
| 36 |
+
description="Upload an image and get the segmented result using Meta’s SAM model (CPU compatible)."
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
demo.launch()
|