Update app.py
Browse files2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879801 unmodified line82838485868788892 unmodified linesfrom cellpose import modelsimport numpy as npimport cv2import matplotlib.pyplot as pltimport tempfilefrom PIL import Imageimport iofrom huggingface_hub import hf_hub_downloadHF_REPO_ID = "myang4218/cellposemodel"MODEL_OPTIONS = {"Hemocytometer Model": "hemocytometermodel.npy","General Model": "generalmodel.npy"}loaded_models = {}@spaces.GPUdef segment_and_count(image, model_choice):model_filename = MODEL_OPTIONS[model_choice]model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=model_filename)if model_filename in loaded_models:model = loaded_models[model_filename]else:model = models.CellposeModel(gpu=True, pretrained_model=model_path)loaded_models[model_filename] = model# 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", label="Microscopy Image"),gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), label="Select Model", value="Hemocytometer Model")],outputs=[1 unmodified linegr.Image(type="pil", label="Segmented Overlay")],title="Cell Counter with Cellpose",description="Upload a microscopy image and select a model to count the number of cells using Cellpose segmentation.")if __name__ == "__main__":demo.launch()2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889901 unmodified line92939495969798992 unmodified linesfrom cellpose import modelsimport numpy as npimport cv2from PIL import Imagefrom huggingface_hub import hf_hub_download# Hugging Face model repoHF_REPO_ID = "myang4218/cellposemodel"# Model filename optionsMODEL_OPTIONS = {"Hemocytometer Model": "hemocytometermodel.npy","General Model": "generalmodel.npy"}# Cache loaded modelsloaded_models = {}@spaces.GPUdef segment_and_count(image, box, model_choice):# Download and load selected modelmodel_filename = MODEL_OPTIONS[model_choice]model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=model_filename)if model_filename in loaded_models:model = loaded_models[model_filename]else:model = models.CellposeModel(gpu=True, pretrained_model=model_path)loaded_models[model_filename] = model# Get ROI coordinates from selection boxif box is None:# No box selected – process entire imageroi_pil = imagex, y = 0, 0else:x, y = int(box["x"]), int(box["y"])w, h = int(box["width"]), int(box["height"])roi_pil = image.crop((x, y, x + w, y + h))# Convert cropped region to NumPyroi_np = np.array(roi_pil)# Convert to RGB if neededif len(roi_np.shape) == 2:roi_np = cv2.cvtColor(roi_np, cv2.COLOR_GRAY2RGB)elif roi_np.shape[2] == 4:roi_np = cv2.cvtColor(roi_np, cv2.COLOR_RGBA2RGB)# Run Cellpose on cropped ROImasks, flows, styles = model.eval(roi_np, diameter=None, channels=[0, 0])cell_count = len(np.unique(masks)) - 1 # Exclude background# Create colored overlay for ROIoverlay_roi = roi_np.copy().astype(np.float32)if masks.max() > 0:np.random.seed(42)colors = np.random.randint(0, 255, size=(masks.max() + 1, 3))colors[0] = [0, 0, 0]colored_mask = colors[masks]alpha = 0.4overlay_roi = (1 - alpha) * overlay_roi + alpha * colored_maskoverlay_roi = np.clip(overlay_roi, 0, 255).astype(np.uint8)# Prepare final overlay imagefull_overlay = np.array(image).astype(np.float32)if full_overlay.shape[2] == 4:full_overlay = cv2.cvtColor(full_overlay, cv2.COLOR_RGBA2RGB)# Paste the overlay ROI back onto the full imageh, w = overlay_roi.shape[:2]full_overlay[y:y + h, x:x + w] = overlay_roi# Convert back to PIL for outputoverlay_image = Image.fromarray(full_overlay.astype(np.uint8))return cell_count, overlay_image# Gradio interfacedemo = gr.Interface(fn=segment_and_count,inputs=[gr.Image(type="pil", label="Microscopy Image", tool="select"),gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), label="Select Model", value="Hemocytometer Model")],outputs=[1 unmodified linegr.Image(type="pil", label="Segmented Overlay")],title="Cell Counter with Cellpose",description="Upload a microscopy image and optionally select a region to segment cells using Cellpose.")if __name__ == "__main__":demo.launch()
app.py+54-44