Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +55 -0
- requirements.txt +5 -0
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from cellpose import models
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
# Load Cellpose pretrained model for cytoplasm
|
| 8 |
+
model = models.Cellpose(model_type='cyto') # or 'nuclei' for nucleus
|
| 9 |
+
|
| 10 |
+
def segment_and_count(image: Image.Image):
|
| 11 |
+
# Convert image to numpy RGB
|
| 12 |
+
img_np = np.array(image.convert("RGB"))
|
| 13 |
+
|
| 14 |
+
# Run Cellpose
|
| 15 |
+
masks, flows, styles, diams = model.eval(img_np, diameter=None, channels=[0, 0]) # grayscale or RGB
|
| 16 |
+
|
| 17 |
+
# Create overlay image
|
| 18 |
+
outlines = masks_to_overlay(img_np, masks)
|
| 19 |
+
|
| 20 |
+
# Count unique masks (excluding background=0)
|
| 21 |
+
unique_ids = np.unique(masks)
|
| 22 |
+
cell_count = len(unique_ids[unique_ids > 0])
|
| 23 |
+
|
| 24 |
+
return Image.fromarray(outlines), f"Detected cells: {cell_count}"
|
| 25 |
+
|
| 26 |
+
# Draw outlines on image
|
| 27 |
+
def masks_to_overlay(image, masks):
|
| 28 |
+
overlay = image.copy()
|
| 29 |
+
contours, _ = cv2.findContours(masks.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 30 |
+
cv2.drawContours(overlay, contours, -1, (0, 255, 0), 1)
|
| 31 |
+
return overlay
|
| 32 |
+
|
| 33 |
+
# Gradio interface
|
| 34 |
+
with gr.Blocks() as demo:
|
| 35 |
+
gr.Markdown("## 🧬 Cell Counting with Cellpose")
|
| 36 |
+
with gr.Row():
|
| 37 |
+
with gr.Column():
|
| 38 |
+
image_input = gr.Image(type="pil", label="Upload Microscopy Image")
|
| 39 |
+
run_btn = gr.Button("Count Cells")
|
| 40 |
+
count_output = gr.Textbox(label="Detected Cell Count")
|
| 41 |
+
examples = gr.Examples(
|
| 42 |
+
examples=[
|
| 43 |
+
["examples/cells1.png"],
|
| 44 |
+
["examples/cells2.jpg"],
|
| 45 |
+
["examples/cells3.png"]
|
| 46 |
+
],
|
| 47 |
+
inputs=[image_input],
|
| 48 |
+
label="Example Images"
|
| 49 |
+
)
|
| 50 |
+
with gr.Column():
|
| 51 |
+
image_output = gr.Image(type="pil", label="Cell Mask Overlay")
|
| 52 |
+
|
| 53 |
+
run_btn.click(fn=segment_and_count, inputs=image_input, outputs=[image_output, count_output])
|
| 54 |
+
|
| 55 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
cellpose
|
| 3 |
+
numpy
|
| 4 |
+
opencv-python
|
| 5 |
+
Pillow
|