Astridkraft commited on
Commit
aa82308
·
verified ·
1 Parent(s): 47b01fe

Create sam_module.py

Browse files
Files changed (1) hide show
  1. sam_module.py +1016 -0
sam_module.py ADDED
@@ -0,0 +1,1016 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def create_sam_mask(self, image, bbox_coords, mode):
2
+ """
3
+ ERWEITERTE Funktion: Erstellt präzise Maske mit SAM 2
4
+ """
5
+ try:
6
+ print("#" * 80)
7
+ print("# 🎯 STARTE SAM 2 SEGMENTIERUNG")
8
+ print("#" * 80)
9
+ print(f"📐 Eingabebild-Größe: {image.size}")
10
+ print(f"🎛️ Ausgewählter Modus: {mode}")
11
+
12
+ # ============================================================
13
+ # VORBEREITUNG FÜR ALLE MODI
14
+ # ============================================================
15
+ original_image = image
16
+
17
+ # 1. SAM2 laden
18
+ if not self.sam_initialized:
19
+ print("📥 SAM 2 ist noch nicht geladen, starte Lazy Loading...")
20
+ self._lazy_load_sam()
21
+
22
+ if self.sam_model is None or self.sam_processor is None:
23
+ print("⚠️ SAM 2 Model nicht verfügbar, verwende Fallback")
24
+ return self._create_rectangular_mask(image, bbox_coords, mode)
25
+
26
+ # 2. Validiere BBox
27
+ x1, y1, x2, y2 = self._validate_bbox(image, bbox_coords)
28
+ original_bbox = (x1, y1, x2, y2)
29
+ print(f"📏 Original-BBox Größe: {x2-x1} × {y2-y1} px")
30
+
31
+ # ============================================================
32
+ # BLOCK 1: ENVIRONMENT_CHANGE
33
+ # ============================================================
34
+ if mode == "environment_change":
35
+ print("-" * 60)
36
+ print("🌳 MODUS: ENVIRONMENT_CHANGE")
37
+ print("-" * 60)
38
+
39
+ # Der Prozessor von SAM erwartet ein NumPy-Array kein PIL
40
+ image_np = np.array(image.convert("RGB"))
41
+
42
+ # Packt die BBox-Koordinaten in eine 3D-Liste
43
+ input_boxes = [[[x1, y1, x2, y2]]]
44
+
45
+ # Aufruf des SAM-Prozessors mit Originalbild in Form NumPy-Array und BBox.Der Processor verarbeitet Bild und BBox
46
+ # in die für SAM erforderlichen Tensoren und speichert sie in inputs.
47
+ inputs = self.sam_processor(
48
+ image_np,
49
+ input_boxes=input_boxes,
50
+ return_tensors="pt"
51
+ ).to(self.device) # Ohne .to(self.device) werden die Tensoren standardmäßig im CPU-RAM erzeugt und gespeichert! Da GPU-Fehler!
52
+
53
+ print(f" - 'input_boxes' Shape: {inputs['input_boxes'].shape}")
54
+
55
+ # SAM2 Vorhersage
56
+ print("-" * 60)
57
+ print("🧠 SAM 2 INFERENZ (Vorhersage)")
58
+ with torch.no_grad():
59
+ print(" Führe Vorhersage durch...")
60
+ outputs = self.sam_model(**inputs) #führt die Segmentierung mit SAM aus
61
+ print(f"✅ Vorhersage abgeschlossen")
62
+ print(f" Anzahl der Vorhersagemasken: {outputs.pred_masks.shape[2]}")
63
+
64
+ num_masks = outputs.pred_masks.shape[2]
65
+ print(f" SAM lieferte {num_masks} verschiedene Masken")
66
+
67
+ # Sammlung aller Masken in all_masks
68
+ all_masks = []
69
+
70
+ for i in range(num_masks):
71
+ single_mask = outputs.pred_masks[:, :, i, :, :]
72
+ resized_mask = F.interpolate(
73
+ single_mask,
74
+ size=(image.height, image.width),
75
+ mode='bilinear',
76
+ align_corners=False
77
+ ).squeeze()
78
+
79
+ mask_np = resized_mask.sigmoid().cpu().numpy() #wandelt Modellausgaben in Wahrscheinlichkeiten und bewegt Daten von GPU nach CPU
80
+ all_masks.append(mask_np) #fügt die aktuelle Maske der Liste all_masks hinzu
81
+
82
+
83
+ bbox_center = ((x1 + x2) // 2, (y1 + y2) // 2)
84
+ bbox_area = (x2 - x1) * (y2 - y1)
85
+ print(f" Erwartetes BBox-Zentrum: {bbox_center}")
86
+ print(f" Erwartete BBox-Fläche: {bbox_area:,} Pixel")
87
+
88
+ print("🤔 HEURISTIK: Beste Maske auswählen")
89
+ best_mask_idx = 0
90
+ best_score = -1
91
+
92
+ # Alle 3 Masken analysieren (OHNE sie alle zu skalieren!)
93
+ for i in range(num_masks):
94
+ mask_np_temp = all_masks[i] #verwende Maske auf Original-Bildgröße
95
+
96
+ # Adaptive Vor-Filterung (prüft ob Maske überhaupt gültig ist)
97
+ mask_max = mask_np_temp.max()
98
+ if mask_max < 0.3:
99
+ continue # Maske überspringen
100
+
101
+ adaptive_threshold = max(0.3, mask_max * 0.7)
102
+ mask_binary = (mask_np_temp > adaptive_threshold).astype(np.uint8)
103
+
104
+ # wenn nur schwarze Pixel (keine Segmentierung) nimm die nächste Maske
105
+ if np.sum(mask_binary) == 0:
106
+ print(f" ❌ Maske {i+1}: Keine Pixel nach adaptive_threshold {adaptive_threshold:.3f}")
107
+ continue
108
+
109
+ # Heuristik-Berechnung
110
+ mask_area_pixels = np.sum(mask_binary)
111
+
112
+ #Berechnung von Überlappung SAM-Maske und ursprünglicher BBox
113
+ bbox_mask = np.zeros((image.height, image.width), dtype=np.uint8)
114
+ bbox_mask[y1:y2, x1:x2] = 1
115
+
116
+ overlap = np.sum(mask_binary & bbox_mask)
117
+ bbox_overlap_ratio = overlap / np.sum(bbox_mask) if np.sum(bbox_mask) > 0 else 0
118
+
119
+ # Schwerpunkt berechnen
120
+ y_coords, x_coords = np.where(mask_binary > 0)
121
+ if len(y_coords) > 0:
122
+ centroid_y = np.mean(y_coords)
123
+ centroid_x = np.mean(x_coords)
124
+ centroid_distance = np.sqrt((centroid_x - bbox_center[0])**2 + (centroid_y - bbox_center[1])**2)
125
+ normalized_distance = centroid_distance / max(image.width, image.height)
126
+ else:
127
+ normalized_distance = 1.0
128
+
129
+ # Flächen-Ratio
130
+ area_ratio = mask_area_pixels / bbox_area
131
+ area_score = 1.0 - min(abs(area_ratio - 1.0), 1.0)
132
+
133
+ # Konfidenz
134
+ confidence_score = mask_max
135
+
136
+ # Standard-Score
137
+ score = (
138
+ bbox_overlap_ratio * 0.4 +
139
+ (1.0 - normalized_distance) * 0.25 +
140
+ area_score * 0.25 +
141
+ confidence_score * 0.1
142
+ )
143
+
144
+ print(f" 📊 STANDARD-SCORES für Maske {i+1}:")
145
+ print(f" • BBox-Überlappung: {bbox_overlap_ratio:.3f}")
146
+ print(f" • Zentrums-Distanz: {centroid_distance if 'centroid_distance' in locals() else 'N/A'}")
147
+ print(f" • Flächen-Ratio: {area_ratio:.3f}")
148
+ print(f" • GESAMTSCORE: {score:.3f}")
149
+
150
+ if score > best_score:
151
+ best_score = score
152
+ best_mask_idx = i
153
+ print(f" 🏆 Neue beste Maske: Nr. {i+1} mit Score {score:.3f}")
154
+
155
+ print(f"✅ Beste Maske ausgewählt: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")
156
+
157
+ # Beste Maske verwenden - mask_np beste Maske
158
+ mask_np = all_masks[best_mask_idx]
159
+
160
+ max_val = mask_np.max()
161
+ print(f" 🔍 Maximaler SAM-Konfidenzwert der besten Maske: {max_val:.3f}")
162
+
163
+ if max_val < 0.6:
164
+ dynamic_threshold = 0.3
165
+ print(f" ⚠️ SAM ist unsicher (max_val={max_val:.3f} < 0.6)")
166
+ else:
167
+ dynamic_threshold = max_val * 0.8
168
+ print(f" ✅ SAM ist sicher (max_val={max_val:.3f} >= 0.6)")
169
+
170
+ # Binärmaske erstellen (256x256)
171
+ mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255
172
+
173
+ # Fallback bei leerer Maske, der höchste Wert ist 0 also schwarz
174
+ if mask_array.max() == 0:
175
+ print(" ⚠️ Maske leer, erstelle rechteckige Fallback-Maske")
176
+ mask_array = np.zeros((512, 512), dtype=np.uint8) * 255 # weiße 512x512-Maske
177
+
178
+ # Skaliere BBox auf 512x512
179
+ scale_x = 512 / image.width
180
+ scale_y = 512 / image.height
181
+ fb_x1 = int(x1 * scale_x)
182
+ fb_y1 = int(y1 * scale_y)
183
+ fb_x2 = int(x2 * scale_x)
184
+ fb_y2 = int(y2 * scale_y)
185
+
186
+ # Schwarzes Rechteck für Person bzw. BBox
187
+ cv2.rectangle(mask_array, (fb_x1, fb_y1), (fb_x2, fb_y2), 0, -1)
188
+
189
+ # Damit wird die Rohmaske für die UI-Anzeige gespeichert
190
+ raw_mask_array = mask_array.copy()
191
+
192
+ print("🌳 ENVIRONMENT-CHANGE POSTPROCESSING")
193
+
194
+ # Konvertierung zu PIL, hochskalieren auf Originalgröße (korrekte Überlagerung mit O-Bild),
195
+ # Konvertierung NumPy für weitere Verarbeitung da mathematisch korrekter als PIL.
196
+ if image.size != original_image.size:
197
+ print(f" ⚠️ Bildgröße angepasst: {image.size} → {original_image.size}")
198
+ temp_mask = Image.fromarray(mask_array).convert("L")
199
+ temp_mask = temp_mask.resize(original_image.size, Image.Resampling.NEAREST)
200
+ mask_array = np.array(temp_mask)
201
+ print(f" ✅ Maske auf Originalgröße skaliert: {mask_array.shape}")
202
+
203
+ # Maske invertieren (Person wird schwarz, Hintergrund weiß)
204
+ mask_array = 255 - mask_array
205
+ print(" ✅ Maske invertiert (Person schwarz, Hintergrund weiß)")
206
+
207
+ # Weiße Punkte in der Person (schwarz) entfernen
208
+ print("🧹 Entferne weiße Punkte in der Person...")
209
+ kernel_open = np.ones((3, 3), np.uint8)
210
+ mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_OPEN, kernel_open, iterations=3)
211
+ print(" ✅ MORPH_OPEN entfernt weiße Punkte in der Person")
212
+
213
+ # DEBUG nach MORPH_OPEN
214
+ print(f" Nach MORPH_OPEN - Weiße Pixel: {np.sum(mask_array > 127)}")
215
+
216
+ # Morphologische Operationen für saubere Umgebung - entfernt schwarze Pixel aus Umgebung
217
+ print("🔧 Verbessere Umgebungsmaske...")
218
+ kernel_close = np.ones((5, 5), np.uint8)
219
+ mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_CLOSE, kernel_close)
220
+ print(" ✅ MORPH_CLOSE für zusammenhängende Umgebung")
221
+
222
+ # DEBUG nach MORPH_CLOSE
223
+ print(f" Nach MORPH_CLOSE - Weiße Pixel: {np.sum(mask_array > 127)}")
224
+
225
+ # Weiche Ränder für bessere Integration der Person
226
+ print("🌈 Erstelle weiche Übergänge...")
227
+ mask_array = cv2.GaussianBlur(mask_array, (9, 9), 2.0) #2.0 bestimmt wie stark die Unschärfe ist
228
+ print(" ✅ Gaussian Blur für weiche Übergänge")
229
+
230
+ # DEBUG nach Gaussian Blur
231
+ print(f" Nach Gaussian Blur - Min/Max: {mask_array.min()}/{mask_array.max()}")
232
+ print(f" Nach Gaussian Blur - dtype: {mask_array.dtype}")
233
+
234
+ # Gamma-Korrektur für präzisere Ränder
235
+ print("🎛️ Wende Gamma-Korrektur an...")
236
+ mask_array = mask_array.astype(np.float32) / 255.0
237
+ print(f" Konvertiert zu Float32: Min={mask_array.min():.3f}, Max={mask_array.max():.3f}")
238
+
239
+ mask_array = np.clip(mask_array, 0.0, 1.0) #begrenzt alle Werte auf 0 und 1
240
+ mask_array = mask_array ** 0.85 # Gamma-Korrektur Werte > 0.5 werden abgedunkelt, <0.5 aufgehellt-erzeugt natürliche Maskenübergänge
241
+ print(f" Nach Gamma 0.85: Min={mask_array.min():.3f}, Max={mask_array.max():.3f}")
242
+
243
+ mask_array = (mask_array * 255).astype(np.uint8)
244
+ print(" ✅ Gamma-Korrektur (0.85) gegen milchige Ränder")
245
+
246
+ # FINALE QUALITÄTSKONTROLLE
247
+ print("-" * 60)
248
+ print("📊 FINALE MASKEN-STATISTIK (ENVIRONMENT_CHANGE)")
249
+
250
+ white_pixels = np.sum(mask_array > 127)
251
+ black_pixels = np.sum(mask_array <= 127)
252
+ total_pixels = mask_array.size
253
+
254
+ white_ratio = white_pixels / total_pixels * 100
255
+ black_ratio = black_pixels / total_pixels * 100
256
+
257
+ print(f" Weiße Pixel (HINTERGRUND - Veränderung): {white_pixels:,} ({white_ratio:.1f}%)")
258
+ print(f" Schwarze Pixel (PERSON - Erhaltung): {black_pixels:,} ({black_ratio:.1f}%)")
259
+ print(f" Gesamtpixel: {total_pixels:,}")
260
+
261
+ # Warnungen basierend auf Verhältnis
262
+ if white_ratio < 30:
263
+ print(f" ⚠️ WARNUNG: Sehr wenig Hintergrund ({white_ratio:.1f}%)")
264
+ print(f" ℹ️ Das könnte bedeuten, dass die Person zu groß segmentiert wurde")
265
+ elif white_ratio > 90:
266
+ print(f" ⚠️ WARNUNG: Sehr viel Hintergrund ({white_ratio:.1f}%)")
267
+ print(f" ℹ️ Das könnte bedeuten, dass die Person zu klein segmentiert wurde")
268
+ elif 50 <= white_ratio <= 80:
269
+ print(f" ✅ OPTIMALES Verhältnis ({white_ratio:.1f}%)")
270
+ else:
271
+ print(f" ℹ️ Normales Verhältnis ({white_ratio:.1f}%)")
272
+
273
+ # Zurück zu PIL Image
274
+ mask = Image.fromarray(mask_array).convert("L")
275
+ raw_mask = Image.fromarray(raw_mask_array).convert("L")
276
+
277
+ print("#" * 80)
278
+ print(f"✅ SAM 2 SEGMENTIERUNG ABGESCHLOSSEN")
279
+ print(f"📐 Finale Maskengröße: {mask.size}")
280
+ print(f"🎛️ Verwendeter Modus: {mode}")
281
+ print("#" * 80)
282
+
283
+ return mask, raw_mask # in mask steht die invertierte nachbearbeitete Maske, in raw_mask die Rohmaske
284
+
285
+ # ============================================================
286
+ # BLOCK 2: FOCUS_CHANGE
287
+ # ============================================================
288
+ elif mode == "focus_change":
289
+ print("-" * 60)
290
+ print("🎯 MODUS: FOCUS_CHANGE (OPTIMIERT)")
291
+ print("-" * 60)
292
+
293
+ # Konvertierung O-Bild in NumPy-Array für SAM
294
+ image_np = np.array(image.convert("RGB"))
295
+
296
+ # Packt die BBox-Koordinaten in eine 3D-Liste
297
+ input_boxes = [[[x1, y1, x2, y2]]]
298
+
299
+ # Nur Mittelpunkt als positiver Prompt
300
+ center_x = (x1 + x2) // 2
301
+ center_y = (y1 + y2) // 2
302
+ input_points = [[[[center_x, center_y]]]] # NUR EIN PUNKT in 4D-Liste
303
+ input_labels = [[[1]]] # Markiert Punkt als Positiver Prompt also der Bereich muß segmentiert werden
304
+
305
+ print(f" 🎯 SAM-Prompt: BBox [{x1},{y1},{x2},{y2}]")
306
+ print(f" 👁️ Punkt: Nur Mitte ({center_x},{center_y})")
307
+
308
+ # SAM Inputs vorbereiten
309
+ inputs = self.sam_processor(
310
+ image_np,
311
+ input_boxes=input_boxes,
312
+ input_points=input_points,
313
+ input_labels=input_labels,
314
+ return_tensors="pt"
315
+ ).to(self.device)
316
+
317
+ # SAM Vorhersage (alle 3 Masken)
318
+ print("🧠 SAM 2 INFERENZ (3 Masken-Varianten)")
319
+ with torch.no_grad():
320
+ print(" Führe Vorhersage durch...")
321
+ outputs = self.sam_model(**inputs)
322
+ print(f"✅ Vorhersage abgeschlossen")
323
+ print(f" Anzahl der Vorhersagemasken: {outputs.pred_masks.shape[2]}")
324
+
325
+ num_masks = outputs.pred_masks.shape[2]
326
+
327
+
328
+ # Sammlung aller Masken in all_masks
329
+ all_masks = []
330
+
331
+ for i in range(num_masks):
332
+ single_mask = outputs.pred_masks[:, :, i, :, :]
333
+ resized_mask = F.interpolate(
334
+ single_mask,
335
+ size=(image.height, image.width),
336
+ mode='bilinear',
337
+ align_corners=False
338
+ ).squeeze()
339
+
340
+ mask_np = resized_mask.sigmoid().cpu().numpy()
341
+ all_masks.append(mask_np) #fügt die aktuelle Maske der Liste all_masks hinzu
342
+
343
+
344
+ # BBox-Information für Heuristik
345
+ bbox_center = ((x1 + x2) // 2, (y1 + y2) // 2)
346
+ bbox_area = (x2 - x1) * (y2 - y1)
347
+
348
+ print("🤔 HEURISTIK: Beste Maske auswählen")
349
+ best_mask_idx = 0
350
+ best_score = -1
351
+
352
+ # Alle 3 Masken analysieren
353
+ for i in range(num_masks):
354
+ # Maske in Original-Bildgröße -vorher interpolate- analysieren
355
+
356
+ mask_np_temp = all_masks[i]
357
+
358
+ # Adaptive Vor-Filterung (prüft ob Maske überhaupt gültig ist)
359
+ mask_max = mask_np_temp.max()
360
+ if mask_max < 0.3:
361
+ continue # Maske überspringen
362
+
363
+ adaptive_threshold = max(0.3, mask_max * 0.7)
364
+ mask_binary = (mask_np_temp > adaptive_threshold).astype(np.uint8)
365
+
366
+ # wenn nur schwarze Pixel (keine Segmentierung) nimm die nächste Maske
367
+ if np.sum(mask_binary) == 0:
368
+ continue
369
+
370
+ # Heuristik-Berechnung
371
+ mask_area_pixels = np.sum(mask_binary) # zählt alle weißen Pixel in der Binärmaske
372
+
373
+ # Berechnet wie gut die SAM-Maske mit der ursprünglichen BBox überlappt
374
+ bbox_mask = np.zeros((image.height, image.width), dtype=np.uint8)
375
+ bbox_mask[y1:y2, x1:x2] = 1
376
+ overlap = np.sum(mask_binary & bbox_mask)
377
+ bbox_overlap_ratio = overlap / np.sum(bbox_mask) if np.sum(bbox_mask) > 0 else 0
378
+
379
+ # Schwerpunkt
380
+ y_coords, x_coords = np.where(mask_binary > 0)
381
+ if len(y_coords) > 0:
382
+ centroid_y = np.mean(y_coords)
383
+ centroid_x = np.mean(x_coords)
384
+ centroid_distance = np.sqrt((centroid_x - bbox_center[0])**2 +
385
+ (centroid_y - bbox_center[1])**2)
386
+ normalized_distance = centroid_distance / max(image.width, image.height)
387
+ else:
388
+ normalized_distance = 1.0
389
+
390
+ # Flächen-Ratio
391
+ area_ratio = mask_area_pixels / bbox_area
392
+ area_score = 1.0 - min(abs(area_ratio - 1.0), 1.0)
393
+
394
+ # FOCUS_CHANGE spezifischer Score
395
+ score = (
396
+ bbox_overlap_ratio * 0.4 + # 40% BBox-Überlappung
397
+ (1.0 - normalized_distance) * 0.25 + # 25% Zentrumsnähe
398
+ area_score * 0.25 + # 25% Flächenpassung
399
+ mask_max * 0.1 # 10% SAM-Konfidenz
400
+ )
401
+
402
+ print(f" Maske {i+1}: Score={score:.3f}, "
403
+ f"Überlappung={bbox_overlap_ratio:.3f}, "
404
+ f"Fläche={mask_area_pixels:,}px")
405
+
406
+ if score > best_score:
407
+ best_score = score
408
+ best_mask_idx = i
409
+
410
+ print(f"✅ Beste Maske: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")
411
+
412
+ # NUR DIE BESTE MASKE AUF 512x512 HERUNTERSKALIEREN -Für Inpaint
413
+ best_mask_256 = outputs.pred_masks[:, :, best_mask_idx, :, :]
414
+ resized_mask = F.interpolate(
415
+ best_mask_256,
416
+ size=(512, 512), # DIREKT AUF CONTROLNET-ZIELGRÖßE
417
+ mode='bilinear',
418
+ align_corners=False
419
+ ).squeeze()
420
+
421
+ mask_np = resized_mask.cpu().numpy()
422
+ print(f" 🔄 Beste Maske skaliert auf 512×512 für ControlNet")
423
+
424
+ # ============================================================
425
+ # DYNAMISCHER THRESHOLD
426
+ # SAM gibt nur Wahrscheinlichkeiten aus!
427
+ # Nachdem das Modell eine Maske für eine Person vorhersagt (wo jeder Pixel einen Wert zwischen 0 und 1 hat,
428
+ # wie "wahrscheinlich gehört dieser Pixel zur Person"), wird diese Maske binarisiert (0 oder 1), indem alle
429
+ # Pixel unter 0.05 auf 0 gesetzt werden, alle darüber auf 1.
430
+ # ============================================================
431
+ mask_max = mask_np.max() #höchster Wahrscheinlichkeitswert in SAM-Maske
432
+ if best_score < 0.7: # Schlechte Maskenqualität
433
+ dynamic_threshold = 0.05 # SEHR NIEDRIG für maximale Abdeckung
434
+ print(f" ⚠️ Masken-Score niedrig ({best_score:.3f}). "
435
+ f"Threshold=0.05 für maximale Abdeckung")
436
+ else:
437
+ dynamic_threshold = max(0.15, mask_max * 0.3) # Moderater Threshold
438
+ print(f" ✅ Gute Maske. Threshold={dynamic_threshold:.3f}")
439
+
440
+ # Binärmaske erstellen (512x512)
441
+ mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255
442
+
443
+ # Fallback bei leerer Maske, der höchste Wert ist 0 also schwarz
444
+ if mask_array.max() == 0:
445
+ print(" ⚠️ Maske leer, erstelle rechteckige Fallback-Maske")
446
+ mask_array = np.zeros((512, 512), dtype=np.uint8)
447
+ # BBox auf 512x512 skalieren für Fallback
448
+ scale_x = 512 / image.width
449
+ scale_y = 512 / image.height
450
+ fb_x1 = int(x1 * scale_x)
451
+ fb_y1 = int(y1 * scale_y)
452
+ fb_x2 = int(x2 * scale_x)
453
+ fb_y2 = int(y2 * scale_y)
454
+ cv2.rectangle(mask_array, (fb_x1, fb_y1), (fb_x2, fb_y2), 255, -1) #weiße Rechteckbox
455
+
456
+ # Damit wird die Rohmaske für die UI-Anzeige gespeichert
457
+ raw_mask_array = mask_array.copy()
458
+
459
+ # FOCUS_CHANGE POSTPROCESSING (angepasst für 512x512)
460
+ print("🔧 FOCUS_CHANGE POSTPROCESSING (auf 512×512)")
461
+ print(f" mask_array - Min/Max: {mask_array.min()}/{mask_array.max()}")
462
+ print(f" mask_array - Weiße Pixel: {np.sum(mask_array > 0)}")
463
+ print(f" mask_array - Shape: {mask_array.shape}")
464
+ print(f" mask_array - dtype: {mask_array.dtype}")
465
+
466
+ # 1. Findet und behält nur die größte zusammenhängende Komponente der Maske
467
+ labeled_array, num_features = ndimage.label(mask_array)
468
+ if num_features > 1:
469
+ sizes = ndimage.sum(mask_array, labeled_array, range(1, num_features + 1))
470
+ largest_component = np.argmax(sizes) + 1
471
+ mask_array = np.where(labeled_array == largest_component, mask_array, 0)
472
+ print(f" ✅ Größte Komponente behalten ({num_features}→1)")
473
+
474
+ # 2. Morphologische Operationen
475
+ kernel_close = np.ones((5, 5), np.uint8)
476
+ mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_CLOSE, kernel_close, iterations=2)
477
+
478
+ kernel_dilate = np.ones((15, 15), np.uint8)
479
+ mask_array = cv2.dilate(mask_array, kernel_dilate, iterations=1)
480
+
481
+ # 3. Weiche Übergänge mittlerer Blur für natürliche Übergänge
482
+ mask_array = cv2.GaussianBlur(mask_array, (9, 9), 2.0)
483
+
484
+ # 4. Gamma-Korrektur
485
+ mask_array_float = mask_array.astype(np.float32) / 255.0
486
+ mask_array_float = np.clip(mask_array_float, 0.0, 1.0)
487
+ mask_array_float = mask_array_float ** 0.85
488
+ mask_array = (mask_array_float * 255).astype(np.uint8)
489
+
490
+ # 5. Auf Originalgröße für Rückgabe (falls benötigt)
491
+ mask_512 = Image.fromarray(mask_array).convert("L")
492
+ raw_mask = Image.fromarray(raw_mask_array).convert("L")
493
+
494
+ # Finale Maske für ControlNet ist 512x512
495
+ mask = mask_512
496
+
497
+ print(f"✅ FOCUS_CHANGE Maske erstellt: {mask.size}")
498
+ return mask, raw_mask
499
+
500
+ # ============================================================
501
+ # BLOCK 3: FACE_ONLY_CHANGE
502
+ # ============================================================
503
+ elif mode == "face_only_change":
504
+ print("-" * 60)
505
+ print("👤 SPEZIALMODUS: NUR GESICHT - ROBUSTER WORKFLOW")
506
+ print("-" * 60)
507
+
508
+ # ============================================================
509
+ # Originalbild sichern
510
+ # Andere Vorgehensweise da SAM bei kleinen Köpfen sonst keine Chance hat!
511
+ # Bild ausschneiden auf eine vergrößerte quadratische Box - Crops
512
+ # ============================================================
513
+ original_image = image
514
+ print(f"💾 Originalbild gesichert: {original_image.size}")
515
+
516
+ # ============================================================
517
+ # Crop = BBox × 2.5 (ERHÖHT für mehr Kontext)
518
+ # ============================================================
519
+ print("✂️ SCHRITT 2: ERSTELLE QUADRATISCHEN AUSSCHNITT (BBox × 2.5)")
520
+
521
+ # BBox-Zentrum berechnen
522
+ bbox_center_x = (x1 + x2) // 2
523
+ bbox_center_y = (y1 + y2) // 2
524
+ print(f" 📍 BBox-Zentrum: ({bbox_center_x}, {bbox_center_y})")
525
+
526
+ # Größte Dimension der BBox finden
527
+ bbox_width = x2 - x1
528
+ bbox_height = y2 - y1
529
+ bbox_max_dim = max(bbox_width, bbox_height)
530
+ print(f" 📏 BBox Dimensionen: {bbox_width} × {bbox_height} px")
531
+ print(f" 📐 Maximale BBox-Dimension: {bbox_max_dim} px")
532
+
533
+ # Crop-Größe berechnen (BBox × 2.5)
534
+ crop_size = int(bbox_max_dim * 2.5)
535
+ print(f" 🎯 Ziel-Crop-Größe: {crop_size} × {crop_size} px (BBox × 2.5)")
536
+
537
+ # Crop-Koordinaten berechnen (zentriert um BBox)
538
+ crop_x1 = bbox_center_x - crop_size // 2
539
+ crop_y1 = bbox_center_y - crop_size // 2
540
+ crop_x2 = crop_x1 + crop_size
541
+ crop_y2 = crop_y1 + crop_size
542
+
543
+ # Sicherstellen, dass Crop innerhalb der Bildgrenzen bleibt
544
+ crop_x1 = max(0, crop_x1)
545
+ crop_y1 = max(0, crop_y1)
546
+ crop_x2 = min(original_image.width, crop_x2)
547
+ crop_y2 = min(original_image.height, crop_y2)
548
+
549
+ # Falls Crop zu klein ist, anpassen
550
+ actual_crop_width = crop_x2 - crop_x1
551
+ actual_crop_height = crop_y2 - crop_y1
552
+
553
+ if actual_crop_width < crop_size or actual_crop_height < crop_size:
554
+ # An Kanten anpassen
555
+ if crop_x1 == 0:
556
+ crop_x2 = min(original_image.width, crop_size)
557
+ elif crop_x2 == original_image.width:
558
+ crop_x1 = max(0, original_image.width - crop_size)
559
+
560
+ if crop_y1 == 0:
561
+ crop_y2 = min(original_image.height, crop_size)
562
+ elif crop_y2 == original_image.height:
563
+ crop_y1 = max(0, original_image.height - crop_size)
564
+
565
+ print(f" 🔲 Crop-Bereich: [{crop_x1}, {crop_y1}, {crop_x2}, {crop_y2}]")
566
+ print(f" 📏 Tatsächliche Crop-Größe: {crop_x2-crop_x1} × {crop_y2-crop_y1} px")
567
+
568
+ # Bild ausschneiden- 2,5 mal so groß und quadratisch wie BBox
569
+ cropped_image = original_image.crop((crop_x1, crop_y1, crop_x2, crop_y2))
570
+ print(f" ✅ Quadratischer Ausschnitt erstellt: {cropped_image.size}")
571
+
572
+ # ============================================================
573
+ # BBox-Koordinaten transformieren
574
+ # ============================================================
575
+ print("📐 SCHRITT 3: BBox-KOORDINATEN TRANSFORMIEREN")
576
+ rel_x1 = x1 - crop_x1
577
+ rel_y1 = y1 - crop_y1
578
+ rel_x2 = x2 - crop_x1
579
+ rel_y2 = y2 - crop_y1
580
+
581
+ # Sicherstellen, dass BBox innerhalb des Crops liegt
582
+ rel_x1 = max(0, rel_x1)
583
+ rel_y1 = max(0, rel_y1)
584
+ rel_x2 = min(cropped_image.width, rel_x2)
585
+ rel_y2 = min(cropped_image.height, rel_y2)
586
+
587
+ print(f" 🎯 Relative BBox im Crop: [{rel_x1}, {rel_y1}, {rel_x2}, {rel_y2}]")
588
+ print(f" 📏 Relative BBox Größe: {rel_x2-rel_x1} × {rel_y2-rel_y1} px")
589
+
590
+ # ============================================================
591
+ # INTENSIVE BILDAUFBEREITUNG FÜR GESICHTSERKENNUNG
592
+ # ============================================================
593
+ print("🔍 SCHRITT 4: ERWEITERTE BILDAUFBEREITUNG FÜR GESICHTSERKENNUNG")
594
+
595
+ # 1. Kontrast verstärken
596
+ contrast_enhancer = ImageEnhance.Contrast(cropped_image)
597
+ enhanced_image = contrast_enhancer.enhance(1.8) # 80% mehr Kontrast
598
+
599
+ # 2. Schärfe erhöhen für bessere Kantenerkennung
600
+ sharpness_enhancer = ImageEnhance.Sharpness(enhanced_image)
601
+ enhanced_image = sharpness_enhancer.enhance(2.0) # 100% mehr Schärfe
602
+
603
+ # 3. Helligkeit anpassen
604
+ brightness_enhancer = ImageEnhance.Brightness(enhanced_image)
605
+ enhanced_image = brightness_enhancer.enhance(1.1) # 10% heller
606
+
607
+ print(f" ✅ Erweiterte Bildaufbereitung abgeschlossen")
608
+ print(f" • Kontrast: +80%")
609
+ print(f" • Schärfe: +100%")
610
+ print(f" • Helligkeit: +10%")
611
+
612
+ # Für SAM: Verwende aufbereiteten Ausschnitt
613
+ image = enhanced_image
614
+ x1, y1, x2, y2 = rel_x1, rel_y1, rel_x2, rel_y2
615
+
616
+ print(" 🔄 SAM wird auf aufbereitetem Ausschnitt ausgeführt")
617
+ print(f" 📊 SAM-Eingabegröße: {image.size}")
618
+
619
+ # ============================================================
620
+ # SAM-AUSFÜHRUNG
621
+ # ============================================================
622
+ print("-" * 60)
623
+ print(f"📦 BOUNDING BOX DETAILS FÜR SAM:")
624
+ print(f" Bild-Größe für SAM: {image.size}")
625
+ print(f" BBox Koordinaten: [{x1}, {y1}, {x2}, {y2}]")
626
+ print(f" BBox Dimensionen: {x2-x1}px × {y2-y1}px")
627
+
628
+ # Vorbereitung für SAM2 - WICHTIG: NUR EINE BBOX
629
+ print("-" * 60)
630
+ print("🖼️ BILDAUFBEREITUNG FÜR SAM 2")
631
+ # SAM erwartet NumPy-Array, kein PIL
632
+ image_np = np.array(image.convert("RGB"))
633
+
634
+ # Immer nur eine BBox verwenden (SAM 2 erwartet genau 1)
635
+ input_boxes = [[[x1, y1, x2, y2]]]
636
+
637
+ # Punkt in der BBox-Mitte (zur Ünterstützung von SAM damit BBox nicht zu dicht um Kopf gezogen werden muß!)
638
+ center_x = (x1 + x2) // 2
639
+ center_y = (y1 + y2) // 2
640
+
641
+ # Punkt im Gesicht (30% höher vom Mittelpunkt)(auch für größere BBox)
642
+ bbox_height = y2 - y1
643
+ face_offset = int(bbox_height * 0.3)
644
+ face_x = center_x
645
+ face_y = center_y - face_offset
646
+ face_y = max(y1 + 10, min(face_y, y2 - 10)) # In BBox halten
647
+
648
+ # BEIDE Punkte kombinieren
649
+ input_points = [[[[center_x, center_y], [face_x, face_y]]]] # ZWEI Punkte
650
+ input_labels = [[[1, 1]]] # Beide sind positive Prompts
651
+
652
+ print(f" 🎯 SAM-Prompt: BBox [{x1},{y1},{x2},{y2}]")
653
+ print(f" 👁️ Punkte: Mitte ({center_x},{center_y}), Gesicht ({face_x},{face_y})")
654
+
655
+ # Aufruf des SAM-Prozessors mit den Variablen. Der Processor verpackt diese Rohdaten
656
+ # in die für das SAM-Modell erforderlichen Tensoren und speichert sie in inputs.
657
+ inputs = self.sam_processor(
658
+ image_np,
659
+ input_boxes=input_boxes,
660
+ input_points=input_points, # ZWEI Punkte
661
+ input_labels=input_labels, # Zwei Labels
662
+ return_tensors="pt"
663
+ ).to(self.device) # Ohne .to(self.device) werden die Tensoren standardmäßig im CPU-RAM erzeugt und gespeichert! Da GPU-Fehler!
664
+
665
+ print(f"✅ Processor-Ausgabe: Dictionary mit {len(inputs)} Schlüsseln: {list(inputs.keys())}")
666
+ print(f" - 'pixel_values' Shape: {inputs['pixel_values'].shape}")
667
+ print(f" - 'input_boxes' Shape: {inputs['input_boxes'].shape}")
668
+ if 'input_points' in inputs:
669
+ print(f" - 'input_points' Shape: {inputs['input_points'].shape}")
670
+
671
+ # 4. SAM2 Vorhersage
672
+ print("-" * 60)
673
+ print("🧠 SAM 2 INFERENZ (Vorhersage)")
674
+ with torch.no_grad():
675
+ print(" Führe Vorhersage durch...")
676
+ outputs = self.sam_model(**inputs)
677
+ print(f"✅ Vorhersage abgeschlossen")
678
+ print(f" Anzahl der Vorhersagemasken: {outputs.pred_masks.shape[2]}")
679
+
680
+ # 5. Maske extrahieren
681
+ print("📏 SCHRITT 6: MASKE EXTRAHIEREN")
682
+
683
+ num_masks = outputs.pred_masks.shape[2]
684
+ print(f" SAM lieferte {num_masks} verschiedene Masken")
685
+
686
+ # Extrahiere alle Masken
687
+ all_masks = []
688
+
689
+ for i in range(num_masks):
690
+ single_mask = outputs.pred_masks[:, :, i, :, :]
691
+ resized_mask = F.interpolate(
692
+ single_mask,
693
+ size=(image.height, image.width),
694
+ mode='bilinear',
695
+ align_corners=False
696
+ ).squeeze()
697
+
698
+ mask_np = resized_mask.sigmoid().cpu().numpy()
699
+ all_masks.append(mask_np)
700
+
701
+ # Basis-Statistiken für jede Maske
702
+ mask_binary = (mask_np > 0.5).astype(np.uint8)
703
+ mask_area = np.sum(mask_binary)
704
+ print(f" Maske {i+1}: Größe={mask_area:,} Pixel, Max-Konfidenz={mask_np.max():.3f}")
705
+
706
+ # ============================================================
707
+ # HEURISTIK
708
+ # ============================================================
709
+ print("🤔 SCHRITT 6: MASKENAUSWAHL MIT MODUS-SPEZIFISCHER HEURISTIK")
710
+
711
+ bbox_center = ((x1 + x2) // 2, (y1 + y2) // 2)
712
+ bbox_area = (x2 - x1) * (y2 - y1)
713
+ print(f" Erwartetes BBox-Zentrum: {bbox_center}")
714
+ print(f" Erwartete BBox-Fläche: {bbox_area:,} Pixel")
715
+
716
+ best_mask_idx = 0
717
+ best_score = -1
718
+
719
+ for i, mask_np in enumerate(all_masks):
720
+ mask_max = mask_np.max()
721
+
722
+ # Grundlegende Filterung
723
+ if mask_max < 0.3:
724
+ print(f" ❌ Maske {i+1}: Zu niedrige Konfidenz ({mask_max:.3f}), überspringe")
725
+ continue
726
+
727
+ # Adaptiver Threshold
728
+ adaptive_threshold = max(0.3, mask_max * 0.7)
729
+ mask_binary = (mask_np > adaptive_threshold).astype(np.uint8)
730
+
731
+ if np.sum(mask_binary) == 0:
732
+ print(f" ❌ Maske {i+1}: Keine Pixel nach Threshold {adaptive_threshold:.3f}")
733
+ continue
734
+
735
+ mask_area_pixels = np.sum(mask_binary)
736
+
737
+ # ============================================================
738
+ # SPEZIALHEURISTIK
739
+ # ============================================================
740
+
741
+ print(f" 🔍 Analysiere Maske {i+1} mit GESICHTS-HEURISTIK")
742
+
743
+ # 1. FLÄCHENBASIERTE BEWERTUNG (40%)
744
+ area_ratio = mask_area_pixels / bbox_area
745
+ print(f" 📐 Flächen-Ratio: {area_ratio:.3f} ({mask_area_pixels:,} / {bbox_area:,} Pixel)")
746
+
747
+ # Optimale Kopfgröße: 80-120% der BBox
748
+ if area_ratio < 0.6:
749
+ print(f" ⚠️ Fläche zu klein für Kopf (<60% der BBox)")
750
+ area_score = area_ratio * 0.5 # Stark bestrafen
751
+ elif area_ratio > 1.5:
752
+ print(f" ⚠️ Fläche zu groß für Kopf (>150% der BBox)")
753
+ area_score = 2.0 - area_ratio # Linear bestrafen
754
+ elif 0.8 <= area_ratio <= 1.2:
755
+ area_score = 1.0 # Perfekte Größe
756
+ print(f" ✅ Perfekte Kopfgröße (80-120% der BBox)")
757
+ else:
758
+ # Sanfte Abweichung
759
+ area_score = 1.0 - abs(area_ratio - 1.0) * 0.5
760
+
761
+ # 2. KOMPAKTHEIT/SOLIDITÄT (30%)
762
+ labeled_mask = measure.label(mask_binary)
763
+ regions = measure.regionprops(labeled_mask)
764
+
765
+ if len(regions) == 0:
766
+ compactness_score = 0.1
767
+ print(f" ❌ Keine zusammenhängenden Regionen gefunden")
768
+ else:
769
+ # Größte Region finden (sollte der Kopf sein)
770
+ largest_region = max(regions, key=lambda r: r.area)
771
+
772
+ # Solidität = Fläche / konvexe Hüllenfläche
773
+ solidity = largest_region.solidity if hasattr(largest_region, 'solidity') else 0.7
774
+
775
+ # Exzentrizität (wie elliptisch) - Köpfe sind tendenziell elliptisch
776
+ eccentricity = largest_region.eccentricity if hasattr(largest_region, 'eccentricity') else 0.5
777
+
778
+ # Perfekt runde Formen (Kreis) sind 0, Linie wäre 1
779
+ # Köpfe haben typischerweise 0.5-0.8
780
+ if 0.4 <= eccentricity <= 0.9:
781
+ eccentricity_score = 1.0 - abs(eccentricity - 0.65) * 2
782
+ else:
783
+ eccentricity_score = 0.2
784
+
785
+ compactness_score = (solidity * 0.6 + eccentricity_score * 0.4)
786
+ print(f" 🎯 Kompaktheits-Analyse:")
787
+ print(f" • Solidität (Fläche/Konvex): {solidity:.3f}")
788
+ print(f" • Exzentrizität (Form): {eccentricity:.3f}")
789
+ print(f" • Kompaktheits-Score: {compactness_score:.3f}")
790
+
791
+ # 3. BBOX-ÜBERLAPPUNG (20%)
792
+ bbox_mask = np.zeros((image.height, image.width), dtype=np.uint8)
793
+ bbox_mask[y1:y2, x1:x2] = 1
794
+ overlap = np.sum(mask_binary & bbox_mask)
795
+ bbox_overlap_ratio = overlap / mask_area_pixels if mask_area_pixels > 0 else 0
796
+
797
+ # Für Kopf: Sollte großteils in BBox sein (mind. 70%)
798
+ if bbox_overlap_ratio >= 0.7:
799
+ bbox_score = 1.0
800
+ print(f" ✅ Hohe BBox-Überlappung: {bbox_overlap_ratio:.3f} ({overlap:,} Pixel)")
801
+ elif bbox_overlap_ratio >= 0.5:
802
+ bbox_score = bbox_overlap_ratio * 1.2
803
+ print(f" ⚠️ Mittlere BBox-Überlappung: {bbox_overlap_ratio:.3f}")
804
+ else:
805
+ bbox_score = bbox_overlap_ratio * 0.8
806
+ print(f" ❌ Geringe BBox-Überlappung: {bbox_overlap_ratio:.3f}")
807
+
808
+ # SAM-KONFIDENZ (10%)
809
+ confidence_score = mask_max
810
+
811
+ # GESAMTSCORE für Gesicht
812
+ score = (
813
+ area_score * 0.4 + # 40% Flächenpassung
814
+ compactness_score * 0.3 + # 30% Kompaktheit
815
+ bbox_score * 0.2 + # 20% BBox-Überlappung
816
+ confidence_score * 0.1 # 10% Konfidenz
817
+ )
818
+
819
+ print(f" 📊 GESICHTS-SCORES für Maske {i+1}:")
820
+ print(f" • Flächen-Score: {area_score:.3f}")
821
+ print(f" • Kompaktheits-Score: {compactness_score:.3f}")
822
+ print(f" • BBox-Überlappungs-Score: {bbox_score:.3f}")
823
+ print(f" • Konfidenz-Score: {confidence_score:.3f}")
824
+ print(f" • GESAMTSCORE: {score:.3f}")
825
+
826
+ if score > best_score:
827
+ best_score = score
828
+ best_mask_idx = i
829
+ print(f" 🏆 Neue beste Maske: Nr. {i+1} mit Score {score:.3f}")
830
+
831
+ print(f"✅ Beste Maske ausgewählt: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")
832
+
833
+ # Beste Maske verwenden
834
+ mask_np = all_masks[best_mask_idx]
835
+ max_val = mask_np.max()
836
+ print(f"🔍 Maximaler SAM-Konfidenzwert der besten Maske: {max_val:.3f}")
837
+
838
+ # ============================================================
839
+ # THRESHOLD-BESTIMMUNG
840
+ # ============================================================
841
+ # Spezieller Threshold für Gesichter
842
+ if max_val < 0.5:
843
+ dynamic_threshold = 0.25
844
+ print(f" ⚠️ SAM ist unsicher für Gesicht (max_val={max_val:.3f} < 0.5)")
845
+ elif max_val < 0.8:
846
+ dynamic_threshold = max_val * 0.65 # Mittlerer Threshold
847
+ print(f" ℹ️ SAM ist mäßig sicher für Gesicht (max_val={max_val:.3f})")
848
+ else:
849
+ dynamic_threshold = max_val * 0.75 # Hoher Threshold
850
+ print(f" ✅ SAM ist sicher für Gesicht (max_val={max_val:.3f} >= 0.8)")
851
+
852
+ print(f" 🎯 Gesichts-Threshold: {dynamic_threshold:.3f}")
853
+
854
+ # Binärmaske erstellen
855
+ print("🐛 DEBUG THRESHOLD:")
856
+ print(f" mask_np Min/Max: {mask_np.min():.3f}/{mask_np.max():.3f}")
857
+ print(f" dynamic_threshold: {dynamic_threshold:.3f}")
858
+
859
+ mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255
860
+
861
+ print(f"🚨 DEBUG BINÄRMASKE:")
862
+ print(f" mask_array Min/Max: {mask_array.min()}/{mask_array.max()}")
863
+ print(f" Weiße Pixel in mask_array: {np.sum(mask_array > 0)}")
864
+ print(f" Anteil weiße Pixel: {np.sum(mask_array > 0) / mask_array.size:.1%}")
865
+
866
+ # Fallback wenn Maske leer
867
+ if mask_array.max() == 0:
868
+ print("⚠️ KRITISCH: Binärmaske ist leer! Erzwinge Testmaske (BBox).")
869
+ print(f" 🚨 BBox für Fallback: x1={x1}, y1={y1}, x2={x2}, y2={y2}")
870
+
871
+ test_mask = np.zeros((image.height, image.width), dtype=np.uint8)
872
+ cv2.rectangle(test_mask, (x1, y1), (x2, y2), 255, -1)
873
+
874
+ mask_array = test_mask
875
+ print(f"🐛 DEBUG ERZWUNGENE MASKE: Weiße Pixel: {np.sum(mask_array > 0)}")
876
+
877
+ # Rohmaske speichern
878
+ raw_mask_array = mask_array.copy()
879
+
880
+ # ============================================================
881
+ # POSTPROCESSING
882
+ # ============================================================
883
+
884
+ print("👤 GESICHTS-SPEZIFISCHES POSTPROCESSING")
885
+
886
+ # 1. Größte zusammenhängende Komponente finden
887
+ labeled_array, num_features = ndimage.label(mask_array)
888
+
889
+ if num_features > 0:
890
+ print(f" 🔍 Gefundene Komponenten: {num_features}")
891
+
892
+ sizes = ndimage.sum(mask_array, labeled_array, range(1, num_features + 1))
893
+ largest_component_idx = np.argmax(sizes) + 1
894
+
895
+ print(f" 👑 Größte Komponente: Nr. {largest_component_idx} mit {sizes[largest_component_idx-1]:,} Pixel")
896
+
897
+ # NUR die größte Komponente behalten (der Kopf)
898
+ mask_array = np.where(labeled_array == largest_component_idx, mask_array, 0)
899
+
900
+ # MORPHOLOGISCHE OPERATIONEN FÜR SAUBEREN KOPF
901
+ print(" ⚙️ Morphologische Operationen für sauberen Kopf")
902
+
903
+ # Zuerst CLOSE, um kleine Löcher im Kopf zu füllen
904
+ kernel_close = np.ones((7, 7), np.uint8)
905
+ mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_CLOSE, kernel_close, iterations=1)
906
+ print(" • MORPH_CLOSE (7x7) - Löcher im Kopf füllen")
907
+
908
+ # Dann OPEN, um kleine Ausreißer zu entfernen
909
+ kernel_open = np.ones((5, 5), np.uint8)
910
+ mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_OPEN, kernel_open, iterations=1)
911
+ print(" • MORPH_OPEN (5x5) - Rauschen entfernen")
912
+
913
+ # ============================================================
914
+ # KRITISCH: MASKE IMMER ZURÜCK AUF ORIGINALGRÖSSE (auch bei Fallback!)
915
+ # ============================================================
916
+ print("-" * 60)
917
+ print("🔄 MASKE IMMER ZURÜCK AUF ORIGINALGRÖSSE TRANSFORMIEREN")
918
+
919
+ # WICHTIG: Immer die richtigen Crop-Koordinaten verwenden
920
+ temp_mask = Image.fromarray(mask_array).convert("L")
921
+ print(f" Maskengröße auf Ausschnitt: {temp_mask.size}")
922
+
923
+ # Maske auf ORIGINALBILDGRÖSSE bringen
924
+ final_mask = Image.new("L", original_image.size, 0)
925
+ print(f" Leere Maske in Originalgröße: {final_mask.size}")
926
+
927
+ # Immer die gespeicherten Crop-Koordinaten verwenden
928
+ if 'crop_x1' in locals() and 'crop_y1' in locals():
929
+ final_mask.paste(temp_mask, (crop_x1, crop_y1))
930
+ print(f" Maskenposition im Original: ({crop_x1}, {crop_y1})")
931
+ else:
932
+ # Fallback: Zentrieren
933
+ x_offset = (original_image.width - temp_mask.width) // 2
934
+ y_offset = (original_image.height - temp_mask.height) // 2
935
+ final_mask.paste(temp_mask, (x_offset, y_offset))
936
+ print(f" ⚠️ Keine Crop-Koordinaten, zentriert: ({x_offset}, {y_offset})")
937
+
938
+ mask_array = np.array(final_mask)
939
+ print(f" ✅ Maske zurück auf Originalgröße skaliert: {mask_array.shape}")
940
+
941
+ # Bild-Referenz zurücksetzen
942
+ image = original_image
943
+ print(f" 🔄 Bild-Referenz wieder auf Original gesetzt: {image.size}")
944
+
945
+ # ============================================================
946
+ # ABSCHLIESSENDE STATISTIK
947
+ # ============================================================
948
+
949
+ print("📊 FINALE MASKEN-STATISTIK")
950
+
951
+ # Weiße Pixel zählen
952
+ white_pixels = np.sum(mask_array > 0)
953
+ total_pixels = mask_array.size
954
+ white_ratio = white_pixels / total_pixels * 100
955
+
956
+ # Original-BBox Fläche (vor Crop)
957
+ original_bbox_width = original_bbox[2] - original_bbox[0]
958
+ original_bbox_height = original_bbox[3] - original_bbox[1]
959
+ original_face_area = original_bbox_width * original_bbox_height
960
+ coverage_ratio = white_pixels / original_face_area if original_face_area > 0 else 0
961
+ print(f" 👤 GESICHTSABDECKUNG: {coverage_ratio:.1%} der ursprünglichen BBox")
962
+
963
+ print(f" Weiße Pixel (Veränderungsbereich): {white_pixels:,} ({white_ratio:.1f}%)")
964
+ print(f" Schwarze Pixel (Erhaltungsbereich): {total_pixels-white_pixels:,} ({100-white_ratio:.1f}%)")
965
+ print(f" Gesamtpixel: {total_pixels:,}")
966
+
967
+ # Warnungen basierend auf Abdeckung
968
+ if coverage_ratio < 0.7:
969
+ print(f" ⚠️ WARNUNG: Geringe Gesichtsabdeckung ({coverage_ratio:.1%})")
970
+ elif coverage_ratio > 1.3:
971
+ print(f" ⚠️ WARNUNG: Sehr hohe Gesichtsabdeckung ({coverage_ratio:.1%})")
972
+ elif 0.8 <= coverage_ratio <= 1.2:
973
+ print(f" ✅ OPTIMALE Gesichtsabdeckung ({coverage_ratio:.1%})")
974
+
975
+ # Zurück zu PIL Image
976
+ mask = Image.fromarray(mask_array).convert("L")
977
+ raw_mask = Image.fromarray(raw_mask_array).convert("L")
978
+
979
+ print("#" * 80)
980
+ print(f"✅ SAM 2 SEGMENTIERUNG ABGESCHLOSSEN")
981
+ print(f"📐 Finale Maskengröße: {mask.size}")
982
+ print(f"🎛️ Verwendeter Modus: {mode}")
983
+
984
+ print(f"👤 Crop={crop_size}×{crop_size}px, Heuristik-Score={best_score:.3f}")
985
+ print(f"👤 Kopfabdeckung: {coverage_ratio:.1%} der BBox")
986
+
987
+ print(f"🔍 DEBUG FINALE MASKE:")
988
+ print(f" mask_array Min/Max: {mask_array.min()}/{mask_array.max()}, Typ: {mask_array.dtype}")
989
+ print(f" Weiße Pixel final: {np.sum(mask_array > 0)}")
990
+
991
+ print("#" * 80)
992
+
993
+ return mask, raw_mask
994
+
995
+ # ============================================================
996
+ # UNBEKANNTER MODUS
997
+ # ============================================================
998
+ else:
999
+ print(f"❌ Unbekannter Modus: {mode}")
1000
+ return self._create_rectangular_mask(image, bbox_coords, "focus_change")
1001
+
1002
+ except Exception as e:
1003
+ print("❌" * 40)
1004
+ print("❌ FEHLER IN SAM 2 SEGMENTIERUNG")
1005
+ print(f"Fehler: {str(e)[:200]}")
1006
+ print("❌" * 40)
1007
+ import traceback
1008
+ traceback.print_exc()
1009
+
1010
+ # Fallback
1011
+ fallback_mask = self._create_rectangular_mask(original_image, original_bbox, mode)
1012
+ if fallback_mask.size != original_image.size:
1013
+ print(f" ⚠️ Fallback-Maske angepasst: {fallback_mask.size} → {original_image.size}")
1014
+ fallback_mask = fallback_mask.resize(original_image.size, Image.Resampling.NEAREST)
1015
+
1016
+ return fallback_mask, fallback_mask