Spaces:
Running
on
Zero
Running
on
Zero
Add histogram normalization on foreground pixels after alpha premultiply
Browse files
app.py
CHANGED
|
@@ -376,8 +376,25 @@ def preprocess_image(input: Image.Image) -> Image.Image:
|
|
| 376 |
bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2
|
| 377 |
output = output.crop(bbox) # type: ignore
|
| 378 |
output = np.array(output).astype(np.float32) / 255
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
return output
|
| 382 |
|
| 383 |
|
|
|
|
| 376 |
bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2
|
| 377 |
output = output.crop(bbox) # type: ignore
|
| 378 |
output = np.array(output).astype(np.float32) / 255
|
| 379 |
+
rgb = output[:, :, :3]
|
| 380 |
+
alpha = output[:, :, 3:4]
|
| 381 |
+
rgb = rgb * alpha # premultiply alpha
|
| 382 |
+
|
| 383 |
+
# Histogram normalization on foreground pixels only
|
| 384 |
+
fg_mask = (alpha[:, :, 0] > 0.05)
|
| 385 |
+
if fg_mask.any():
|
| 386 |
+
for c in range(3):
|
| 387 |
+
ch = rgb[:, :, c]
|
| 388 |
+
fg_vals = ch[fg_mask]
|
| 389 |
+
if fg_vals.max() > fg_vals.min():
|
| 390 |
+
# Stretch foreground channel to use full [0, 1] range
|
| 391 |
+
lo, hi = np.percentile(fg_vals, [1, 99])
|
| 392 |
+
if hi > lo:
|
| 393 |
+
ch_norm = np.clip((ch - lo) / (hi - lo), 0, 1)
|
| 394 |
+
# Only apply to foreground pixels
|
| 395 |
+
rgb[:, :, c] = np.where(fg_mask, ch_norm, 0)
|
| 396 |
+
|
| 397 |
+
output = Image.fromarray((rgb * 255).astype(np.uint8))
|
| 398 |
return output
|
| 399 |
|
| 400 |
|