Spaces:
Sleeping
Sleeping
AI Agent commited on
Commit ·
66564c2
1
Parent(s): e66cd5c
Smooth alpha-feathered edges, force PNG format in Gallery, remove unsupported preview param, increase crop padding
Browse files
app.py
CHANGED
|
@@ -138,17 +138,26 @@ def mask_iou(m1: np.ndarray, m2: np.ndarray) -> float:
|
|
| 138 |
return float(inter) / float(union) if union > 0 else 0.0
|
| 139 |
|
| 140 |
def mask_to_crop(orig_rgb: np.ndarray, mask: np.ndarray) -> np.ndarray:
|
|
|
|
| 141 |
h, w = orig_rgb.shape[:2]
|
| 142 |
rgba = np.zeros((h, w, 4), dtype=np.uint8)
|
| 143 |
rgba[:, :, :3] = orig_rgb
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
ys, xs = np.nonzero(mask)
|
| 147 |
if len(ys) == 0:
|
| 148 |
return rgba
|
| 149 |
y0, y1 = int(ys.min()), int(ys.max())
|
| 150 |
x0, x1 = int(xs.min()), int(xs.max())
|
| 151 |
-
pad =
|
| 152 |
y0, x0 = max(0, y0 - pad), max(0, x0 - pad)
|
| 153 |
y1, x1 = min(h - 1, y1 + pad), min(w - 1, x1 + pad)
|
| 154 |
return rgba[y0:y1+1, x0:x1+1]
|
|
@@ -351,8 +360,8 @@ with gr.Blocks(title="SAM 3 Asset Extractor") as demo:
|
|
| 351 |
columns=3,
|
| 352 |
object_fit="contain",
|
| 353 |
height=650,
|
|
|
|
| 354 |
elem_classes=["gallery-container"],
|
| 355 |
-
preview=True,
|
| 356 |
)
|
| 357 |
|
| 358 |
submit_btn.click(fn=extract_assets, inputs=[input_image], outputs=[output_gallery])
|
|
|
|
| 138 |
return float(inter) / float(union) if union > 0 else 0.0
|
| 139 |
|
| 140 |
def mask_to_crop(orig_rgb: np.ndarray, mask: np.ndarray) -> np.ndarray:
|
| 141 |
+
"""Crop an RGBA image using a mask with feathered (anti-aliased) edges."""
|
| 142 |
h, w = orig_rgb.shape[:2]
|
| 143 |
rgba = np.zeros((h, w, 4), dtype=np.uint8)
|
| 144 |
rgba[:, :, :3] = orig_rgb
|
| 145 |
+
|
| 146 |
+
# Create soft alpha channel with Gaussian-feathered edges
|
| 147 |
+
# This eliminates the harsh jagged pixel boundaries
|
| 148 |
+
mask_float = mask.astype(np.float32)
|
| 149 |
+
# Blur the binary mask to create a smooth gradient at edges
|
| 150 |
+
alpha_soft = cv2.GaussianBlur(mask_float, (7, 7), sigmaX=1.5)
|
| 151 |
+
# Normalize: keep interior at 255, smoothly fade edges to 0
|
| 152 |
+
alpha_soft = np.clip(alpha_soft * 255, 0, 255).astype(np.uint8)
|
| 153 |
+
rgba[:, :, 3] = alpha_soft
|
| 154 |
|
| 155 |
ys, xs = np.nonzero(mask)
|
| 156 |
if len(ys) == 0:
|
| 157 |
return rgba
|
| 158 |
y0, y1 = int(ys.min()), int(ys.max())
|
| 159 |
x0, x1 = int(xs.min()), int(xs.max())
|
| 160 |
+
pad = 10 # More breathing room around crops
|
| 161 |
y0, x0 = max(0, y0 - pad), max(0, x0 - pad)
|
| 162 |
y1, x1 = min(h - 1, y1 + pad), min(w - 1, x1 + pad)
|
| 163 |
return rgba[y0:y1+1, x0:x1+1]
|
|
|
|
| 360 |
columns=3,
|
| 361 |
object_fit="contain",
|
| 362 |
height=650,
|
| 363 |
+
format="png",
|
| 364 |
elem_classes=["gallery-container"],
|
|
|
|
| 365 |
)
|
| 366 |
|
| 367 |
submit_btn.click(fn=extract_assets, inputs=[input_image], outputs=[output_gallery])
|