import gradio as gr import numpy as np import cv2 import os import tifffile import tempfile from PIL import Image from matplotlib import cm from cellpose import models # ========================= # Model (GPU off by default on Spaces CPU) # ========================= # If you enable a GPU hardware on the Space, set gpu=True model = models.CellposeModel(pretrained_model="cellpose_train_folder_qpi_live_0520", gpu=False) # ========================= # Utils # ========================= def _get_path_from_gradio_file(file_obj): """ Gradio File may come as: - dict with 'name' and 'path' - str path - tempfile.NamedTemporaryFile / file-like with .name Return a filesystem path. """ if file_obj is None: return None if isinstance(file_obj, dict): p = file_obj.get("path") or file_obj.get("name") return p if isinstance(file_obj, str): return file_obj return getattr(file_obj, "name", None) def load_image_from_path(path): if path is None or not os.path.exists(path): raise ValueError("Image path not found.") ext = os.path.splitext(path)[-1].lower() if ext in [".tif", ".tiff"]: image = tifffile.imread(path) else: image = cv2.imread(path, cv2.IMREAD_UNCHANGED) if image is None: raise ValueError("Failed to load the image.") return image def to_uint8_grayscale(img): img = img.astype(np.float32) img = img - img.min() img = img / (img.max() + 1e-8) return (img * 255).astype(np.uint8) def apply_gamma_correction(image, gamma): image = image.astype(np.float32) image = image - image.min() image = image / (image.max() + 1e-8) image = np.power(image, gamma) image = (image * 255).astype(np.uint8) return image def colorize_with_matplotlib(mask_labels, cmap_name="nipy_spectral"): """ Colorize an integer-labeled mask using a matplotlib colormap. The result is RGB uint8. """ m = mask_labels.astype(np.float32) maxv = np.max(m) if maxv <= 0: rgb = np.zeros((*m.shape, 3), dtype=np.uint8) return rgb norm = m / (maxv + 1e-8) cmap = cm.get_cmap(cmap_name) rgba = cmap(norm) # float RGBA in [0,1] rgb = (rgba[..., :3] * 255).astype(np.uint8) return rgb def overlay_colored_mask_on_gray(gray_uint8, colored_mask_uint8, alpha=0.5): gray_rgb = cv2.cvtColor(gray_uint8, cv2.COLOR_GRAY2BGR) overlay = cv2.addWeighted(gray_rgb, 1 - alpha, colored_mask_uint8, alpha, 0) return overlay def run_cellpose(image_uint8_gray, diameter, flow_threshold): """ Run Cellpose and return the labeled mask (uint16) and a normalized 0-255 mask (uint8) for saving. """ masks = model.eval(image_uint8_gray, diameter=diameter, flow_threshold=flow_threshold, channels=[0, 0])[0] if masks is None: masks = np.zeros_like(image_uint8_gray, dtype=np.uint16) masks_u16 = masks.astype(np.uint16) masks_u8 = (masks_u16.astype(np.float32) / (masks_u16.max() + 1e-8) * 255).astype(np.uint8) return masks_u16, masks_u8 def save_grayscale_mask_png(mask_u8): out_path = os.path.join(tempfile.gettempdir(), "predicted_mask.png") Image.fromarray(mask_u8).convert("L").save(out_path) return out_path # ========================= # Preview helpers (use img_path_state) # ========================= def preview_from_state(img_path, use_gamma, gamma_val): if not img_path: return None img = load_image_from_path(img_path) if img.ndim == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if use_gamma: return apply_gamma_correction(img, gamma_val) return to_uint8_grayscale(img) def set_state_from_upload(file_obj, use_gamma, gamma_val): """ Called when a user uploads a file. Returns (img_path_state, preview) """ path = _get_path_from_gradio_file(file_obj) if not path: return None, None try: prev = preview_from_state(path, use_gamma, gamma_val) except Exception: prev = None # IMPORTANT: we do NOT change the File component; Gradio handles showing the filename for uploads. return path, prev # ========================= # Custom & Grid using state # ========================= def segment_custom_state(img_path, use_gamma, gamma_val, diameter, flow_threshold): if not img_path: return None, None image = load_image_from_path(img_path) if image.ndim == 3: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if use_gamma: image_u8 = apply_gamma_correction(image, gamma_val) else: image_u8 = to_uint8_grayscale(image) mask_u16, mask_u8 = run_cellpose(image_u8, diameter=diameter, flow_threshold=flow_threshold) colored = colorize_with_matplotlib(mask_u16, cmap_name="nipy_spectral") overlay = overlay_colored_mask_on_gray(image_u8, colored, alpha=0.5) out_path = save_grayscale_mask_png(mask_u8) return overlay, out_path DIAMS = [30, 60, 90] FLOWS = [0.4, 0.7, 1.0] def run_grid_state(img_path, use_gamma, gamma_val): if not img_path: return [] image = load_image_from_path(img_path) if image.ndim == 3: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if use_gamma: image_u8 = apply_gamma_correction(image, gamma_val) else: image_u8 = to_uint8_grayscale(image) gallery_items = [] for d in DIAMS: for f in FLOWS: mask_u16, _ = run_cellpose(image_u8, diameter=d, flow_threshold=f) colored = colorize_with_matplotlib(mask_u16, cmap_name="nipy_spectral") overlay = overlay_colored_mask_on_gray(image_u8, colored, alpha=0.5) caption = f"diameter={d}, flow={f}" gallery_items.append((overlay, caption)) return gallery_items # ========================= # Example Images (Click to load and segment with diameter and flow values shown below) # ========================= EXAMPLE_META = [ ("crl_112_img.png", "Cell: SW480 (QPI)
System: Omnimesoscope
(diam, flow) = (60, 1.0)"), ("psi_train_00021_img.png", "Cell: Mouse L cells (QPI)
System: Michelson interferometer
(diam, flow) = (40, 0.9)"), ("13d_128_img.png", "Cell: SW480 (QPI)
System: Omnimesoscope
(diam, flow) = (60, 0.7)"), ("zangle_0506_00641_img.png", "Cell: MDA-MB-231 (QPI)
System: DPC
(diam, flow) = (60, 0.5)"), ("zangle_0520_00221_img.png", "Cell: MCF-7 (QPI)
System: DPC
(diam, flow) = (60, 0.9)"), ] def _abs_path(fname: str) -> str: base = os.path.dirname(__file__) return os.path.join(base, fname) EXAMPLE_FILES = [_abs_path(fname) for (fname, _cap) in EXAMPLE_META] def load_example_by_index(idx, use_gamma, gamma_val): """ On example click: set state + preview, DO NOT touch the File input. """ if idx < 0 or idx >= len(EXAMPLE_FILES): return None, None path = EXAMPLE_FILES[idx] try: prev = preview_from_state(path, use_gamma, gamma_val) except Exception: prev = None return path, prev # (img_path_state, preview) # wrappers per example (easy wiring) def load_ex1(use_gamma, gamma_val): return load_example_by_index(0, use_gamma, gamma_val) def load_ex2(use_gamma, gamma_val): return load_example_by_index(1, use_gamma, gamma_val) def load_ex3(use_gamma, gamma_val): return load_example_by_index(2, use_gamma, gamma_val) def load_ex4(use_gamma, gamma_val): return load_example_by_index(3, use_gamma, gamma_val) def load_ex5(use_gamma, gamma_val): return load_example_by_index(4, use_gamma, gamma_val) # ========================= # UI # ========================= description = """

