Spaces:
Sleeping
Sleeping
Update gradio_app.py
Browse files- gradio_app.py +159 -49
gradio_app.py
CHANGED
|
@@ -3,24 +3,58 @@ import numpy as np
|
|
| 3 |
import cv2
|
| 4 |
import os
|
| 5 |
import tifffile
|
|
|
|
| 6 |
from PIL import Image
|
|
|
|
| 7 |
from cellpose import models
|
| 8 |
|
| 9 |
-
# ===
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
if ext in [".tif", ".tiff"]:
|
| 16 |
-
image = tifffile.imread(
|
| 17 |
else:
|
| 18 |
-
image = cv2.imread(
|
| 19 |
if image is None:
|
| 20 |
raise ValueError("Failed to load the uploaded image.")
|
| 21 |
return image
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
def apply_gamma_correction(image, gamma):
|
| 25 |
image = image.astype(np.float32)
|
| 26 |
image = image - image.min()
|
|
@@ -29,7 +63,48 @@ def apply_gamma_correction(image, gamma):
|
|
| 29 |
image = (image * 255).astype(np.uint8)
|
| 30 |
return image
|
| 31 |
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
def update_gamma_display(file, use_gamma, gamma_val):
|
| 34 |
if file is None:
|
| 35 |
return None
|
|
@@ -39,41 +114,62 @@ def update_gamma_display(file, use_gamma, gamma_val):
|
|
| 39 |
if use_gamma:
|
| 40 |
img = apply_gamma_correction(img, gamma_val)
|
| 41 |
else:
|
| 42 |
-
img =
|
| 43 |
-
img = (img - img.min()) / (img.max() + 1e-8)
|
| 44 |
-
img = (img * 255).astype(np.uint8)
|
| 45 |
return img
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
| 50 |
image = load_image_robust(file)
|
| 51 |
-
|
| 52 |
if image.ndim == 3:
|
| 53 |
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 54 |
-
|
| 55 |
if use_gamma:
|
| 56 |
-
|
| 57 |
else:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
description = """
|
| 78 |
**CellPhase1.0** is developed and released by the **Center for Label-free Imaging and Multiscale Biophotonics**, Beckman Institute, University of Illinois Urbana-Champaign.
|
| 79 |
Supported by the **National Institute of Health/National Institute of Biomedical Imaging and Bioengineering**, Award #: **P41EB031772**.
|
|
@@ -85,7 +181,6 @@ Source code available on [GitHub](https://github.com/...)
|
|
| 85 |
**License**: Open Source – [MIT License](https://opensource.org/licenses/MIT)
|
| 86 |
"""
|
| 87 |
|
| 88 |
-
# === Gradio Interface ===
|
| 89 |
with gr.Blocks(title="CellPhase1.0 - Cell Segmentation Tool") as demo:
|
| 90 |
gr.Markdown(description)
|
| 91 |
|
|
@@ -98,23 +193,38 @@ with gr.Blocks(title="CellPhase1.0 - Cell Segmentation Tool") as demo:
|
|
| 98 |
|
| 99 |
gamma_preview = gr.Image(type="numpy", label="Gamma Corrected Image Preview")
|
| 100 |
|
| 101 |
-
diameter_slider = gr.Slider(10, 120, value=50, step=5, label="Diameter")
|
| 102 |
-
flow_slider = gr.Slider(0.2, 1.0, value=0.6, step=0.1, label="Flow Threshold")
|
| 103 |
-
run_btn = gr.Button("Run Segmentation")
|
| 104 |
-
|
| 105 |
with gr.Column():
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
|
| 110 |
-
#
|
| 111 |
file_input.change(update_gamma_display, inputs=[file_input, use_gamma, gamma_slider], outputs=gamma_preview)
|
| 112 |
gamma_slider.change(update_gamma_display, inputs=[file_input, use_gamma, gamma_slider], outputs=gamma_preview)
|
| 113 |
use_gamma.change(update_gamma_display, inputs=[file_input, use_gamma, gamma_slider], outputs=gamma_preview)
|
| 114 |
|
| 115 |
-
#
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
|
|
|
| 120 |
demo.launch(share=True)
|
|
|
|
| 3 |
import cv2
|
| 4 |
import os
|
| 5 |
import tifffile
|
| 6 |
+
import tempfile
|
| 7 |
from PIL import Image
|
| 8 |
+
from matplotlib import cm
|
| 9 |
from cellpose import models
|
| 10 |
|
| 11 |
+
# =========================
|
| 12 |
+
# Model (GPU off by default on Spaces CPU)
|
| 13 |
+
# =========================
|
| 14 |
+
# If you enable a GPU hardware on the Space, set gpu=True
|
| 15 |
+
model = models.CellposeModel(pretrained_model="cellpose_train_folder_qpi_live_0520", gpu=False)
|
| 16 |
+
|
| 17 |
+
# =========================
|
| 18 |
+
# Utils
|
| 19 |
+
# =========================
|
| 20 |
+
def _get_path_from_gradio_file(file_obj):
|
| 21 |
+
"""
|
| 22 |
+
Gradio File may come as:
|
| 23 |
+
- dict with 'name' and 'path'
|
| 24 |
+
- str path
|
| 25 |
+
- tempfile.NamedTemporaryFile / file-like with .name
|
| 26 |
+
Return a filesystem path.
|
| 27 |
+
"""
|
| 28 |
+
if file_obj is None:
|
| 29 |
+
return None
|
| 30 |
+
if isinstance(file_obj, dict):
|
| 31 |
+
# v4 often gives {'name': <orig>, 'size': ..., 'data': ..., 'mime_type': ..., 'is_file': True, 'orig_name': ..., 'path': <tmp>}
|
| 32 |
+
p = file_obj.get("path") or file_obj.get("name")
|
| 33 |
+
return p
|
| 34 |
+
if isinstance(file_obj, str):
|
| 35 |
+
return file_obj
|
| 36 |
+
# Fallback: try attributes
|
| 37 |
+
return getattr(file_obj, "name", None)
|
| 38 |
+
|
| 39 |
+
def load_image_robust(file_obj):
|
| 40 |
+
path = _get_path_from_gradio_file(file_obj)
|
| 41 |
+
if path is None or not os.path.exists(path):
|
| 42 |
+
raise ValueError("Could not resolve uploaded file path.")
|
| 43 |
+
ext = os.path.splitext(path)[-1].lower()
|
| 44 |
if ext in [".tif", ".tiff"]:
|
| 45 |
+
image = tifffile.imread(path)
|
| 46 |
else:
|
| 47 |
+
image = cv2.imread(path, cv2.IMREAD_UNCHANGED)
|
| 48 |
if image is None:
|
| 49 |
raise ValueError("Failed to load the uploaded image.")
|
| 50 |
return image
|
| 51 |
|
| 52 |
+
def to_uint8_grayscale(img):
|
| 53 |
+
img = img.astype(np.float32)
|
| 54 |
+
img = img - img.min()
|
| 55 |
+
img = img / (img.max() + 1e-8)
|
| 56 |
+
return (img * 255).astype(np.uint8)
|
| 57 |
+
|
| 58 |
def apply_gamma_correction(image, gamma):
|
| 59 |
image = image.astype(np.float32)
|
| 60 |
image = image - image.min()
|
|
|
|
| 63 |
image = (image * 255).astype(np.uint8)
|
| 64 |
return image
|
| 65 |
|
| 66 |
+
def colorize_with_matplotlib(mask_labels, cmap_name="nipy_spectral"):
|
| 67 |
+
"""
|
| 68 |
+
Colorize an integer-labeled mask using a matplotlib colormap.
|
| 69 |
+
The result is RGB uint8.
|
| 70 |
+
"""
|
| 71 |
+
m = mask_labels.astype(np.float32)
|
| 72 |
+
maxv = np.max(m)
|
| 73 |
+
if maxv <= 0:
|
| 74 |
+
rgb = np.zeros((*m.shape, 3), dtype=np.uint8)
|
| 75 |
+
return rgb
|
| 76 |
+
norm = m / (maxv + 1e-8)
|
| 77 |
+
cmap = cm.get_cmap(cmap_name)
|
| 78 |
+
rgba = cmap(norm) # float RGBA in [0,1]
|
| 79 |
+
rgb = (rgba[..., :3] * 255).astype(np.uint8)
|
| 80 |
+
return rgb
|
| 81 |
+
|
| 82 |
+
def overlay_colored_mask_on_gray(gray_uint8, colored_mask_uint8, alpha=0.5):
|
| 83 |
+
gray_rgb = cv2.cvtColor(gray_uint8, cv2.COLOR_GRAY2BGR)
|
| 84 |
+
overlay = cv2.addWeighted(gray_rgb, 1 - alpha, colored_mask_uint8, alpha, 0)
|
| 85 |
+
return overlay
|
| 86 |
+
|
| 87 |
+
def run_cellpose(image_uint8_gray, diameter, flow_threshold):
|
| 88 |
+
"""
|
| 89 |
+
Run Cellpose and return the labeled mask (uint16) and a normalized 0-255 mask (uint8) for saving.
|
| 90 |
+
"""
|
| 91 |
+
# cellpose expects HxW (grayscale) for channels=[0,0]
|
| 92 |
+
masks = model.eval(image_uint8_gray, diameter=diameter, flow_threshold=flow_threshold, channels=[0, 0])[0]
|
| 93 |
+
if masks is None:
|
| 94 |
+
masks = np.zeros_like(image_uint8_gray, dtype=np.uint16)
|
| 95 |
+
masks_u16 = masks.astype(np.uint16)
|
| 96 |
+
# for grayscale save (not for coloring), normalize label map to 0-255 just to provide a quick PNG
|
| 97 |
+
masks_u8 = (masks_u16.astype(np.float32) / (masks_u16.max() + 1e-8) * 255).astype(np.uint8)
|
| 98 |
+
return masks_u16, masks_u8
|
| 99 |
+
|
| 100 |
+
def save_grayscale_mask_png(mask_u8):
|
| 101 |
+
out_path = os.path.join(tempfile.gettempdir(), "predicted_mask.png")
|
| 102 |
+
Image.fromarray(mask_u8).convert("L").save(out_path)
|
| 103 |
+
return out_path
|
| 104 |
+
|
| 105 |
+
# =========================
|
| 106 |
+
# Gamma preview
|
| 107 |
+
# =========================
|
| 108 |
def update_gamma_display(file, use_gamma, gamma_val):
|
| 109 |
if file is None:
|
| 110 |
return None
|
|
|
|
| 114 |
if use_gamma:
|
| 115 |
img = apply_gamma_correction(img, gamma_val)
|
| 116 |
else:
|
| 117 |
+
img = to_uint8_grayscale(img)
|
|
|
|
|
|
|
| 118 |
return img
|
| 119 |
|
| 120 |
+
# =========================
|
| 121 |
+
# Custom single run (nipy_spectral)
|
| 122 |
+
# =========================
|
| 123 |
+
def segment_custom(file, use_gamma, gamma_val, diameter, flow_threshold):
|
| 124 |
image = load_image_robust(file)
|
|
|
|
| 125 |
if image.ndim == 3:
|
| 126 |
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
|
|
|
| 127 |
if use_gamma:
|
| 128 |
+
image_u8 = apply_gamma_correction(image, gamma_val)
|
| 129 |
else:
|
| 130 |
+
image_u8 = to_uint8_grayscale(image)
|
| 131 |
+
|
| 132 |
+
mask_u16, mask_u8 = run_cellpose(image_u8, diameter=diameter, flow_threshold=flow_threshold)
|
| 133 |
+
# colorize with nipy_spectral
|
| 134 |
+
colored = colorize_with_matplotlib(mask_u16, cmap_name="nipy_spectral")
|
| 135 |
+
overlay = overlay_colored_mask_on_gray(image_u8, colored, alpha=0.5)
|
| 136 |
+
out_path = save_grayscale_mask_png(mask_u8)
|
| 137 |
+
return overlay, out_path
|
| 138 |
+
|
| 139 |
+
# =========================
|
| 140 |
+
# Automatic Grid run (3x3)
|
| 141 |
+
# =========================
|
| 142 |
+
DIAMS = [30, 60, 90]
|
| 143 |
+
FLOWS = [0.4, 0.7, 1.0]
|
| 144 |
+
|
| 145 |
+
def run_grid(file, use_gamma, gamma_val):
|
| 146 |
+
"""
|
| 147 |
+
Returns a list of (image, caption) tuples for a Gradio Gallery.
|
| 148 |
+
"""
|
| 149 |
+
if file is None:
|
| 150 |
+
return []
|
| 151 |
|
| 152 |
+
image = load_image_robust(file)
|
| 153 |
+
if image.ndim == 3:
|
| 154 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 155 |
+
if use_gamma:
|
| 156 |
+
image_u8 = apply_gamma_correction(image, gamma_val)
|
| 157 |
+
else:
|
| 158 |
+
image_u8 = to_uint8_grayscale(image)
|
| 159 |
+
|
| 160 |
+
gallery_items = []
|
| 161 |
+
for d in DIAMS:
|
| 162 |
+
for f in FLOWS:
|
| 163 |
+
mask_u16, _ = run_cellpose(image_u8, diameter=d, flow_threshold=f)
|
| 164 |
+
colored = colorize_with_matplotlib(mask_u16, cmap_name="nipy_spectral")
|
| 165 |
+
overlay = overlay_colored_mask_on_gray(image_u8, colored, alpha=0.5)
|
| 166 |
+
caption = f"diameter={d}, flow={f}"
|
| 167 |
+
gallery_items.append((overlay, caption))
|
| 168 |
+
return gallery_items
|
| 169 |
+
|
| 170 |
+
# =========================
|
| 171 |
+
# UI
|
| 172 |
+
# =========================
|
| 173 |
description = """
|
| 174 |
**CellPhase1.0** is developed and released by the **Center for Label-free Imaging and Multiscale Biophotonics**, Beckman Institute, University of Illinois Urbana-Champaign.
|
| 175 |
Supported by the **National Institute of Health/National Institute of Biomedical Imaging and Bioengineering**, Award #: **P41EB031772**.
|
|
|
|
| 181 |
**License**: Open Source – [MIT License](https://opensource.org/licenses/MIT)
|
| 182 |
"""
|
| 183 |
|
|
|
|
| 184 |
with gr.Blocks(title="CellPhase1.0 - Cell Segmentation Tool") as demo:
|
| 185 |
gr.Markdown(description)
|
| 186 |
|
|
|
|
| 193 |
|
| 194 |
gamma_preview = gr.Image(type="numpy", label="Gamma Corrected Image Preview")
|
| 195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
with gr.Column():
|
| 197 |
+
gr.Markdown("### 1) Automatic Segmentation (3×3 grid)")
|
| 198 |
+
auto_btn = gr.Button("Run Automatic Grid (diam=[30,60,90], flow=[0.4,0.7,1.0])")
|
| 199 |
+
grid_gallery = gr.Gallery(label="Grid Results", columns=3, preview=True, height=480)
|
| 200 |
|
| 201 |
+
# Live gamma preview updates
|
| 202 |
file_input.change(update_gamma_display, inputs=[file_input, use_gamma, gamma_slider], outputs=gamma_preview)
|
| 203 |
gamma_slider.change(update_gamma_display, inputs=[file_input, use_gamma, gamma_slider], outputs=gamma_preview)
|
| 204 |
use_gamma.change(update_gamma_display, inputs=[file_input, use_gamma, gamma_slider], outputs=gamma_preview)
|
| 205 |
|
| 206 |
+
# Automatic grid run
|
| 207 |
+
auto_btn.click(fn=run_grid, inputs=[file_input, use_gamma, gamma_slider], outputs=grid_gallery)
|
| 208 |
+
|
| 209 |
+
gr.Markdown("---")
|
| 210 |
+
gr.Markdown("### 2) Custom Segmentation (nipy_spectral overlay)")
|
| 211 |
+
|
| 212 |
+
with gr.Row():
|
| 213 |
+
with gr.Column():
|
| 214 |
+
diameter_slider = gr.Slider(10, 120, value=50, step=5, label="Diameter")
|
| 215 |
+
flow_slider = gr.Slider(0.2, 1.0, value=0.6, step=0.1, label="Flow Threshold")
|
| 216 |
+
run_btn = gr.Button("Run Custom Segmentation")
|
| 217 |
+
with gr.Column():
|
| 218 |
+
overlay_output = gr.Image(type="numpy", label="Custom Segmentation Overlay")
|
| 219 |
+
mask_output = gr.File(label="Download Grayscale Mask (.png)")
|
| 220 |
+
|
| 221 |
+
# Custom run
|
| 222 |
+
run_btn.click(
|
| 223 |
+
fn=segment_custom,
|
| 224 |
+
inputs=[file_input, use_gamma, gamma_slider, diameter_slider, flow_slider],
|
| 225 |
+
outputs=[overlay_output, mask_output],
|
| 226 |
+
)
|
| 227 |
|
| 228 |
if __name__ == "__main__":
|
| 229 |
+
# share=True is fine on Spaces (ignored), but helpful locally
|
| 230 |
demo.launch(share=True)
|