Update app.py
Browse files12343 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import gradio as grfrom cellpose import modelsimport numpy as npimport cv23 unmodified linesimport iofrom huggingface_hub import hf_hub_downloadHF_REPO_ID = "myang4218/cellposemodel"HF_MODEL_FILENAME = "cellposemodel.npy"model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=HF_MODEL_FILENAME)print(f"Model downloaded to: {model_path}")# Load pretrained Cellpose model (nuclei or cyto depending on your data)model = models.CellposeModel(gpu=True, pretrained_model=model_path)def segment_and_count(image):# Convert PIL Image to numpy arrayimage_np = np.array(image)# If grayscale, convert to RGBif len(image_np.shape) == 2:image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)# Run Cellposemasks, flows, styles = model.eval(image_np, diameter=None, channels=[0, 0])# Count unique cellscell_count = len(np.unique(masks)) - 1 # subtract 1 for background# Overlay mask for displayoverlay = image_np.copy()alpha = 0.3 # Transparency factor (0.0 - 1.0, where 1.0 is fully opaque)# Blend the red color with the original image where mask > 0overlay[masks > 0] = (1 - alpha) * overlay[masks > 0] + alpha * np.array([255, 0, 0])# Convert result to PIL Image for outputoverlay_image = Image.fromarray(overlay)return cell_count, overlay_image# Gradio interfacedemo = gr.Interface(fn=segment_and_count,inputs=gr.Image(type="pil"),outputs=[gr.Number(label="Number of Cells"), gr.Image(type="pil", label="Segmented Overlay")],title="Cell Counter with Cellpose",description="Upload a microscopy image and count the number of cells using Cellpose segmentation.")if __name__ == "__main__":123453 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import gradio as grimport spacesfrom cellpose import modelsimport numpy as npimport cv23 unmodified linesimport iofrom huggingface_hub import hf_hub_download# Download model at startupHF_REPO_ID = "myang4218/cellposemodel"HF_MODEL_FILENAME = "cellposemodel.npy"model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=HF_MODEL_FILENAME)print(f"Model downloaded to: {model_path}")@spaces.GPUdef segment_and_count(image):# Initialize model inside the GPU-decorated functionmodel = models.CellposeModel(gpu=True, pretrained_model=model_path)# Convert PIL Image to numpy arrayimage_np = np.array(image)# If grayscale, convert to RGBif 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:# Handle RGBA imagesimage_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)# Run Cellposemasks, flows, styles = model.eval(image_np, diameter=None, channels=[0, 0])# Count unique cellscell_count = len(np.unique(masks)) - 1 # subtract 1 for background# Create better overlay visualizationoverlay = image_np.copy().astype(np.float32)# Create colored mask overlayif masks.max() > 0:# Generate random colors for each cellnp.random.seed(42) # For reproducible colorscolors = np.random.randint(0, 255, size=(masks.max() + 1, 3))colors[0] = [0, 0, 0] # Background stays black# Create colored overlaycolored_mask = colors[masks]# Blend with original imagealpha = 0.4overlay = (1 - alpha) * overlay + alpha * colored_mask# Ensure values are in valid range and convert to uint8overlay = np.clip(overlay, 0, 255).astype(np.uint8)# Convert result to PIL Image for outputoverlay_image = Image.fromarray(overlay)return cell_count, overlay_image# Gradio interfacedemo = gr.Interface(fn=segment_and_count,inputs=gr.Image(type="pil"),outputs=[gr.Number(label="Number of Cells"),gr.Image(type="pil", label="Segmented Overlay")],title="Cell Counter with Cellpose",description="Upload a microscopy image and count the number of cells using Cellpose segmentation.",)if __name__ == "__main__":
app.py+39-22