CellPhase1.0 — Whole-Cell Segmentation for QPI

Note:
CellPhase1.0 is developed and released by the Center for Label-free Imaging and Multiscale Biophotonics, Beckman Institute, University of Illinois Urbana-Champaign.
Supported by the National Institute of Health/National Institute of Biomedical Imaging and Bioengineering, Award #: P41EB031772.

Model: CellPhase1.0
Input: QPI
Output: Whole-cell segmentation mask and overlay visualization

Parameters: Tune Diameter and Flow Threshold to get the best results

Steps:
1. Run Automatic Segmentation with the following parameter combinations:
    Diameter = [30, 60, 90]   |   Flow Threshold = [0.4, 0.7, 1.0] (Total: 9 combinations)
2. Use Custom Segmentation: Tune your own diameter and flow threshold using the sliders, then view results.
3. Download results if needed.
4. Explore Example Images to see how the tool works with different cell types and imaging systems.

Note:
This is the first version, trained on diverse cell types and QPI imaging systems. We aim to improve this with further collaboration and community support.

License: MIT License

For inquiries, contact: Sourya Sengupta souryas2@illinois.edu

""" with gr.Blocks(title="CellPhase1.0 - Cell Segmentation Tool") as demo: gr.HTML(description) # hidden state: the currently selected image path (from upload OR example) img_path_state = gr.State(value=None) with gr.Row(): with gr.Column(): # File uploader (uploads MAY show filename; that's desired) file_input = gr.File(label="Upload Cell Image", file_types=[".jpg", ".jpeg", ".png", ".tif", ".tiff"]) use_gamma = gr.Checkbox(label="Use Gamma Correction", value=False) gamma_slider = gr.Slider(0.2, 2.5, value=1.0, step=0.1, label="Gamma Value") gamma_preview = gr.Image(type="numpy", label="Gamma Corrected Image Preview") with gr.Column(): gr.Markdown("### 1) Automatic Segmentation") auto_btn = gr.Button("Run Automatic Segmentation with Different Diameter and Flow") grid_gallery = gr.Gallery(label="Grid Results", columns=3, preview=True, height=480) # When a user uploads a file: update STATE + preview (filename remains visible in File) file_input.change( fn=set_state_from_upload, inputs=[file_input, use_gamma, gamma_slider], outputs=[img_path_state, gamma_preview], ) # Recompute preview from STATE when gamma controls change gamma_slider.change(preview_from_state, inputs=[img_path_state, use_gamma, gamma_slider], outputs=gamma_preview) use_gamma.change(preview_from_state, inputs=[img_path_state, use_gamma, gamma_slider], outputs=gamma_preview) # Automatic grid uses STATE auto_btn.click(fn=run_grid_state, inputs=[img_path_state, use_gamma, gamma_slider], outputs=grid_gallery) gr.Markdown("---") gr.Markdown("### 2) Custom Segmentation") with gr.Row(): with gr.Column(): diameter_slider = gr.Slider(10, 120, value=50, step=5, label="Diameter") flow_slider = gr.Slider(0.2, 1.0, value=0.6, step=0.1, label="Flow Threshold") run_btn = gr.Button("Run Custom Segmentation") with gr.Column(): overlay_output = gr.Image(type="numpy", label="Custom Segmentation Overlay") mask_output = gr.File(label="Download Grayscale Mask (.png)") # Custom run uses STATE run_btn.click( fn=segment_custom_state, inputs=[img_path_state, use_gamma, gamma_slider, diameter_slider, flow_slider], outputs=[overlay_output, mask_output], ) gr.Markdown("---") gr.Markdown("### Example Images (Details shown below each image)") with gr.Row(): # 5 side-by-side panels (image + caption + button) for idx, (fname, caption_html) in enumerate(EXAMPLE_META): with gr.Column(): img_comp = gr.Image(value=_abs_path(fname), label=f"Example {idx+1}", interactive=False) gr.Markdown(caption_html) btn = gr.Button("Use this example") # clicking a button sets STATE + preview; DOES NOT touch the File input if idx == 0: btn.click(load_ex1, inputs=[use_gamma, gamma_slider], outputs=[img_path_state, gamma_preview]) elif idx == 1: btn.click(load_ex2, inputs=[use_gamma, gamma_slider], outputs=[img_path_state, gamma_preview]) elif idx == 2: btn.click(load_ex3, inputs=[use_gamma, gamma_slider], outputs=[img_path_state, gamma_preview]) elif idx == 3: btn.click(load_ex4, inputs=[use_gamma, gamma_slider], outputs=[img_path_state, gamma_preview]) else: btn.click(load_ex5, inputs=[use_gamma, gamma_slider], outputs=[img_path_state, gamma_preview]) if __name__ == "__main__": # share=True is fine on Spaces (ignored there), helpful locally demo.launch(share=True)