Astridkraft commited on
Commit
0de5ba9
·
verified ·
1 Parent(s): 98758f6

Update sam_module.py

Browse files
Files changed (1) hide show
  1. sam_module.py +21 -6
sam_module.py CHANGED
@@ -114,7 +114,10 @@ def create_sam_mask(self, image, bbox_coords, mode):
114
  # SAM Vorhersage (alle 3 Masken)
115
  print("🧠 SAM 2 INFERENZ (3 Masken-Varianten)")
116
  with torch.no_grad():
 
117
  outputs = self.sam_model(**inputs)
 
 
118
 
119
  # BBox-Information für Heuristik
120
  bbox_center = ((x1 + x2) // 2, (y1 + y2) // 2)
@@ -130,7 +133,7 @@ def create_sam_mask(self, image, bbox_coords, mode):
130
  mask_256 = outputs.pred_masks[:, :, i, :, :]
131
  mask_np_256 = mask_256.sigmoid().squeeze().cpu().numpy()
132
 
133
- # Für Heuristik: Temporär auf Bildgröße skalieren
134
  temp_mask = F.interpolate(
135
  mask_256,
136
  size=(image.height, image.width),
@@ -139,14 +142,15 @@ def create_sam_mask(self, image, bbox_coords, mode):
139
  ).squeeze()
140
  mask_np_temp = temp_mask.sigmoid().cpu().numpy()
141
 
142
- # Adaptive Vor-Filterung
143
  mask_max = mask_np_temp.max()
144
  if mask_max < 0.3:
145
  continue # Maske überspringen
146
 
147
  adaptive_threshold = max(0.3, mask_max * 0.7)
148
  mask_binary = (mask_np_temp > adaptive_threshold).astype(np.uint8)
149
-
 
150
  if np.sum(mask_binary) == 0:
151
  continue
152
 
@@ -192,7 +196,7 @@ def create_sam_mask(self, image, bbox_coords, mode):
192
 
193
  print(f"✅ Beste Maske: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")
194
 
195
- # NUR DIE BESTE MASKE AUF 512x512 SKALIEREN
196
  best_mask_256 = outputs.pred_masks[:, :, best_mask_idx, :, :]
197
  resized_mask = F.interpolate(
198
  best_mask_256,
@@ -204,7 +208,14 @@ def create_sam_mask(self, image, bbox_coords, mode):
204
  mask_np = resized_mask.sigmoid().cpu().numpy()
205
  print(f" 🔄 Beste Maske skaliert auf 512×512 für ControlNet")
206
 
207
- # Dynamischer Threshold für focus_change
 
 
 
 
 
 
 
208
  mask_max = mask_np.max()
209
  if best_score < 0.7: # Schlechte Maskenqualität
210
  dynamic_threshold = 0.05 # SEHR NIEDRIG für maximale Abdeckung
@@ -217,7 +228,7 @@ def create_sam_mask(self, image, bbox_coords, mode):
217
  # Binärmaske erstellen
218
  mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255
219
 
220
- # Fallback bei leerer Maske
221
  if mask_array.max() == 0:
222
  print(" ⚠️ Maske leer, erstelle rechteckige Fallback-Maske")
223
  mask_array = np.zeros((512, 512), dtype=np.uint8)
@@ -232,6 +243,10 @@ def create_sam_mask(self, image, bbox_coords, mode):
232
 
233
  # FOCUS_CHANGE POSTPROCESSING (angepasst für 512x512)
234
  print("🔧 FOCUS_CHANGE POSTPROCESSING (auf 512×512)")
 
 
 
 
235
 
236
  # 1. Größte Komponente behalten
237
  labeled_array, num_features = ndimage.label(mask_array)
 
114
  # SAM Vorhersage (alle 3 Masken)
115
  print("🧠 SAM 2 INFERENZ (3 Masken-Varianten)")
116
  with torch.no_grad():
117
+ print(" Führe Vorhersage durch...")
118
  outputs = self.sam_model(**inputs)
119
+ print(f"✅ Vorhersage abgeschlossen")
120
+ print(f" Anzahl der Vorhersagemasken: {outputs.pred_masks.shape[2]}")
121
 
122
  # BBox-Information für Heuristik
123
  bbox_center = ((x1 + x2) // 2, (y1 + y2) // 2)
 
133
  mask_256 = outputs.pred_masks[:, :, i, :, :]
134
  mask_np_256 = mask_256.sigmoid().squeeze().cpu().numpy()
135
 
136
+ # Für Heuristik: Temporär auf Bildgröße skalieren für Flächenverhältnis und Schwerpunktposition
137
  temp_mask = F.interpolate(
138
  mask_256,
139
  size=(image.height, image.width),
 
142
  ).squeeze()
143
  mask_np_temp = temp_mask.sigmoid().cpu().numpy()
144
 
145
+ # Adaptive Vor-Filterung (prüft ob Maske überhaupt gültig ist)
146
  mask_max = mask_np_temp.max()
147
  if mask_max < 0.3:
148
  continue # Maske überspringen
149
 
150
  adaptive_threshold = max(0.3, mask_max * 0.7)
151
  mask_binary = (mask_np_temp > adaptive_threshold).astype(np.uint8)
152
+
153
+ # wenn nur schwarze Pixel (keine Segmentierung) nimm die nächste Maske
154
  if np.sum(mask_binary) == 0:
155
  continue
156
 
 
196
 
197
  print(f"✅ Beste Maske: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")
198
 
199
+ # NUR DIE BESTE MASKE AUF 512x512 SKALIEREN -Für Inpaint
200
  best_mask_256 = outputs.pred_masks[:, :, best_mask_idx, :, :]
201
  resized_mask = F.interpolate(
202
  best_mask_256,
 
208
  mask_np = resized_mask.sigmoid().cpu().numpy()
209
  print(f" 🔄 Beste Maske skaliert auf 512×512 für ControlNet")
210
 
211
+
212
+ # ============================================================
213
+ # DYNAMISCHER THRESHOLD
214
+ # SAM gibt nur Wahrscheinlichkeiten aus!
215
+ # Nachdem das Modell eine Maske für eine Person vorhersagt (wo jeder Pixel einen Wert zwischen 0 und 1 hat,
216
+ # wie "wahrscheinlich gehört dieser Pixel zur Person"), wird diese Maske binarisiert (0 oder 1), indem alle
217
+ # Pixel unter 0.05 auf 0 gesetzt werden, alle darüber auf 1.
218
+ # ============================================================
219
  mask_max = mask_np.max()
220
  if best_score < 0.7: # Schlechte Maskenqualität
221
  dynamic_threshold = 0.05 # SEHR NIEDRIG für maximale Abdeckung
 
228
  # Binärmaske erstellen
229
  mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255
230
 
231
+ # Fallback bei leerer Maske, der höchste Wert ist 0 also schwarz
232
  if mask_array.max() == 0:
233
  print(" ⚠️ Maske leer, erstelle rechteckige Fallback-Maske")
234
  mask_array = np.zeros((512, 512), dtype=np.uint8)
 
243
 
244
  # FOCUS_CHANGE POSTPROCESSING (angepasst für 512x512)
245
  print("🔧 FOCUS_CHANGE POSTPROCESSING (auf 512×512)")
246
+ print(f" mask_array - Min/Max: {mask_array.min()}/{mask_array.max()}")
247
+ print(f" mask_array - Weiße Pixel: {np.sum(mask_array > 0)}")
248
+ print(f" mask_array - Shape: {mask_array.shape}")
249
+ print(f" mask_array - dtype: {mask_array.dtype}")
250
 
251
  # 1. Größte Komponente behalten
252
  labeled_array, num_features = ndimage.label(mask_array)