Update app.py
Browse files
app.py
CHANGED
|
@@ -19,18 +19,15 @@ def load_model():
|
|
| 19 |
try:
|
| 20 |
from transformers import SamModel, SamProcessor
|
| 21 |
|
| 22 |
-
# UPGRADE: Large Model für bessere Qualität
|
| 23 |
-
|
| 24 |
-
model_name = "facebook/sam-vit-large" # ← BESSER!
|
| 25 |
|
| 26 |
processor = SamProcessor.from_pretrained(model_name)
|
| 27 |
model = SamModel.from_pretrained(model_name)
|
| 28 |
model.to(device)
|
| 29 |
print(f"✅ Model loaded: {model_name}")
|
| 30 |
except Exception as e:
|
| 31 |
-
print(f"❌
|
| 32 |
-
print("💡 Falling back to base model...")
|
| 33 |
-
# Fallback
|
| 34 |
model_name = "facebook/sam-vit-base"
|
| 35 |
processor = SamProcessor.from_pretrained(model_name)
|
| 36 |
model = SamModel.from_pretrained(model_name)
|
|
@@ -61,22 +58,14 @@ def refine_mask(mask, kernel_size=5):
|
|
| 61 |
"""Maske glätten und Löcher füllen"""
|
| 62 |
mask_uint8 = (mask > 0).astype(np.uint8) * 255
|
| 63 |
|
| 64 |
-
# Morphological Operations für glattere Kanten
|
| 65 |
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
|
| 66 |
-
|
| 67 |
-
# Closing: Löcher füllen
|
| 68 |
mask_closed = cv2.morphologyEx(mask_uint8, cv2.MORPH_CLOSE, kernel)
|
| 69 |
-
|
| 70 |
-
# Opening: Rauschen entfernen
|
| 71 |
mask_refined = cv2.morphologyEx(mask_closed, cv2.MORPH_OPEN, kernel)
|
| 72 |
|
| 73 |
return mask_refined > 0
|
| 74 |
|
| 75 |
def segment_automatic(image, quality="high"):
|
| 76 |
-
"""
|
| 77 |
-
Automatische Segmentierung mit Multi-Mask Output
|
| 78 |
-
quality: "high" (langsamer, präziser) oder "fast" (schneller, gröber)
|
| 79 |
-
"""
|
| 80 |
|
| 81 |
if image is None:
|
| 82 |
return None, {"error": "Kein Bild hochgeladen"}
|
|
@@ -90,7 +79,6 @@ def segment_automatic(image, quality="high"):
|
|
| 90 |
|
| 91 |
center_x, center_y = w // 2, h // 2
|
| 92 |
|
| 93 |
-
# WICHTIG: multimask_output=True für bessere Qualität!
|
| 94 |
inputs = processor(
|
| 95 |
image_pil,
|
| 96 |
input_points=[[[center_x, center_y]]],
|
|
@@ -100,9 +88,8 @@ def segment_automatic(image, quality="high"):
|
|
| 100 |
|
| 101 |
print("🧠 Running inference...")
|
| 102 |
with torch.no_grad():
|
| 103 |
-
outputs = model(**inputs, multimask_output=True)
|
| 104 |
|
| 105 |
-
# Post-process
|
| 106 |
masks = processor.image_processor.post_process_masks(
|
| 107 |
outputs.pred_masks.cpu(),
|
| 108 |
inputs["original_sizes"].cpu(),
|
|
@@ -115,7 +102,6 @@ def segment_automatic(image, quality="high"):
|
|
| 115 |
|
| 116 |
print(f"✅ Got {len(scores)} masks with scores: {scores}")
|
| 117 |
|
| 118 |
-
# Beste Maske
|
| 119 |
best_idx = np.argmax(scores)
|
| 120 |
best_score = scores[best_idx]
|
| 121 |
|
|
@@ -124,29 +110,24 @@ def segment_automatic(image, quality="high"):
|
|
| 124 |
else:
|
| 125 |
best_mask = masks[best_idx].numpy()
|
| 126 |
|
| 127 |
-
# REFINEMENT: Maske glätten
|
| 128 |
if quality == "high":
|
| 129 |
best_mask_refined = refine_mask(best_mask, kernel_size=7)
|
| 130 |
else:
|
| 131 |
best_mask_refined = best_mask > 0
|
| 132 |
|
| 133 |
-
# Overlay mit Anti-Aliasing
|
| 134 |
overlay = image_np.copy()
|
| 135 |
color = np.array([255, 50, 150])
|
| 136 |
|
| 137 |
-
# Weiche Kanten mit Gaussian Blur
|
| 138 |
mask_float = best_mask_refined.astype(float)
|
| 139 |
if quality == "high":
|
| 140 |
mask_float = cv2.GaussianBlur(mask_float, (5, 5), 0)
|
| 141 |
|
| 142 |
-
# Alpha Blending
|
| 143 |
for c in range(3):
|
| 144 |
overlay[:, :, c] = (
|
| 145 |
overlay[:, :, c] * (1 - mask_float * 0.6) +
|
| 146 |
color[c] * mask_float * 0.6
|
| 147 |
)
|
| 148 |
|
| 149 |
-
# Kontur zeichnen
|
| 150 |
contours, _ = cv2.findContours(
|
| 151 |
best_mask_refined.astype(np.uint8),
|
| 152 |
cv2.RETR_EXTERNAL,
|
|
@@ -175,11 +156,8 @@ def segment_automatic(image, quality="high"):
|
|
| 175 |
print(f"❌ ERROR:\n{traceback.format_exc()}")
|
| 176 |
return image, {"error": str(e)}
|
| 177 |
|
| 178 |
-
def segment_multi_dense(image, density="
|
| 179 |
-
"""
|
| 180 |
-
Multi-Object mit dichterem Grid
|
| 181 |
-
density: "high" (15x15), "medium" (9x9), "low" (5x5)
|
| 182 |
-
"""
|
| 183 |
|
| 184 |
if image is None:
|
| 185 |
return None, {"error": "Kein Bild"}
|
|
@@ -189,13 +167,12 @@ def segment_multi_dense(image, density="high"):
|
|
| 189 |
image_pil, image_np = prepare_image(image)
|
| 190 |
h, w = image_np.shape[:2]
|
| 191 |
|
| 192 |
-
# Dichteres Grid basierend auf Density
|
| 193 |
if density == "high":
|
| 194 |
-
grid_size = 5
|
| 195 |
elif density == "medium":
|
| 196 |
-
grid_size = 4
|
| 197 |
else:
|
| 198 |
-
grid_size = 3
|
| 199 |
|
| 200 |
points = []
|
| 201 |
for i in range(1, grid_size + 1):
|
|
@@ -234,17 +211,14 @@ def segment_multi_dense(image, density="high"):
|
|
| 234 |
else:
|
| 235 |
mask = masks[best_idx].numpy()
|
| 236 |
|
| 237 |
-
# Nur Masken mit gutem Score behalten
|
| 238 |
if scores[best_idx] > 0.7:
|
| 239 |
all_masks.append(refine_mask(mask))
|
| 240 |
all_scores.append(scores[best_idx])
|
| 241 |
|
| 242 |
print(f"✅ Got {len(all_masks)} quality masks")
|
| 243 |
|
| 244 |
-
# Masken kombinieren mit verschiedenen Farben
|
| 245 |
overlay = image_np.copy()
|
| 246 |
|
| 247 |
-
# HSV-basierte Farbgenerierung
|
| 248 |
colors = []
|
| 249 |
for i in range(len(all_masks)):
|
| 250 |
hue = int(180 * i / max(len(all_masks), 1))
|
|
@@ -252,15 +226,13 @@ def segment_multi_dense(image, density="high"):
|
|
| 252 |
color_rgb = cv2.cvtColor(color_hsv, cv2.COLOR_HSV2RGB)[0][0]
|
| 253 |
colors.append(color_rgb)
|
| 254 |
|
| 255 |
-
# Masken anwenden
|
| 256 |
for mask, color, score in zip(all_masks, colors, all_scores):
|
| 257 |
-
alpha = 0.4 + (score - 0.7) * 0.2
|
| 258 |
overlay[mask] = (
|
| 259 |
overlay[mask] * (1 - alpha) +
|
| 260 |
np.array(color) * alpha
|
| 261 |
).astype(np.uint8)
|
| 262 |
|
| 263 |
-
# Kontur
|
| 264 |
contours, _ = cv2.findContours(
|
| 265 |
mask.astype(np.uint8),
|
| 266 |
cv2.RETR_EXTERNAL,
|
|
@@ -289,34 +261,25 @@ def segment_multi_dense(image, density="high"):
|
|
| 289 |
# Gradio Interface
|
| 290 |
with gr.Blocks(title="SAM2 v2.0", theme=gr.themes.Soft()) as demo:
|
| 291 |
|
| 292 |
-
gr.Markdown(""
|
| 293 |
-
#
|
| 294 |
-
### Verbesserte Qualität mit Large Model & Multi-Mask Output
|
| 295 |
-
""")
|
| 296 |
|
| 297 |
with gr.Tab("🤖 Automatisch (Verbessert)"):
|
| 298 |
with gr.Row():
|
| 299 |
with gr.Column():
|
| 300 |
-
input_auto = gr.Image(type="pil", label="
|
| 301 |
quality_radio = gr.Radio(
|
| 302 |
choices=["high", "fast"],
|
| 303 |
value="high",
|
| 304 |
-
label="Qualität"
|
| 305 |
-
info="High = präziser aber langsamer"
|
| 306 |
)
|
| 307 |
-
btn_auto = gr.Button("
|
| 308 |
|
| 309 |
-
gr.Markdown(""
|
| 310 |
-
**Verbesserungen:**
|
| 311 |
-
- ✨ Large Model (bessere Details)
|
| 312 |
-
- 🎯 Multi-Mask Output
|
| 313 |
-
- 🔄 Kanten-Glättung
|
| 314 |
-
- 🌊 Weiche Übergänge
|
| 315 |
-
""")
|
| 316 |
|
| 317 |
with gr.Column():
|
| 318 |
-
output_auto = gr.Image(label="
|
| 319 |
-
json_auto = gr.JSON(label="
|
| 320 |
|
| 321 |
btn_auto.click(
|
| 322 |
fn=segment_automatic,
|
|
@@ -327,25 +290,19 @@ with gr.Blocks(title="SAM2 v2.0", theme=gr.themes.Soft()) as demo:
|
|
| 327 |
with gr.Tab("🎯 Multi-Region (Dicht)"):
|
| 328 |
with gr.Row():
|
| 329 |
with gr.Column():
|
| 330 |
-
input_multi = gr.Image(type="pil", label="
|
| 331 |
density_radio = gr.Radio(
|
| 332 |
choices=["high", "medium", "low"],
|
| 333 |
value="medium",
|
| 334 |
-
label="Punkt-Dichte"
|
| 335 |
-
info="High = mehr Details, aber langsamer"
|
| 336 |
)
|
| 337 |
-
btn_multi = gr.Button("
|
| 338 |
|
| 339 |
-
gr.Markdown(""
|
| 340 |
-
**Grid-Größen:**
|
| 341 |
-
- High: 5x5 = 25 Punkte (für Details wie Flossen!)
|
| 342 |
-
- Medium: 4x4 = 16 Punkte
|
| 343 |
-
- Low: 3x3 = 9 Punkte
|
| 344 |
-
""")
|
| 345 |
|
| 346 |
with gr.Column():
|
| 347 |
-
output_multi = gr.Image(label="
|
| 348 |
-
json_multi = gr.JSON(label="
|
| 349 |
|
| 350 |
btn_multi.click(
|
| 351 |
fn=segment_multi_dense,
|
|
@@ -353,16 +310,10 @@ with gr.Blocks(title="SAM2 v2.0", theme=gr.themes.Soft()) as demo:
|
|
| 353 |
outputs=[output_multi, json_multi]
|
| 354 |
)
|
| 355 |
|
| 356 |
-
gr.
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
- 🖼️ Kontrast zwischen Objekt & Hintergrund
|
| 364 |
-
- 📏 Nicht zu klein im Bild
|
| 365 |
-
|
| 366 |
-
**Bei fehlenden Details (z.B. Flosse):**
|
| 367 |
-
- Nutze "Multi-Region" mit "High" Density
|
| 368 |
-
- Oder
|
|
|
|
| 19 |
try:
|
| 20 |
from transformers import SamModel, SamProcessor
|
| 21 |
|
| 22 |
+
# UPGRADE: Large Model für bessere Qualität
|
| 23 |
+
model_name = "facebook/sam-vit-large"
|
|
|
|
| 24 |
|
| 25 |
processor = SamProcessor.from_pretrained(model_name)
|
| 26 |
model = SamModel.from_pretrained(model_name)
|
| 27 |
model.to(device)
|
| 28 |
print(f"✅ Model loaded: {model_name}")
|
| 29 |
except Exception as e:
|
| 30 |
+
print(f"❌ Error: {e}, falling back to base model")
|
|
|
|
|
|
|
| 31 |
model_name = "facebook/sam-vit-base"
|
| 32 |
processor = SamProcessor.from_pretrained(model_name)
|
| 33 |
model = SamModel.from_pretrained(model_name)
|
|
|
|
| 58 |
"""Maske glätten und Löcher füllen"""
|
| 59 |
mask_uint8 = (mask > 0).astype(np.uint8) * 255
|
| 60 |
|
|
|
|
| 61 |
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
|
|
|
|
|
|
|
| 62 |
mask_closed = cv2.morphologyEx(mask_uint8, cv2.MORPH_CLOSE, kernel)
|
|
|
|
|
|
|
| 63 |
mask_refined = cv2.morphologyEx(mask_closed, cv2.MORPH_OPEN, kernel)
|
| 64 |
|
| 65 |
return mask_refined > 0
|
| 66 |
|
| 67 |
def segment_automatic(image, quality="high"):
|
| 68 |
+
"""Automatische Segmentierung mit Multi-Mask Output"""
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
if image is None:
|
| 71 |
return None, {"error": "Kein Bild hochgeladen"}
|
|
|
|
| 79 |
|
| 80 |
center_x, center_y = w // 2, h // 2
|
| 81 |
|
|
|
|
| 82 |
inputs = processor(
|
| 83 |
image_pil,
|
| 84 |
input_points=[[[center_x, center_y]]],
|
|
|
|
| 88 |
|
| 89 |
print("🧠 Running inference...")
|
| 90 |
with torch.no_grad():
|
| 91 |
+
outputs = model(**inputs, multimask_output=True)
|
| 92 |
|
|
|
|
| 93 |
masks = processor.image_processor.post_process_masks(
|
| 94 |
outputs.pred_masks.cpu(),
|
| 95 |
inputs["original_sizes"].cpu(),
|
|
|
|
| 102 |
|
| 103 |
print(f"✅ Got {len(scores)} masks with scores: {scores}")
|
| 104 |
|
|
|
|
| 105 |
best_idx = np.argmax(scores)
|
| 106 |
best_score = scores[best_idx]
|
| 107 |
|
|
|
|
| 110 |
else:
|
| 111 |
best_mask = masks[best_idx].numpy()
|
| 112 |
|
|
|
|
| 113 |
if quality == "high":
|
| 114 |
best_mask_refined = refine_mask(best_mask, kernel_size=7)
|
| 115 |
else:
|
| 116 |
best_mask_refined = best_mask > 0
|
| 117 |
|
|
|
|
| 118 |
overlay = image_np.copy()
|
| 119 |
color = np.array([255, 50, 150])
|
| 120 |
|
|
|
|
| 121 |
mask_float = best_mask_refined.astype(float)
|
| 122 |
if quality == "high":
|
| 123 |
mask_float = cv2.GaussianBlur(mask_float, (5, 5), 0)
|
| 124 |
|
|
|
|
| 125 |
for c in range(3):
|
| 126 |
overlay[:, :, c] = (
|
| 127 |
overlay[:, :, c] * (1 - mask_float * 0.6) +
|
| 128 |
color[c] * mask_float * 0.6
|
| 129 |
)
|
| 130 |
|
|
|
|
| 131 |
contours, _ = cv2.findContours(
|
| 132 |
best_mask_refined.astype(np.uint8),
|
| 133 |
cv2.RETR_EXTERNAL,
|
|
|
|
| 156 |
print(f"❌ ERROR:\n{traceback.format_exc()}")
|
| 157 |
return image, {"error": str(e)}
|
| 158 |
|
| 159 |
+
def segment_multi_dense(image, density="medium"):
|
| 160 |
+
"""Multi-Object mit dichterem Grid"""
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
if image is None:
|
| 163 |
return None, {"error": "Kein Bild"}
|
|
|
|
| 167 |
image_pil, image_np = prepare_image(image)
|
| 168 |
h, w = image_np.shape[:2]
|
| 169 |
|
|
|
|
| 170 |
if density == "high":
|
| 171 |
+
grid_size = 5
|
| 172 |
elif density == "medium":
|
| 173 |
+
grid_size = 4
|
| 174 |
else:
|
| 175 |
+
grid_size = 3
|
| 176 |
|
| 177 |
points = []
|
| 178 |
for i in range(1, grid_size + 1):
|
|
|
|
| 211 |
else:
|
| 212 |
mask = masks[best_idx].numpy()
|
| 213 |
|
|
|
|
| 214 |
if scores[best_idx] > 0.7:
|
| 215 |
all_masks.append(refine_mask(mask))
|
| 216 |
all_scores.append(scores[best_idx])
|
| 217 |
|
| 218 |
print(f"✅ Got {len(all_masks)} quality masks")
|
| 219 |
|
|
|
|
| 220 |
overlay = image_np.copy()
|
| 221 |
|
|
|
|
| 222 |
colors = []
|
| 223 |
for i in range(len(all_masks)):
|
| 224 |
hue = int(180 * i / max(len(all_masks), 1))
|
|
|
|
| 226 |
color_rgb = cv2.cvtColor(color_hsv, cv2.COLOR_HSV2RGB)[0][0]
|
| 227 |
colors.append(color_rgb)
|
| 228 |
|
|
|
|
| 229 |
for mask, color, score in zip(all_masks, colors, all_scores):
|
| 230 |
+
alpha = 0.4 + (score - 0.7) * 0.2
|
| 231 |
overlay[mask] = (
|
| 232 |
overlay[mask] * (1 - alpha) +
|
| 233 |
np.array(color) * alpha
|
| 234 |
).astype(np.uint8)
|
| 235 |
|
|
|
|
| 236 |
contours, _ = cv2.findContours(
|
| 237 |
mask.astype(np.uint8),
|
| 238 |
cv2.RETR_EXTERNAL,
|
|
|
|
| 261 |
# Gradio Interface
|
| 262 |
with gr.Blocks(title="SAM2 v2.0", theme=gr.themes.Soft()) as demo:
|
| 263 |
|
| 264 |
+
gr.Markdown("# 🎨 SAM2 Segmentierung v2.0")
|
| 265 |
+
gr.Markdown("### Verbesserte Qualität mit Large Model & Multi-Mask Output")
|
|
|
|
|
|
|
| 266 |
|
| 267 |
with gr.Tab("🤖 Automatisch (Verbessert)"):
|
| 268 |
with gr.Row():
|
| 269 |
with gr.Column():
|
| 270 |
+
input_auto = gr.Image(type="pil", label="Bild hochladen")
|
| 271 |
quality_radio = gr.Radio(
|
| 272 |
choices=["high", "fast"],
|
| 273 |
value="high",
|
| 274 |
+
label="Qualität"
|
|
|
|
| 275 |
)
|
| 276 |
+
btn_auto = gr.Button("Segmentieren", variant="primary", size="lg")
|
| 277 |
|
| 278 |
+
gr.Markdown("**Verbesserungen:** Large Model, Multi-Mask, Kanten-Glättung")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
with gr.Column():
|
| 281 |
+
output_auto = gr.Image(label="Ergebnis")
|
| 282 |
+
json_auto = gr.JSON(label="Details")
|
| 283 |
|
| 284 |
btn_auto.click(
|
| 285 |
fn=segment_automatic,
|
|
|
|
| 290 |
with gr.Tab("🎯 Multi-Region (Dicht)"):
|
| 291 |
with gr.Row():
|
| 292 |
with gr.Column():
|
| 293 |
+
input_multi = gr.Image(type="pil", label="Bild hochladen")
|
| 294 |
density_radio = gr.Radio(
|
| 295 |
choices=["high", "medium", "low"],
|
| 296 |
value="medium",
|
| 297 |
+
label="Punkt-Dichte"
|
|
|
|
| 298 |
)
|
| 299 |
+
btn_multi = gr.Button("Alle Bereiche", variant="primary", size="lg")
|
| 300 |
|
| 301 |
+
gr.Markdown("**Grid:** High=5x5, Medium=4x4, Low=3x3")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
with gr.Column():
|
| 304 |
+
output_multi = gr.Image(label="Ergebnis")
|
| 305 |
+
json_multi = gr.JSON(label="Details")
|
| 306 |
|
| 307 |
btn_multi.click(
|
| 308 |
fn=segment_multi_dense,
|
|
|
|
| 310 |
outputs=[output_multi, json_multi]
|
| 311 |
)
|
| 312 |
|
| 313 |
+
with gr.Tab("📡 API Info"):
|
| 314 |
+
api_doc = """
|
| 315 |
+
### API Endpoint
|
| 316 |
+
|
| 317 |
+
**URL:** https://dein-space.hf.space/api/predict
|
| 318 |
+
|
| 319 |
+
**JavaScript Beispiel:**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|