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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ from cellpose import models
4
+ import numpy as np
5
+ import cv2
6
+ import matplotlib.pyplot as plt
7
+ import tempfile
8
+ from PIL import Image
9
+ import io
10
+ from huggingface_hub import hf_hub_download
11
+
12
+ HF_REPO_ID = "myang4218/cellposemodel"
13
+ MODEL_OPTIONS = {
14
+ "Hemocytometer Model": "hemocytometermodel.npy",
15
+ "General Model": "generalmodel.npy"
16
+ }
17
+
18
+ loaded_models = {}
19
+
20
+ # Global variables to store segmentation results for real-time viability assessment
21
+ current_masks = None
22
+ current_image = None
23
+ current_region_coords = None
24
+
25
+ def debug_editor_data(editor_data):
26
+ """Debug function to understand the structure of ImageEditor data"""
27
+ if editor_data is None:
28
+ return "No data provided"
29
+
30
+ info = f"Type: {type(editor_data)}\n"
31
+
32
+ if isinstance(editor_data, dict):
33
+ info += f"Keys: {list(editor_data.keys())}\n"
34
+ for key, value in editor_data.items():
35
+ info += f" {key}: {type(value)}\n"
36
+ if key == 'layers' and value:
37
+ info += f" Layers count: {len(value)}\n"
38
+ for i, layer in enumerate(value):
39
+ info += f" Layer {i}: {type(layer)}\n"
40
+ if hasattr(layer, 'size'):
41
+ info += f" Size: {layer.size}\n"
42
+ info += f" Mode: {layer.mode}\n"
43
+ else:
44
+ if hasattr(editor_data, 'size'):
45
+ info += f"Size: {editor_data.size}\n"
46
+ info += f"Mode: {editor_data.mode}\n"
47
+
48
+ return info
49
+
50
+ def extract_region_from_editor(editor_data):
51
+ """Extract the selected region from ImageEditor data"""
52
+ if editor_data is None:
53
+ return None, None
54
+
55
+ if isinstance(editor_data, dict):
56
+ background = editor_data.get('background')
57
+ layers = editor_data.get('layers', [])
58
+
59
+ if background is None:
60
+ return None, None
61
+
62
+ background_np = np.array(background)
63
+
64
+ if layers and len(layers) > 0:
65
+ selection_layer = layers[0]
66
+ selection_np = np.array(selection_layer)
67
+
68
+ if len(selection_np.shape) == 3:
69
+ if selection_np.shape[2] == 4: # RGBA
70
+ mask = selection_np[:, :, 3] > 0
71
+ else: # RGB
72
+ mask = np.any(selection_np > 0, axis=2)
73
+ else:
74
+ mask = selection_np > 0
75
+
76
+ coords = np.where(mask)
77
+ if len(coords[0]) > 0:
78
+ y_min, y_max = coords[0].min(), coords[0].max()
79
+ x_min, x_max = coords[1].min(), coords[1].max()
80
+
81
+ pad = 5
82
+ h, w = background_np.shape[:2]
83
+ y_min = max(0, y_min - pad)
84
+ y_max = min(h, y_max + pad)
85
+ x_min = max(0, x_min - pad)
86
+ x_max = min(w, x_max + pad)
87
+
88
+ region = background_np[y_min:y_max+1, x_min:x_max+1]
89
+ return region, (x_min, y_min, x_max, y_max)
90
+
91
+ return background_np, None
92
+
93
+ else:
94
+ if hasattr(editor_data, 'size'):
95
+ image_np = np.array(editor_data)
96
+ return image_np, None
97
+ else:
98
+ return None, None
99
+
100
+ def calculate_blue_intensity(image_np, masks):
101
+ """Calculate blue intensity for each cell"""
102
+ if len(image_np.shape) == 2:
103
+ # Convert grayscale to RGB
104
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
105
+ elif len(image_np.shape) == 3 and image_np.shape[2] == 4:
106
+ # Handle RGBA
107
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
108
+
109
+ # Calculate blue intensity for each cell
110
+ cell_blue_intensities = {}
111
+ unique_cells = np.unique(masks)
112
+
113
+ for cell_id in unique_cells:
114
+ if cell_id == 0: # Skip background
115
+ continue
116
+
117
+ cell_mask = masks == cell_id
118
+ cell_pixels = image_np[cell_mask]
119
+
120
+ if len(cell_pixels) > 0:
121
+ # Calculate mean blue intensity (blue channel)
122
+ blue_intensity = np.mean(cell_pixels[:, 2]) # Blue channel is index 2
123
+ cell_blue_intensities[cell_id] = blue_intensity
124
+
125
+ return cell_blue_intensities
126
+
127
+ def create_viability_overlay(image_np, masks, blue_threshold):
128
+ """Create overlay showing live/dead cells based on blue threshold"""
129
+ global current_masks, current_image
130
+
131
+ if masks is None or image_np is None:
132
+ return None, 0, 0
133
+
134
+ # Calculate blue intensities
135
+ cell_blue_intensities = calculate_blue_intensity(image_np, masks)
136
+
137
+ # Create overlay
138
+ overlay = image_np.copy().astype(np.float32)
139
+
140
+ live_count = 0
141
+ dead_count = 0
142
+
143
+ # Color cells based on viability
144
+ for cell_id, blue_intensity in cell_blue_intensities.items():
145
+ cell_mask = masks == cell_id
146
+
147
+ if blue_intensity > blue_threshold:
148
+ # Dead cell - color in red
149
+ overlay[cell_mask] = [255, 0, 0] # Red
150
+ dead_count += 1
151
+ else:
152
+ # Live cell - color in green
153
+ overlay[cell_mask] = [0, 255, 0] # Green
154
+ live_count += 1
155
+
156
+ # Blend with original image
157
+ alpha = 0.5
158
+ overlay = (1 - alpha) * image_np + alpha * overlay
159
+ overlay = np.clip(overlay, 0, 255).astype(np.uint8)
160
+
161
+ return Image.fromarray(overlay), live_count, dead_count
162
+
163
+ @spaces.GPU
164
+ def segment_cells(editor_data, model_choice, crop_coords=None):
165
+ """
166
+ First stage: Segment cells and store results for viability assessment
167
+ """
168
+ global current_masks, current_image, current_region_coords
169
+
170
+ try:
171
+ debug_info = debug_editor_data(editor_data)
172
+
173
+ # Load the model
174
+ model_filename = MODEL_OPTIONS[model_choice]
175
+ model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=model_filename)
176
+
177
+ if model_filename in loaded_models:
178
+ model = loaded_models[model_filename]
179
+ else:
180
+ model = models.CellposeModel(gpu=True, pretrained_model=model_path)
181
+ loaded_models[model_filename] = model
182
+
183
+ # Extract region from editor
184
+ region_np, region_coords = extract_region_from_editor(editor_data)
185
+
186
+ if region_np is None:
187
+ return 0, None, f"No image provided. Debug info:\n{debug_info}", gr.update(visible=False)
188
+
189
+ # Handle manual crop coordinates
190
+ if crop_coords and crop_coords.strip():
191
+ try:
192
+ coords = [int(x.strip()) for x in crop_coords.split(',')]
193
+ if len(coords) == 4:
194
+ x_min, y_min, x_max, y_max = coords
195
+ h, w = region_np.shape[:2]
196
+ x_min = max(0, min(x_min, w-1))
197
+ y_min = max(0, min(y_min, h-1))
198
+ x_max = max(x_min+1, min(x_max, w))
199
+ y_max = max(y_min+1, min(y_max, h))
200
+
201
+ region_np = region_np[y_min:y_max, x_min:x_max]
202
+ region_coords = (x_min, y_min, x_max, y_max)
203
+ except ValueError:
204
+ pass
205
+
206
+ # Process image format
207
+ if len(region_np.shape) == 2:
208
+ region_np = cv2.cvtColor(region_np, cv2.COLOR_GRAY2RGB)
209
+ elif len(region_np.shape) == 3 and region_np.shape[2] == 4:
210
+ region_np = cv2.cvtColor(region_np, cv2.COLOR_RGBA2RGB)
211
+
212
+ # Run Cellpose segmentation
213
+ masks, flows, styles = model.eval(region_np, diameter=None, channels=[0, 0])
214
+
215
+ # Store results globally for viability assessment
216
+ current_masks = masks
217
+ current_image = region_np
218
+ current_region_coords = region_coords
219
+
220
+ # Count unique cells
221
+ cell_count = len(np.unique(masks)) - 1
222
+
223
+ # Create basic segmentation overlay
224
+ overlay = region_np.copy().astype(np.float32)
225
+
226
+ if masks.max() > 0:
227
+ np.random.seed(42)
228
+ colors = np.random.randint(0, 255, size=(masks.max() + 1, 3))
229
+ colors[0] = [0, 0, 0] # Background stays black
230
+
231
+ colored_mask = colors[masks]
232
+ alpha = 0.4
233
+ overlay = (1 - alpha) * overlay + alpha * colored_mask
234
+
235
+ overlay = np.clip(overlay, 0, 255).astype(np.uint8)
236
+ overlay_image = Image.fromarray(overlay)
237
+
238
+ info_msg = f"Segmentation complete! Found {cell_count} cells.\n"
239
+ if region_coords:
240
+ info_msg += f"Region: {region_coords}\n"
241
+ info_msg += f"Now use the blue threshold slider below for viability assessment."
242
+
243
+ # Make viability section visible
244
+ viability_section_update = gr.update(visible=True)
245
+
246
+ return cell_count, overlay_image, info_msg, viability_section_update
247
+
248
+ except Exception as e:
249
+ current_masks = None
250
+ current_image = None
251
+ current_region_coords = None
252
+ return 0, None, f"Error: {str(e)}", gr.update(visible=False)
253
+
254
+ def update_viability_assessment(blue_threshold):
255
+ """
256
+ Real-time viability assessment based on blue threshold
257
+ """
258
+ global current_masks, current_image
259
+
260
+ if current_masks is None or current_image is None:
261
+ return None, 0, 0, "Please run segmentation first"
262
+
263
+ try:
264
+ # Create viability overlay
265
+ viability_overlay, live_count, dead_count = create_viability_overlay(
266
+ current_image, current_masks, blue_threshold
267
+ )
268
+
269
+ total_count = live_count + dead_count
270
+ viability_info = f"Total cells: {total_count}\nLive (green): {live_count}\nDead (red): {dead_count}"
271
+
272
+ if total_count > 0:
273
+ viability_percentage = (live_count / total_count) * 100
274
+ viability_info += f"\nViability: {viability_percentage:.1f}%"
275
+
276
+ return viability_overlay, live_count, dead_count, viability_info
277
+
278
+ except Exception as e:
279
+ return None, 0, 0, f"Error in viability assessment: {str(e)}"
280
+
281
+ @spaces.GPU
282
+ def segment_with_coords(image, model_choice, crop_coords):
283
+ """Alternative function for manual coordinates input"""
284
+ global current_masks, current_image, current_region_coords
285
+
286
+ if image is None:
287
+ return 0, None, "No image provided", gr.update(visible=False)
288
+
289
+ try:
290
+ # Load the model
291
+ model_filename = MODEL_OPTIONS[model_choice]
292
+ model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=model_filename)
293
+
294
+ if model_filename in loaded_models:
295
+ model = loaded_models[model_filename]
296
+ else:
297
+ model = models.CellposeModel(gpu=True, pretrained_model=model_path)
298
+ loaded_models[model_filename] = model
299
+
300
+ # Convert PIL Image to numpy array
301
+ image_np = np.array(image)
302
+
303
+ # Apply crop if coordinates are provided
304
+ if crop_coords and crop_coords.strip():
305
+ try:
306
+ coords = [int(x.strip()) for x in crop_coords.split(',')]
307
+ if len(coords) == 4:
308
+ x_min, y_min, x_max, y_max = coords
309
+ h, w = image_np.shape[:2]
310
+ x_min = max(0, min(x_min, w-1))
311
+ y_min = max(0, min(y_min, h-1))
312
+ x_max = max(x_min+1, min(x_max, w))
313
+ y_max = max(y_min+1, min(y_max, h))
314
+
315
+ image_np = image_np[y_min:y_max, x_min:x_max]
316
+ current_region_coords = (x_min, y_min, x_max, y_max)
317
+ except ValueError:
318
+ pass
319
+
320
+ # Process image format
321
+ if len(image_np.shape) == 2:
322
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
323
+ elif len(image_np.shape) == 3 and image_np.shape[2] == 4:
324
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
325
+
326
+ # Run Cellpose
327
+ masks, flows, styles = model.eval(image_np, diameter=None, channels=[0, 0])
328
+
329
+ # Store results globally
330
+ current_masks = masks
331
+ current_image = image_np
332
+
333
+ # Count unique cells
334
+ cell_count = len(np.unique(masks)) - 1
335
+
336
+ # Create overlay
337
+ overlay = image_np.copy().astype(np.float32)
338
+
339
+ if masks.max() > 0:
340
+ np.random.seed(42)
341
+ colors = np.random.randint(0, 255, size=(masks.max() + 1, 3))
342
+ colors[0] = [0, 0, 0]
343
+
344
+ colored_mask = colors[masks]
345
+ alpha = 0.4
346
+ overlay = (1 - alpha) * overlay + alpha * colored_mask
347
+
348
+ overlay = np.clip(overlay, 0, 255).astype(np.uint8)
349
+ overlay_image = Image.fromarray(overlay)
350
+
351
+ info_msg = f"Segmentation complete! Found {cell_count} cells.\n"
352
+ info_msg += f"Now use the blue threshold slider below for viability assessment."
353
+
354
+ return cell_count, overlay_image, info_msg, gr.update(visible=True)
355
+
356
+ except Exception as e:
357
+ current_masks = None
358
+ current_image = None
359
+ return 0, None, f"Error: {str(e)}", gr.update(visible=False)
360
+
361
+ # Create the Gradio interface
362
+ with gr.Blocks(title="Cell Counter with Real-time Viability Assessment", theme=gr.themes.Soft()) as demo:
363
+ gr.Markdown("# Cell Counter with Real-time Viability Assessment")
364
+ gr.Markdown("Upload a microscopy image, run segmentation, then use the blue threshold slider for real-time viability assessment.")
365
+
366
+ with gr.Tab("Image Editor (Draw Selection)"):
367
+ gr.Markdown("### Step 1: Draw selection and run segmentation")
368
+
369
+ with gr.Row():
370
+ with gr.Column():
371
+ image_editor = gr.ImageEditor(
372
+ label="Draw selection on image",
373
+ type="pil",
374
+ brush=gr.Brush(colors=["#ff0000"], color_mode="fixed", default_size=20),
375
+ eraser=gr.Eraser(default_size=20)
376
+ )
377
+ model_dropdown1 = gr.Dropdown(
378
+ choices=list(MODEL_OPTIONS.keys()),
379
+ label="Select Model",
380
+ value="Hemocytometer Model"
381
+ )
382
+ segment_btn1 = gr.Button("🔬 Run Segmentation", variant="primary", size="lg")
383
+
384
+ with gr.Column():
385
+ cell_count_output1 = gr.Number(label="Total Cells Detected", precision=0)
386
+ overlay_output1 = gr.Image(type="pil", label="Segmentation Result")
387
+ info_output1 = gr.Textbox(label="Processing Info", lines=3)
388
+
389
+ # Viability Assessment Section
390
+ with gr.Group(visible=False) as viability_section1:
391
+ gr.Markdown("### Step 2: Real-time Viability Assessment")
392
+ gr.Markdown("Adjust the blue threshold to classify cells as live (green) or dead (red). Higher values = more blue = more dead.")
393
+
394
+ with gr.Row():
395
+ with gr.Column():
396
+ blue_threshold_slider1 = gr.Slider(
397
+ minimum=0,
398
+ maximum=255,
399
+ value=100,
400
+ step=1,
401
+ label="Blue Threshold",
402
+ info="Higher values = more cells classified as dead"
403
+ )
404
+
405
+ with gr.Column():
406
+ live_count_output1 = gr.Number(label="Live Cells (Green)", precision=0)
407
+ dead_count_output1 = gr.Number(label="Dead Cells (Red)", precision=0)
408
+
409
+ viability_overlay1 = gr.Image(type="pil", label="Viability Assessment (Green=Live, Red=Dead)")
410
+ viability_info1 = gr.Textbox(label="Viability Statistics", lines=4)
411
+
412
+ # Event handlers
413
+ segment_btn1.click(
414
+ fn=segment_cells,
415
+ inputs=[image_editor, model_dropdown1],
416
+ outputs=[cell_count_output1, overlay_output1, info_output1, viability_section1]
417
+ )
418
+
419
+ blue_threshold_slider1.change(
420
+ fn=update_viability_assessment,
421
+ inputs=[blue_threshold_slider1],
422
+ outputs=[viability_overlay1, live_count_output1, dead_count_output1, viability_info1]
423
+ )
424
+
425
+ with gr.Tab("Manual Coordinates"):
426
+ gr.Markdown("### Step 1: Upload image and run segmentation")
427
+
428
+ with gr.Row():
429
+ with gr.Column():
430
+ image_input = gr.Image(type="pil", label="Microscopy Image")
431
+ model_dropdown2 = gr.Dropdown(
432
+ choices=list(MODEL_OPTIONS.keys()),
433
+ label="Select Model",
434
+ value="Hemocytometer Model"
435
+ )
436
+ coord_input = gr.Textbox(
437
+ label="Crop Coordinates (optional)",
438
+ placeholder="e.g., 100,100,400,400",
439
+ info="Format: x_min,y_min,x_max,y_max"
440
+ )
441
+ segment_btn2 = gr.Button("🔬 Run Segmentation", variant="primary", size="lg")
442
+
443
+ with gr.Column():
444
+ cell_count_output2 = gr.Number(label="Total Cells Detected", precision=0)
445
+ overlay_output2 = gr.Image(type="pil", label="Segmentation Result")
446
+ info_output2 = gr.Textbox(label="Processing Info", lines=3)
447
+
448
+ # Viability Assessment Section
449
+ with gr.Group(visible=False) as viability_section2:
450
+ gr.Markdown("### Step 2: Real-time Viability Assessment")
451
+ gr.Markdown("Adjust the blue threshold to classify cells as live (green) or dead (red). Higher values = more blue = more dead.")
452
+
453
+ with gr.Row():
454
+ with gr.Column():
455
+ blue_threshold_slider2 = gr.Slider(
456
+ minimum=0,
457
+ maximum=255,
458
+ value=100,
459
+ step=1,
460
+ label="Blue Threshold",
461
+ info="Higher values = more cells classified as dead"
462
+ )
463
+
464
+ with gr.Column():
465
+ live_count_output2 = gr.Number(label="Live Cells (Green)", precision=0)
466
+ dead_count_output2 = gr.Number(label="Dead Cells (Red)", precision=0)
467
+
468
+ viability_overlay2 = gr.Image(type="pil", label="Viability Assessment (Green=Live, Red=Dead)")
469
+ viability_info2 = gr.Textbox(label="Viability Statistics", lines=4)
470
+
471
+ # Event handlers
472
+ segment_btn2.click(
473
+ fn=segment_with_coords,
474
+ inputs=[image_input, model_dropdown2, coord_input],
475
+ outputs=[cell_count_output2, overlay_output2, info_output2, viability_section2]
476
+ )
477
+
478
+ blue_threshold_slider2.change(
479
+ fn=update_viability_assessment,
480
+ inputs=[blue_threshold_slider2],
481
+ outputs=[viability_overlay2, live_count_output2, dead_count_output2, viability_info2]
482
+ )
483
+
484
+ # Instructions
485
+ with gr.Accordion("Instructions", open=False):
486
+ gr.Markdown("""
487
+ ### How to use:
488
+
489
+ 1. **Upload and Segment**:
490
+ - Upload your microscopy image
491
+ - Select a model (Hemocytometer Model for blood cells)
492
+ - Draw a selection region or specify coordinates
493
+ - Click "Run Segmentation"
494
+
495
+ 2. **Viability Assessment**:
496
+ - After segmentation, the viability section will appear
497
+ - Use the blue threshold slider to classify cells in real-time
498
+ - Green cells = Live (low blue intensity)
499
+ - Red cells = Dead (high blue intensity)
500
+ - Adjust the threshold until the classification looks correct
501
+
502
+ 3. **Interpreting Results**:
503
+ - The app calculates viability percentage automatically
504
+ - Live cells appear green, dead cells appear red
505
+ - Statistics show total counts and viability percentage
506
+
507
+ ### Tips:
508
+ - Start with a threshold around 100 and adjust based on your staining
509
+ - Dead cells typically have higher blue intensity due to trypan blue uptake
510
+ - The threshold is applied in real-time without re-running segmentation
511
+ """)
512
+
513
+ if __name__ == "__main__":
514
+ demo.launch()