Fahimeh Orvati Nia
commited on
Commit
·
7c80781
1
Parent(s):
5f6c42c
update
Browse files
app.py
CHANGED
|
@@ -7,10 +7,36 @@ from PIL import Image
|
|
| 7 |
from itertools import product
|
| 8 |
|
| 9 |
def show_preview(image):
|
| 10 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
if image is None:
|
| 12 |
return None
|
| 13 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
return image.convert("RGB")
|
| 15 |
except Exception:
|
| 16 |
return image
|
|
|
|
| 7 |
from itertools import product
|
| 8 |
|
| 9 |
def show_preview(image):
|
| 10 |
+
"""Render uploaded image faithfully, including 16-bit/single-channel inputs.
|
| 11 |
+
|
| 12 |
+
- RGB/RGBA: show as-is (strip alpha)
|
| 13 |
+
- 16-bit or single-channel: min-max (or 1-99%ile) normalize to 8-bit for display
|
| 14 |
+
"""
|
| 15 |
if image is None:
|
| 16 |
return None
|
| 17 |
try:
|
| 18 |
+
arr = np.array(image)
|
| 19 |
+
# RGBA → RGB
|
| 20 |
+
if arr.ndim == 3 and arr.shape[2] == 4:
|
| 21 |
+
return image.convert("RGB")
|
| 22 |
+
# RGB → as-is
|
| 23 |
+
if arr.ndim == 3 and arr.shape[2] == 3:
|
| 24 |
+
return image
|
| 25 |
+
# Single-channel or higher bit-depth
|
| 26 |
+
if arr.ndim == 2 or (arr.ndim == 3 and arr.shape[2] == 1):
|
| 27 |
+
if arr.ndim == 3:
|
| 28 |
+
arr = arr[..., 0]
|
| 29 |
+
a = np.nan_to_num(arr.astype(np.float64), nan=0.0, posinf=0.0, neginf=0.0)
|
| 30 |
+
# Robust contrast stretch
|
| 31 |
+
vmin = np.percentile(a, 1.0)
|
| 32 |
+
vmax = np.percentile(a, 99.0)
|
| 33 |
+
if not np.isfinite(vmin) or not np.isfinite(vmax) or vmax <= vmin:
|
| 34 |
+
vmin, vmax = float(np.min(a)), float(np.max(a))
|
| 35 |
+
denom = max(vmax - vmin, 1e-6)
|
| 36 |
+
vis = np.clip((a - vmin) / denom, 0.0, 1.0) * 255.0
|
| 37 |
+
vis8 = vis.astype(np.uint8)
|
| 38 |
+
return Image.fromarray(vis8, mode='L')
|
| 39 |
+
# Fallback
|
| 40 |
return image.convert("RGB")
|
| 41 |
except Exception:
|
| 42 |
return image
|