Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import cv2
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import os
|
| 7 |
+
import urllib.request
|
| 8 |
+
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
|
| 9 |
+
|
| 10 |
+
# Modell laden oder herunterladen
|
| 11 |
+
MODEL_URL = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"
|
| 12 |
+
MODEL_PATH = "sam_vit_b_01ec64.pth"
|
| 13 |
+
|
| 14 |
+
if not os.path.exists(MODEL_PATH):
|
| 15 |
+
print("Modell wird heruntergeladen...")
|
| 16 |
+
urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
|
| 17 |
+
print("Modell heruntergeladen.")
|
| 18 |
+
|
| 19 |
+
# Modelltyp
|
| 20 |
+
model_type = "vit_b"
|
| 21 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 22 |
+
sam = sam_model_registry[model_type](checkpoint=MODEL_PATH)
|
| 23 |
+
sam.to(device=device)
|
| 24 |
+
|
| 25 |
+
mask_generator = SamAutomaticMaskGenerator(sam)
|
| 26 |
+
|
| 27 |
+
def segment_all_objects(image):
|
| 28 |
+
image_np = np.array(image)
|
| 29 |
+
masks = mask_generator.generate(image_np)
|
| 30 |
+
overlay = image_np.copy()
|
| 31 |
+
|
| 32 |
+
for i, mask in enumerate(masks):
|
| 33 |
+
m = mask["segmentation"]
|
| 34 |
+
color = np.random.randint(0, 255, size=(3,))
|
| 35 |
+
overlay[m] = overlay[m] * 0.3 + color * 0.7
|
| 36 |
+
y, x = np.where(m)
|
| 37 |
+
if len(x) > 0 and len(y) > 0:
|
| 38 |
+
cx, cy = int(np.mean(x)), int(np.mean(y))
|
| 39 |
+
cv2.putText(overlay, f"Obj {i+1}", (cx, cy),
|
| 40 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
|
| 41 |
+
|
| 42 |
+
return Image.fromarray(overlay.astype(np.uint8))
|
| 43 |
+
|
| 44 |
+
demo = gr.Interface(
|
| 45 |
+
fn=segment_all_objects,
|
| 46 |
+
inputs=gr.Image(type="pil", label="Bild hochladen"),
|
| 47 |
+
outputs=gr.Image(type="pil", label="Segmentiertes Ergebnis"),
|
| 48 |
+
title="FishBoost SAM (Meta Original)",
|
| 49 |
+
description="Segmentiert automatisch alle Objekte im Bild mit Metas offiziellem SAM-Modell."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
demo.launch()
|