EnginDev commited on
Commit
e370c30
·
verified ·
1 Parent(s): a738e6c

Create app.py

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