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|
+
import pandas as pd
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from skimage import measure, morphology
|
| 6 |
+
from skimage.segmentation import watershed
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
|
| 9 |
+
def process_image(image):
|
| 10 |
+
"""Process uploaded image and extract cell features"""
|
| 11 |
+
# Convert to BGR if image is RGB
|
| 12 |
+
if len(image.shape) == 3:
|
| 13 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
| 14 |
+
|
| 15 |
+
# Basic preprocessing
|
| 16 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 17 |
+
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
|
| 18 |
+
enhanced = clahe.apply(gray)
|
| 19 |
+
blurred = cv2.medianBlur(enhanced, 5)
|
| 20 |
+
|
| 21 |
+
# Segmentation
|
| 22 |
+
thresh = cv2.adaptiveThreshold(
|
| 23 |
+
blurred, 255,
|
| 24 |
+
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
| 25 |
+
cv2.THRESH_BINARY_INV, 21, 4
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Clean small noise
|
| 29 |
+
cleaned = morphology.opening(thresh, morphology.disk(2))
|
| 30 |
+
|
| 31 |
+
# Watershed segmentation
|
| 32 |
+
sure_bg = cv2.dilate(cleaned, morphology.disk(3), iterations=3)
|
| 33 |
+
dist = cv2.distanceTransform(cleaned, cv2.DIST_L2, 5)
|
| 34 |
+
ret, sure_fg = cv2.threshold(dist, 0.5*dist.max(), 255, 0)
|
| 35 |
+
sure_fg = np.uint8(sure_fg)
|
| 36 |
+
unknown = cv2.subtract(sure_bg, sure_fg)
|
| 37 |
+
|
| 38 |
+
# Marker labelling
|
| 39 |
+
ret, markers = cv2.connectedComponents(sure_fg)
|
| 40 |
+
markers += 1
|
| 41 |
+
markers[unknown == 255] = 0
|
| 42 |
+
markers = watershed(-dist, markers, mask=cleaned)
|
| 43 |
+
|
| 44 |
+
# Extract features
|
| 45 |
+
features = []
|
| 46 |
+
props = measure.regionprops(markers, intensity_image=gray)
|
| 47 |
+
|
| 48 |
+
for i, prop in enumerate(props):
|
| 49 |
+
if prop.area < 50: # Filter small regions
|
| 50 |
+
continue
|
| 51 |
+
|
| 52 |
+
features.append({
|
| 53 |
+
'cell_id': i+1,
|
| 54 |
+
'area': prop.area,
|
| 55 |
+
'perimeter': prop.perimeter,
|
| 56 |
+
'circularity': (4 * np.pi * prop.area) / (prop.perimeter**2 + 1e-6),
|
| 57 |
+
'mean_intensity': prop.mean_intensity,
|
| 58 |
+
'centroid_x': prop.centroid[1],
|
| 59 |
+
'centroid_y': prop.centroid[0]
|
| 60 |
+
})
|
| 61 |
+
|
| 62 |
+
# Create visualization
|
| 63 |
+
vis_img = image.copy()
|
| 64 |
+
contours = measure.find_contours(markers, 0.5)
|
| 65 |
+
|
| 66 |
+
# Draw contours and cell IDs
|
| 67 |
+
for contour in contours:
|
| 68 |
+
coords = contour.astype(int)
|
| 69 |
+
cv2.drawContours(vis_img, [coords], -1, (0,255,0), 1)
|
| 70 |
+
|
| 71 |
+
for region in measure.regionprops(markers):
|
| 72 |
+
if region.area >= 50:
|
| 73 |
+
y, x = region.centroid
|
| 74 |
+
cv2.putText(vis_img, str(region.label),
|
| 75 |
+
(int(x), int(y)),
|
| 76 |
+
cv2.FONT_HERSHEY_SIMPLEX,
|
| 77 |
+
0.4, (255,0,0), 1)
|
| 78 |
+
|
| 79 |
+
# Create summary plots
|
| 80 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
|
| 81 |
+
|
| 82 |
+
# Cell size distribution
|
| 83 |
+
df = pd.DataFrame(features)
|
| 84 |
+
df['area'].hist(ax=axes[0], bins=20)
|
| 85 |
+
axes[0].set_title('Cell Size Distribution')
|
| 86 |
+
axes[0].set_xlabel('Area')
|
| 87 |
+
axes[0].set_ylabel('Count')
|
| 88 |
+
|
| 89 |
+
# Circularity vs Intensity
|
| 90 |
+
axes[1].scatter(df['circularity'], df['mean_intensity'])
|
| 91 |
+
axes[1].set_title('Circularity vs Intensity')
|
| 92 |
+
axes[1].set_xlabel('Circularity')
|
| 93 |
+
axes[1].set_ylabel('Mean Intensity')
|
| 94 |
+
|
| 95 |
+
plt.tight_layout()
|
| 96 |
+
|
| 97 |
+
return (
|
| 98 |
+
cv2.cvtColor(vis_img, cv2.COLOR_BGR2RGB),
|
| 99 |
+
fig,
|
| 100 |
+
df
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# Create Gradio interface
|
| 104 |
+
with gr.Blocks(title="Cell Analysis Tool") as demo:
|
| 105 |
+
gr.Markdown("""
|
| 106 |
+
# 🔬 Bioengineering Cell Analysis Tool
|
| 107 |
+
|
| 108 |
+
Upload microscopy images to analyze cell properties:
|
| 109 |
+
- Automated cell detection
|
| 110 |
+
- Feature extraction (size, shape, intensity)
|
| 111 |
+
- Statistical analysis
|
| 112 |
+
|
| 113 |
+
**Instructions:**
|
| 114 |
+
1. Upload an image containing cells
|
| 115 |
+
2. Wait for analysis to complete
|
| 116 |
+
3. Review results in three tabs:
|
| 117 |
+
- Detected cells visualization
|
| 118 |
+
- Statistical plots
|
| 119 |
+
- Detailed measurements table
|
| 120 |
+
""")
|
| 121 |
+
|
| 122 |
+
with gr.Row():
|
| 123 |
+
with gr.Column():
|
| 124 |
+
input_image = gr.Image(
|
| 125 |
+
label="Upload Image",
|
| 126 |
+
type="numpy",
|
| 127 |
+
tool="upload"
|
| 128 |
+
)
|
| 129 |
+
analyze_btn = gr.Button(
|
| 130 |
+
"Analyze Image",
|
| 131 |
+
variant="primary"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
with gr.Column():
|
| 135 |
+
with gr.Tabs():
|
| 136 |
+
with gr.Tab("Detection Results"):
|
| 137 |
+
output_image = gr.Image(
|
| 138 |
+
label="Detected Cells"
|
| 139 |
+
)
|
| 140 |
+
with gr.Tab("Statistics"):
|
| 141 |
+
output_plot = gr.Plot(
|
| 142 |
+
label="Statistical Analysis"
|
| 143 |
+
)
|
| 144 |
+
with gr.Tab("Measurements"):
|
| 145 |
+
output_table = gr.DataFrame(
|
| 146 |
+
label="Cell Features"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
analyze_btn.click(
|
| 150 |
+
fn=process_image,
|
| 151 |
+
inputs=input_image,
|
| 152 |
+
outputs=[output_image, output_plot, output_table]
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# Launch the demo
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
demo.launch()
|