Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from cellpose import models
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import tempfile
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import io
|
| 9 |
+
from huggingface_hub import hf_hub_download
|
| 10 |
+
|
| 11 |
+
HF_REPO_ID = "myang4218/cellposemodel"
|
| 12 |
+
HF_MODEL_FILENAME = "cellposemodel.npy"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=HF_MODEL_FILENAME)
|
| 17 |
+
print(f"Model downloaded to: {model_path}")
|
| 18 |
+
|
| 19 |
+
# Load pretrained Cellpose model (nuclei or cyto depending on your data)
|
| 20 |
+
model = models.CellposeModel(gpu=True, pretrained_model=model_path)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def segment_and_count(image):
|
| 24 |
+
# Convert PIL Image to numpy array
|
| 25 |
+
image_np = np.array(image)
|
| 26 |
+
|
| 27 |
+
# If grayscale, convert to RGB
|
| 28 |
+
if len(image_np.shape) == 2:
|
| 29 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
|
| 30 |
+
|
| 31 |
+
# Run Cellpose
|
| 32 |
+
masks, flows, styles = model.eval(image_np, diameter=None, channels=[0, 0])
|
| 33 |
+
|
| 34 |
+
# Count unique cells
|
| 35 |
+
cell_count = len(np.unique(masks)) - 1 # subtract 1 for background
|
| 36 |
+
|
| 37 |
+
# Overlay mask for display
|
| 38 |
+
overlay = image_np.copy()
|
| 39 |
+
overlay[masks > 0] = [255, 0, 0] # red overlay for segmented cells
|
| 40 |
+
|
| 41 |
+
# Convert result to PIL Image for output
|
| 42 |
+
overlay_image = Image.fromarray(overlay)
|
| 43 |
+
|
| 44 |
+
return cell_count, overlay_image
|
| 45 |
+
|
| 46 |
+
# Gradio interface
|
| 47 |
+
demo = gr.Interface(
|
| 48 |
+
fn=segment_and_count,
|
| 49 |
+
inputs=gr.Image(type="pil"),
|
| 50 |
+
outputs=[gr.Number(label="Number of Cells"), gr.Image(type="pil", label="Segmented Overlay")],
|
| 51 |
+
title="Cell Counter with Cellpose",
|
| 52 |
+
description="Upload a microscopy image and count the number of cells using Cellpose segmentation."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
demo.launch()
|