Delete app (2).py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689import gradio as grimport spacesfrom cellpose import modelsimport numpy as npimport cv2import matplotlib.pyplot as pltimport tempfilefrom PIL import Image, ImageDrawimport iofrom huggingface_hub import hf_hub_downloadimport base64
HF_REPO_ID = "myang4218/cellposemodel"MODEL_OPTIONS = { "Hemocytometer Model": "hemocytometermodel.npy", "General Model": "generalmodel.npy"}
loaded_models = {}
MAX_SIDE = 1024 MAX_PIXELS = 1024 * 1024
def safe_resize(image_np): h, w = image_np.shape[:2] total = h * w
if max(h, w) <= MAX_SIDE and total <= MAX_PIXELS: return image_np
# compute scale scale_side = MAX_SIDE / max(h, w) scale_pixels = (MAX_PIXELS / total) ** 0.5 scale = min(scale_side, scale_pixels)
new_w = max(1, int(w * scale)) new_h = max(1, int(h * scale))
return cv2.resize(image_np, (new_w, new_h), interpolation=cv2.INTER_AREA)
def draw_exclusion_overlay(image_np, left_width_pct, top_width_pct): h, w = image_np.shape[:2] # Convert to PIL img_pil = Image.fromarray(image_np) draw = ImageDraw.Draw(img_pil, 'RGBA')
left_px = int(w * left_width_pct / 100) top_px = int(h * top_width_pct / 100) # Draw overlays for exclusion zones if left_px > 0: draw.rectangle( [(0, 0), (left_px, h)], fill=(255, 0, 0, 80) ) # border line draw.line([(left_px, 0), (left_px, h)], fill=(255, 0, 0, 255), width=3) if top_px > 0: draw.rectangle( [(0, 0), (w, top_px)], fill=(255, 0, 0, 80) ) # border line draw.line([(0, top_px), (w, top_px)], fill=(255, 0, 0, 255), width=3) return np.array(img_pil)
def apply_stereological_exclusion(masks, left_width_pct, top_width_pct): h, w = masks.shape left_px = int(w * left_width_pct / 100) top_px = int(h * top_width_pct / 100) filtered_masks = masks.copy() cell_ids = np.unique(masks) cell_ids = cell_ids[cell_ids > 0] excluded_cells = [] included_cells = [] for cell_id in cell_ids: cell_mask = (masks == cell_id) # Get cell boundary coordinates rows, cols = np.where(cell_mask) touches_left = np.any(cols < left_px) if left_px > 0 else False touches_top = np.any(rows < top_px) if top_px > 0 else False if touches_left or touches_top: filtered_masks[cell_mask] = 0 excluded_cells.append(cell_id) else: included_cells.append(cell_id) unique_ids = np.unique(filtered_masks) unique_ids = unique_ids[unique_ids > 0] renumbered_masks = np.zeros_like(filtered_masks) for new_id, old_id in enumerate(unique_ids, start=1): renumbered_masks[filtered_masks == old_id] = new_id return renumbered_masks, len(excluded_cells), len(included_cells)
def classify_cells_by_blueness(image_np, masks, blue_threshold): if len(image_np.shape) == 2: image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB) elif len(image_np.shape) == 3 and image_np.shape[2] == 4: image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
hsv = cv2.cvtColor(image_np, cv2.COLOR_RGB2HSV)
# Calculate blueness index for each pixel hue = hsv[:, :, 0].astype(np.float32) saturation = hsv[:, :, 1].astype(np.float32)
# Hue score: peaks around 115 , drops off towards edges # Handle hue wrap-around for blue detection (100-130 range) hue_distance = np.minimum(np.abs(hue - 115), 180 - np.abs(hue - 115)) hue_score = np.maximum(0, 1 - hue_distance / 65) # 65 good blue range
# blueness metric blueness = hue_score * (saturation / 255.0)
# Convert threshold from 0-100 to 0-1 scale threshold = blue_threshold / 100.0
# Get unique cell IDs cell_ids = np.unique(masks) cell_ids = cell_ids[cell_ids > 0]
dead_cells = [] alive_cells = []
# Classify each cell for cell_id in cell_ids: cell_mask = (masks == cell_id) cell_blueness = np.mean(blueness[cell_mask])
if cell_blueness > threshold: dead_cells.append(cell_id) else: alive_cells.append(cell_id)
# Create colored overlay overlay = image_np.copy().astype(np.float32) # Ensure float for blending
# Color dead cells red, alive cells green for cell_id in dead_cells: cell_mask = (masks == cell_id) overlay[cell_mask] = [255, 0, 0]
for cell_id in alive_cells: cell_mask = (masks == cell_id) overlay[cell_mask] = [0, 255, 0]
# Blend with original image alpha = 0.4 final_overlay = (1 - alpha) * image_np.astype(np.float32) + alpha * overlay final_overlay = np.clip(final_overlay, 0, 255).astype(np.uint8)
return len(dead_cells), len(alive_cells), final_overlay
def measure_confluency(masks, image_np): tot_pixels = image_np.shape[0] * image_np.shape[1] cell_pixels = np.count_nonzero(masks) confluency = cell_pixels / tot_pixels * 100 return confluency def filter_mask_by_size(masks, minimum_pixels): filtered_masks = masks.copy() cell_ids = np.unique(masks) cell_ids = cell_ids[cell_ids > 0]
removed_count = 0 for cell_id in cell_ids: cell_mask = (masks == cell_id) cell_pixels = np.count_nonzero(cell_mask) if cell_pixels < minimum_pixels: filtered_masks[cell_mask] = 0 removed_count += 1
unique_ids = np.unique(filtered_masks) unique_ids = unique_ids[unique_ids > 0]
renumbered_masks = np.zeros_like(filtered_masks) for new_id, old_id in enumerate(unique_ids, start=1): renumbered_masks[filtered_masks == old_id] = new_id
return renumbered_masks, removed_count
def filter_mask_by_maxsize(masks, maximum_pixels): filtered_masks = masks.copy() cell_ids = np.unique(masks) cell_ids = cell_ids[cell_ids > 0]
removed_count = 0 for cell_id in cell_ids: cell_mask = (masks == cell_id) cell_pixels = np.count_nonzero(cell_mask) if cell_pixels > maximum_pixels: filtered_masks[cell_mask] = 0 removed_count += 1
unique_ids = np.unique(filtered_masks) unique_ids = unique_ids[unique_ids > 0]
renumbered_masks = np.zeros_like(filtered_masks) for new_id, old_id in enumerate(unique_ids, start=1): renumbered_masks[filtered_masks == old_id] = new_id
return renumbered_masks, removed_count
def rec_min_size(masks, q=25): ids = np.unique(masks) ids = ids[ids > 0] if len(ids) == 0: return 0 sizes = np.array([np.count_nonzero(masks == cid) for cid in ids]) return int(round(np.percentile(sizes, q)))
def toggle_stereological_mode(use_stereology): """Show/hide stereological controls based on checkbox""" return gr.update(visible=use_stereology)
def update_exclusion_preview(image, left_width, top_width): """Update the preview image with exclusion zone overlay""" if image is None: return None image_np = np.array(image) overlay = draw_exclusion_overlay(image_np, left_width, top_width) return Image.fromarray(overlay)
@spaces.GPUdef run_segmentation(image, model_choice, min_cell_size, max_cell_size, use_stereology, left_exclusion, top_exclusion): image_np = np.array(image) image_np = safe_resize(image_np) try: model_filename = MODEL_OPTIONS[model_choice] model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=model_filename)
if model_filename in loaded_models: model = loaded_models[model_filename] else: model = models.CellposeModel(gpu=True, pretrained_model=model_path) loaded_models[model_filename] = model
# Process image format to RGB if len(image_np.shape) == 2: processed_image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB) elif len(image_np.shape) == 3 and image_np.shape[2] == 4: processed_image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB) else: processed_image_np = image_np
# Run Cellpose segmentation masks_raw, flows, styles = model.eval(processed_image_np, diameter=None, channels=[0, 0])
ids = np.unique(masks_raw) ids = ids[ids > 0]
sizes = np.array([np.count_nonzero(masks_raw == cid) for cid in ids])
print("num_cells:", len(ids)) print("mean:", sizes.mean() if len(sizes) > 0 else 0) print("median:", np.median(sizes) if len(sizes) > 0 else 0) print("p90:", np.percentile(sizes, 90) if len(sizes) > 0 else 0) print("max:", sizes.max() if len(sizes) > 0 else 0) # Compute recommendation from RAW masks recommend_min = rec_min_size(masks_raw)
# If user sets slider to 0, use the recommendation min_used = recommend_min if (min_cell_size == 0) else int(min_cell_size)
# Apply filters masks = masks_raw.copy() removed_small = 0 removed_large = 0
if min_used > 0: masks, removed_small = filter_mask_by_size(masks, min_used)
if max_cell_size > 0: masks, removed_large = filter_mask_by_maxsize(masks, int(max_cell_size))
# Apply stereological exclusion if enabled excluded_count = 0 if use_stereology: masks, excluded_count, included_count = apply_stereological_exclusion( masks, left_exclusion, top_exclusion ) filter_msg = "" if removed_small: filter_msg += f"Removed {removed_small} small objects (< {min_used} pixels).\n" if removed_large: filter_msg += f"Removed {removed_large} large objects (> {int(max_cell_size)} pixels).\n" if use_stereology and excluded_count > 0: filter_msg += f"Stereological exclusion: {excluded_count} cells excluded (touching left/top zones).\n"
cell_count = len(np.unique(masks)) - 1 confluency = measure_confluency(masks, processed_image_np)
# Create segmentation overlay (without viability) segmentation_overlay = processed_image_np.copy().astype(np.float32) if masks.max() > 0: np.random.seed(42) colors = np.random.randint(0, 255, size=(masks.max() + 1, 3)) colors[0] = [0, 0, 0] colored_mask = colors[masks] alpha = 0.4 segmentation_overlay = (1 - alpha) * segmentation_overlay + alpha * colored_mask segmentation_overlay = np.clip(segmentation_overlay, 0, 255).astype(np.uint8) # Add exclusion zone overlay if stereology is enabled if use_stereology: segmentation_overlay = draw_exclusion_overlay(segmentation_overlay, left_exclusion, top_exclusion)
info_msg = "" if filter_msg: info_msg += filter_msg info_msg += f"Segmentation complete! Found {cell_count} cells.\n" info_msg += f"Confluency: {confluency:.1f}%\n" if use_stereology: info_msg += f"Stereological counting enabled (Left: {left_exclusion}%, Top: {top_exclusion}%)\n" info_msg += "Now adjust the Blue Threshold for viability assessment."
return ( cell_count, Image.fromarray(segmentation_overlay), info_msg, gr.update(visible=True), pack_array(masks), pack_array(processed_image_np), confluency, gr.update(value=recommend_min), # update slider display to recommended )
except Exception as e: import traceback traceback.print_exc() return ( 0, None, f"Error during segmentation: {str(e)}", gr.update(visible=False), None, None, 0.0, gr.update(), )
def update_viability_realtime(blue_threshold, stored_masks, stored_image_np): # avoid unpacking None (e.g. slider moved before segmentation) if stored_masks is None or stored_image_np is None: return None, 0, 0, 0.0, "Please run segmentation first."
stored_masks = unpack_array(stored_masks) stored_image_np = unpack_array(stored_image_np)
try: dead_count, alive_count, viability_overlay_np = classify_cells_by_blueness( stored_image_np, stored_masks, blue_threshold )
total_count = alive_count + dead_count viability_percent = (alive_count / total_count * 100) if total_count > 0 else 0.0 confluency = measure_confluency(stored_masks, stored_image_np)
overlay_image = Image.fromarray(viability_overlay_np) info_msg = f"Total cells: {total_count}\nLive (green): {alive_count}\nDead (red): {dead_count}\n" info_msg += f"Viability: {viability_percent:.1f}%\nConfluency: {confluency:.1f}%\nBlue threshold: {blue_threshold}%"
return overlay_image, alive_count, dead_count, viability_percent, info_msg
except Exception as e: return None, 0, 0, 0.0, f"Error updating viability: {str(e)}"
def pack_array(arr): pil = Image.fromarray(arr.astype(np.uint8)) buf = io.BytesIO() pil.save(buf, format="PNG") return buf.getvalue()
def unpack_array(data): return np.array(Image.open(io.BytesIO(data)))
def save_tab_result(cell_count, confluency, viab_percent): """Package per-tab results into a dict for Tab 5 summary.""" return { "cell_count": float(cell_count) if cell_count is not None else None, "confluency": float(confluency) if confluency is not None else None, "viab_percent": float(viab_percent) if viab_percent is not None else None, }
def compute_summary(r1, r2, r3, r4): """Average cell count, confluency, and viability across tabs that have data.""" all_results = [r1, r2, r3, r4] valid = [(i + 1, r) for i, r in enumerate(all_results) if r is not None and r.get("cell_count") is not None]
if not valid: return ( 0.0, 0.0, 0.0, "No data yet — run segmentation in at least one tab, then click Refresh Summary." )
avg_count = sum(r["cell_count"] for _, r in valid) / len(valid) avg_conf = sum(r["confluency"] for _, r in valid) / len(valid) avg_viab = sum(r["viab_percent"] for _, r in valid) / len(valid)
lines = [f"Tab {tab_num}: {r['cell_count']:.0f} cells | " f"{r['confluency']:.1f}% confluency | " f"{r['viab_percent']:.1f}% viability" for tab_num, r in valid] lines.append(f"\nAverages ({len(valid)} tab{'s' if len(valid) > 1 else ''}):") lines.append(f" Cell count: {avg_count:.1f}") lines.append(f" Confluency: {avg_conf:.1f}%") lines.append(f" Viability: {avg_viab:.1f}%")
return avg_count, avg_conf, avg_viab, "\n".join(lines)
def build_tab(tab_index, masks_state, image_state, result_state): with gr.Tab(f"Tab {tab_index}"): gr.Markdown("Run segmentation")
with gr.Row(): with gr.Column(): img_input = gr.Image( type="pil", label="Microscopy image", image_mode="RGB", height=512 )
model_dropdown = gr.Dropdown( choices=list(MODEL_OPTIONS.keys()), label="Select Model", value="Hemocytometer Model" )
min_size_slider = gr.Slider( minimum=0, maximum=500, value=0, step=10, label="Minimum Cell Size (pixels). Leave at zero for automated recommendation", )
max_size_slider = gr.Slider( minimum=0, maximum=10000, value=10000, step=10, label="Maximum Cell Size (pixels)", )
gr.Markdown("### Stereological Counting") use_stereo = gr.Checkbox( label="Enable Stereological Counting", value=False, info="Use unbiased stereological rules for cell counting" )
with gr.Group(visible=False) as stereo_controls: gr.Markdown(""" **Stereological Counting Rules:** - Cells touching LEFT or TOP exclusion zones are EXCLUDED - Cells touching RIGHT or BOTTOM edges are INCLUDED - This provides unbiased counting for quantification """)
excl_preview = gr.Image( type="pil", label="Exclusion Zone Preview (Red = Excluded)", height=500 )
left_excl = gr.Slider( minimum=0, maximum=50, value=10, step=1, label="Left Exclusion Width (%)", info="Width of left exclusion zone" )
top_excl = gr.Slider( minimum=0, maximum=50, value=10, step=1, label="Top Exclusion Width (%)", info="Width of top exclusion zone" )
segment_btn = gr.Button("🔬 Run Segmentation", variant="primary", size="lg")
with gr.Column(): cell_count_out = gr.Number(label="Total Cells Detected", precision=0) confluency_out = gr.Number(label="Confluency (%)", precision=1) overlay_out = gr.Image(type="pil", label="Segmentation Result") info_out = gr.Textbox(label="Processing Info", lines=4)
with gr.Group(visible=False) as viability_section: gr.Markdown("### Viability Assessment (Trypan Blue)") gr.Markdown("Adjust the threshold to classify cells as live (green) or dead (red).")
with gr.Row(): with gr.Column(): blue_thresh = gr.Slider( minimum=0, maximum=100, value=25, step=1, label="Blue Threshold (%)", info="Higher values = more selective for blue cells" ) with gr.Column(): live_count_out = gr.Number(label="Live Cells (Green)", precision=0) dead_count_out = gr.Number(label="Dead Cells (Red)", precision=0)
viab_overlay = gr.Image(type="pil", label="Viability Assessment (Green=Live, Red=Dead)") viab_percent_out = gr.Number(label="Viability (%)", precision=1) viab_info = gr.Textbox(label="Analysis Results", lines=5)
# Event handlers
use_stereo.change( fn=toggle_stereological_mode, inputs=[use_stereo], outputs=[stereo_controls] )
img_input.change( fn=update_exclusion_preview, inputs=[img_input, left_excl, top_excl], outputs=[excl_preview] ) left_excl.change( fn=update_exclusion_preview, inputs=[img_input, left_excl, top_excl], outputs=[excl_preview] ) top_excl.change( fn=update_exclusion_preview, inputs=[img_input, left_excl, top_excl], outputs=[excl_preview] )
segment_btn.click( fn=run_segmentation, inputs=[img_input, model_dropdown, min_size_slider, max_size_slider, use_stereo, left_excl, top_excl], outputs=[cell_count_out, overlay_out, info_out, viability_section, masks_state, image_state, confluency_out, min_size_slider] ).then( fn=update_viability_realtime, inputs=[blue_thresh, masks_state, image_state], outputs=[viab_overlay, live_count_out, dead_count_out, viab_percent_out, viab_info] ).then( # Save this tab's results into its dedicated state for Tab 5 fn=save_tab_result, inputs=[cell_count_out, confluency_out, viab_percent_out], outputs=[result_state] )
blue_thresh.change( fn=update_viability_realtime, inputs=[blue_thresh, masks_state, image_state], outputs=[viab_overlay, live_count_out, dead_count_out, viab_percent_out, viab_info] ).then( # Keep result state in sync when threshold is adjusted fn=save_tab_result, inputs=[cell_count_out, confluency_out, viab_percent_out], outputs=[result_state] )
with gr.Blocks( title="CellposeCellCounter", theme=gr.themes.Soft(),) as demo: gr.Markdown("# CellposeCellCounter") gr.Markdown("For accurate cell confluency, crop the image to display only desired area. Note that some image file types are not yet supported. PNG and JPEG are preferred.")
# Shared mask/image state (one pair per tab so tabs don't clobber each other) masks_states = [gr.State(value=None) for _ in range(4)] image_states = [gr.State(value=None) for _ in range(4)] result_states = [gr.State(value=None) for _ in range(4)]
# Build Tabs 1–4 with a loop for i in range(4): build_tab(i + 1, masks_states[i], image_states[i], result_states[i])
# Tab 5 with gr.Tab("Tab 5 — Summary"): gr.Markdown("## Average Results Across All Tabs") gr.Markdown( "Run segmentation (and optionally adjust the blue threshold) in one or more tabs, " "then click **Refresh Summary** to see the averages." )
refresh_btn = gr.Button("Refresh Summary", variant="primary", size="lg")
with gr.Row(): avg_count_out = gr.Number(label="Avg Cell Count", precision=1) avg_conf_out = gr.Number(label="Avg Confluency (%)", precision=1) avg_viab_out = gr.Number(label="Avg Viability (%)", precision=1)
summary_box = gr.Textbox(label="Per-Tab Breakdown", lines=10)
refresh_btn.click( fn=compute_summary, inputs=result_states, # list of 4 gr.State components outputs=[avg_count_out, avg_conf_out, avg_viab_out, summary_box] )
# Instructions with gr.Accordion("Instructions", open=False): gr.Markdown(""" ### How to use:
1. **Upload and Segment**: - Upload your microscopy image. - Select a Cellpose model (e.g., "Hemocytometer Model" for suspension culture). - **(Optional)** Enable Stereological Counting for unbiased quantification. - Click "Run Segmentation".
2. **Stereological Counting** (Optional): - Check "Enable Stereological Counting" to use unbiased counting rules. - Adjust the Left and Top exclusion zone widths using the sliders. - Preview shows excluded areas in red. - **Counting Rules**: - Cells touching LEFT or TOP exclusion zones are EXCLUDED - Cells touching RIGHT or BOTTOM edges are INCLUDED - This ensures unbiased, systematic counting
3. **Analysis Results**: - **Cell Count**: Total number of detected cells (after exclusions if using stereology) - **Confluency**: Percentage of image area covered by cells
4. **Real-time Viability Assessment (Trypan Blue)**: - After segmentation, the viability section will become visible. - Adjust the **"Blue Threshold (%)"** slider in real-time. - **Lower values (10-20%)** are more sensitive. - **Higher values (30-50%)** are more selective. - Green cells = Live, Red cells = Dead.
5. **Summary (Tab 5)**: - After running segmentation in one or more tabs, switch to **Tab 5**. - Click **Refresh Summary** to compute averages across all completed tabs. - Displays average cell count, confluency, and viability, plus a per-tab breakdown.
6. **Interpreting Results**: - The app displays total, live, and dead cell counts, viability percentage, and confluency. - If stereological counting is enabled, excluded cells are noted in the processing info. """)
if __name__ == "__main__": demo.launch()app (2).pyDeleted-689