### Install Samcell Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb Steps to install Samcell by cloning the repository and installing its requirements. Also notes the need to download pre-trained models separately. ```bash git clone https://github.com/NathanMalta/SAMCell.git cd SAMCell pip install -r requirements.txt ``` -------------------------------- ### Install Cellpose from GitHub Source: https://github.com/mouseland/cellpose/blob/main/README.md Install Cellpose directly from its GitHub repository. Ensure dependencies are installed first. ```bash pip install git+https://www.github.com/mouseland/cellpose.git ``` -------------------------------- ### Install Microsam, Pathosam, and CellposeSAM Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb Instructions for creating a conda environment and installing Microsam, PathoSAM, and CellposeSAM using conda and pip. This setup is for Python 3.12. ```bash conda create --name microsam python=3.12 conda activate microsam conda install -c conda-forge microsam=1.4 pip install slideio pip install git+https://github.com/computational-cell-analytics/patho-sam.git pip install git+https://github.com/mouseland/cellpose.git ``` -------------------------------- ### Install Omnipose Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb Instructions for installing Omnipose by cloning the repository and performing an editable pip install. Includes a note about potential compatibility issues with newer PyTorch versions requiring a manual edit. ```bash git clone https://github.com/kevinjohncutler/omnipose.git cd omnipose pip install -e . # (with newer torch versions need to edit omnipose/src/core.py torch.amp => torch.cuda.amp) ``` -------------------------------- ### Install Cellpose from GitHub Source: https://github.com/mouseland/cellpose/blob/main/notebooks/test_Cellpose-SAM.ipynb Installs the Cellpose library directly from its GitHub repository. This is useful for getting the latest version or for development purposes. ```python !pip install git+https://www.github.com/mouseland/cellpose.git ``` -------------------------------- ### Install Cellpose 3.1.1.2 Source: https://github.com/mouseland/cellpose/blob/main/docs/restore.md Install a specific version of Cellpose for image restoration. ```bash pip install cellpose==3.1.1.2 ``` -------------------------------- ### Install XCB Libraries for Qt Issues Source: https://github.com/mouseland/cellpose/blob/main/docs/installation.md If you encounter Qt "xcb" errors, install these libraries using your system's package manager. ```bash sudo apt install libxcb-cursor0 ``` ```bash sudo apt install libxcb-xinerama0 ``` -------------------------------- ### Install Cellpose with BioImage.IO Support Source: https://github.com/mouseland/cellpose/blob/main/docs/models.md Install Cellpose with the necessary packages for exporting models to the BioImage.IO format. Use 'all' for full compatibility. ```bash python -m pip install 'cellpose[bioimageio]' ``` ```bash 'cellpose[all]' ``` -------------------------------- ### Recommended Cellpose-SAM Fine-tuning Setup (CLI) Source: https://github.com/mouseland/cellpose/blob/main/docs/train.md Use this command for fine-tuning the Cellpose-SAM model with specified training parameters. Ensure absolute paths for --dir and --test_dir. ```bash python -m cellpose --train --dir ~/images/train/ --test_dir ~/images/test/ --learning_rate 0.00001 --weight_decay 0.1 --n_epochs 100 --train_batch_size 1 ``` -------------------------------- ### Start Cellpose GUI Source: https://github.com/mouseland/cellpose/blob/main/docs/gui.md Launches the Cellpose GUI from the command line. The first run downloads trained model weights. Ensure Anaconda is in your PATH if not using an Anaconda prompt. ```bash python -m cellpose ``` -------------------------------- ### Run CellposeSAM, MicroSAM, and PathoSAM Benchmarks Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb Executes benchmark tests for CellposeSAM, MicroSAM, and PathoSAM after installation. Requires the 'benchmarks' module to be available. ```python io.logger_setup() benchmarks.run_cellposesam() benchmarks.run_microsam() benchmarks.run_pathosam() ``` -------------------------------- ### Install Cellpose in Editable Mode Source: https://github.com/mouseland/cellpose/blob/main/README.md Install Cellpose from a local GitHub repository in editable mode, allowing for code modifications. ```bash pip install -e . ``` -------------------------------- ### Train Cellpose-SAM on Your Labeled Data Source: https://github.com/mouseland/cellpose/blob/main/README.md This notebook provides a guide for training Cellpose-SAM on your own labeled datasets. It includes instructions for using provided example data as well, making it a comprehensive resource for custom model development. ```python from cellpose import models, io, transforms import os import numpy as np # Define training data path train_path = 'path/to/your/training/data' # Define output path for trained model model_path = 'path/to/save/model' # Load images and masks image_names = [os.path.join(train_path, fname) for fname in os.listdir(train_path) if fname.endswith('.tif')] mask_names = [os.path.join(train_path, fname) for fname in os.listdir(train_path) if fname.endswith('_masks.tif')] # Ensure images and masks are paired correctly # This is a simplified example; actual pairing might need more logic images = [io.imread(im_name) for im_name in image_names] masks = [io.imread(ms_name) for ms_name in mask_names] # Initialize model for training # Use 'cyto' for cytoplasm, 'nuclei' for nucleus segmentation # Use 'cyto3d' or 'nuclei3d' for 3D data model = models.Cellpose(model_type='cyto', gpu=True) # Start training # You can adjust parameters like learning_rate, n_epochs, batch_size etc. model.train(images, masks, dir_above=model_path, learning_rate=0.0004, n_epochs=500, batch_size=8) # Save the trained model # The model will be saved automatically in the specified directory print(f'Model trained and saved to {model_path}') ``` -------------------------------- ### Test Cellpose-SAM with Example Data (2D and 3D) Source: https://github.com/mouseland/cellpose/blob/main/README.md This notebook showcases running Cellpose-SAM using pre-existing example data in both 2D and 3D. It's helpful for understanding the model's performance and basic usage without needing your own data. ```python from cellpose import models import matplotlib.pyplot as plt import numpy as np # Load example data from cellpose.datasets import load_example_data img, flows, masks, diams = load_example_data(image_idx=0, mask_type=0, onechan=False) # Initialize model model = models.Cellpose(model_type='cyto', gpu=False) # Run segmentation on 2D example masks, flows, styles, diams = model.eval(img, diameter=None, flow_threshold=0.4, cellprob_threshold=0.0, ambient_threshold=0.0) # Plot results plt.figure(figsize=(10,10)) plt.imshow(masks, cmap='magma') plt.show() # Example for 3D data (if available and loaded) # img3d, flows3d, masks3d, diams3d = load_example_data(image_idx=0, mask_type=0, three_d=True) # model3d = models.Cellpose(model_type='cyto3d', gpu=False) # masks3d, flows3d, styles3d, diams3d = model3d.eval(img3d, diameter=None, flow_threshold=0.4, cellprob_threshold=0.0, ambient_threshold=0.0) ``` -------------------------------- ### Install Cellpose3 and Dependencies Source: https://github.com/mouseland/cellpose/blob/main/notebooks/run_cellpose3.ipynb Installs the necessary libraries for Cellpose3, including OpenCV and the specific version of cellpose. Ensure you are using a compatible environment. ```python !pip install "opencv-python-headless>=4.9.0.80" !pip install cellpose==3.1.1.2 ``` -------------------------------- ### Download Example 2D Images Source: https://github.com/mouseland/cellpose/blob/main/notebooks/test_Cellpose-SAM.ipynb Downloads a sample dataset of 2D images from the Cellpose website. This is useful for testing the model and its functionalities. ```python import numpy as np import matplotlib.pyplot as plt from cellpose import utils, io # download example 2D images from website url = "http://www.cellpose.org/static/data/imgs_cyto3.npz" filename = "imgs_cyto3.npz" utils.download_url_to_file(url, filename) ``` -------------------------------- ### Start Cellpose GUI for Z-stacks Source: https://github.com/mouseland/cellpose/blob/main/docs/gui.md Launches the Cellpose GUI specifically for processing 3D data (Z-stacks). This option is recommended for multi-Z 3D data. ```bash python -m cellpose --Zstack ``` -------------------------------- ### Install Cellpose with GUI (venv) Source: https://github.com/mouseland/cellpose/blob/main/README.md Install Cellpose with its GUI dependencies using pip within a Python virtual environment (venv). Quotes may be necessary depending on your terminal. ```sh python -m pip install cellpose[gui] ``` ```sh python -m pip install 'cellpose[gui]' ``` -------------------------------- ### Install GPU PyTorch with CUDA 12.6 Source: https://github.com/mouseland/cellpose/blob/main/README.md Install the GPU version of PyTorch and torchvision for Windows with CUDA 12.6. Ensure NVIDIA drivers are installed. ```bash pip3 install torch torchvision --index-url https://download.pytorch.org/whl/cu126 ``` -------------------------------- ### Install Cellsam and Cellpose Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb Instructions for setting up a separate environment for Cellsam and Cellpose (version 3.1.2) using conda and pip. Includes cloning the Cellsam repository and checking out a specific commit. ```bash conda create --name cellsam python=3.11 conda activate cellsam git clone https://github.com/vanvalenlab/cellSAM.git cd cellSAM # checkout latest working model (new commits download new model which performs poorly) git checkout a392cdd199eebd11646cf6dd115a992af33f6365 pip install -e . pip install cellpose==3.1.2 pip install segmentation_models_pytorch==0.4.0 # for segformer ``` -------------------------------- ### Import Libraries for Cellpose Benchmarking Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb Imports necessary libraries for running benchmarks and setting up logging. Ensure all listed libraries are installed in your environment. ```python import numpy as np from cellpose import io, metrics, models, utils import time from tqdm import trange from pathlib import Path from natsort import natsorted import tifffile import benchmarks import importlib importlib.reload(benchmarks) ``` -------------------------------- ### Initialize Cellpose and CellSAM for Denoising/Deblurring Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/invariances.ipynb Initializes Cellpose and CellSAM models, similar to previous setups, but prepares for a loop that iterates through different noise types for potential denoising or deblurring tasks. Requires torch, cv2, and cellpose. ```python from cellSAM import segment_cellular_image from cellpose import resnet_torch import cv2 import torch io.logger_setup() device = torch.device("cuda") ps = 8 backbone = "vit_l" net = TransformerMP(ps=ps, backbone=backbone).to(device) net.load_model("models/cpsam8_0_2100_8_402175188", strict=False, multigpu=False) model = models.CellposeModel(gpu=True, nchan=3) net.eval() model.net = net cp_model = models.CellposeModel(gpu=True, model_type="cyto3") nstr = {"poisson": "denoise", "blur": "deblur", "downsample": "upsample", "aniso": "aniso"} for ii, noise_type in enumerate(["poisson", "blur", "downsample", "aniso"]): ``` -------------------------------- ### Process Images with Different Channel Configurations Source: https://github.com/mouseland/cellpose/blob/main/docs/settings.md Demonstrates how to prepare image data for Cellpose-SAM, which is invariant to channel order and uses the first three channels. Examples show selecting specific channels or combining them. ```python from cellpose import models from cellpose.io import imread model = models.CellposeModel(gpu=True) img = imread("img.tif") # tiff is n x 100 x 100 # if nuclei and cytoplasm are in first two channels img_cp = img[:2] # keep first two channels # if nuclei and cytoplasm are in different channels from first two img_cp = img[[1, 3]] # keep 1 and 3 (2nd and 4th channels) # if you want to combine two stains to create your "cytoplasm" channel # in this example indices 0 and 2 (1st and 3rd) have two cellular stains # and nuclei are in index 1 (2nd channel) img_cp = np.stack((img[[0,2]].sum(axis=0), img[1]), axis=0) masks, flows, styles = model.eval(img_cp) ``` -------------------------------- ### Install Cellpose with GUI (conda) Source: https://github.com/mouseland/cellpose/blob/main/README.md Use this command to install Cellpose along with its graphical user interface dependencies within a conda environment. Ensure your conda environment is activated. ```sh python -m pip install cellpose[gui] ``` -------------------------------- ### Initialize Cellpose and CellSAM Models Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/invariances.ipynb Initializes the CellSAM Transformer model and a CellposeModel, loading pre-trained weights for CellSAM. This setup is for GPU usage and requires specific libraries like torch, cv2, and cellpose. ```python #from cellSAM import cellsam_pipeline from cellSAM import segment_cellular_image from cellpose import resnet_torch import cv2 import torch from train_subsets import TransformerMP io.logger_setup() device = torch.device("cuda") ps = 8 backbone = "vit_l" net = TransformerMP(ps=ps, backbone=backbone).to(device) net.load_model("models/cpsam8_0_2100_8_402175188", strict=False, multigpu=False) model = models.CellposeModel(gpu=True, nchan=3) net.eval() model.net = net cp_model = models.CellposeModel(gpu=True, model_type="cyto3") aps = [[], [], []] masks_preds = [] for sz in [10, 15, 30, 60, 90]: diameters = diam_true.copy() * (30. / sz) imgs_rsz = [transforms.resize_image(imgs[i].transpose(1,2,0), rsz=30./diameters[i]).transpose(2,0,1) for i in range(len(imgs))] masks_true_rsz = [transforms.resize_image(masks_true[i], rsz=30./diameters[i], no_channels=True, interpolation=cv2.INTER_NEAREST) for i in range(len(imgs))] for j in range(1): if j==0: masks_pred, flows, styles = model.eval(imgs_rsz, diameter=30., channels=None, augment=False, bsize=256, tile_overlap=0.1, batch_size=64, flow_threshold=0.4, cellprob_threshold=0, normalize=False) elif j==1: masks_pred, flows, styles = cp_model.eval(imgs_rsz, diameter=30., channels=[2,3], bsize=224, tile_overlap=0.5, batch_size=64, augment=True, flow_threshold=0.4, cellprob_threshold=0, normalize=False) else: if sz!=90: masks_pred = [] bsize = 1024 for i in trange(len(imgs_rsz)): img = imgs_rsz[i][[0,2,1]].copy() Ly, Lx = img.shape[1:] Lyr = bsize if Ly > bsize and Ly > Lx else Ly Lxr = bsize if Lx > bsize and Lx >= Ly else Lx Lxr = int(np.round(bsize * (Lx / Ly))) if Ly > Lx and Lyr==bsize else Lxr Lyr = int(np.round(bsize * (Ly / Lx))) if Lx >= Ly and Lxr==bsize else Lyr if Lyr != Ly or Lxr != Lx: img = cv2.resize(img.transpose(1, 2, 0), (Lxr, Lyr), interpolation=cv2.INTER_LINEAR).transpose(2, 0, 1) if Lyr < bsize or Lxr < bsize: padyx = [(int(np.floor((bsize-Lyr)/2)), int(np.ceil((bsize-Lyr)/2))), (int(np.floor((bsize-Lxr)/2)), int(np.ceil((bsize-Lxr)/2)))] img = np.pad(img, ((0,0), padyx[0], padyx[1]), mode='constant') else: padyx = [(0, 0), (0, 0)] try: masks, _, _ = segment_cellular_image(img, device='cuda') except: masks = np.zeros((bsize, bsize), dtype="uint16") masks = masks[padyx[0][0]:bsize-padyx[0][1], padyx[1][0]:bsize-padyx[1][1]] if Lyr != Ly or Lxr != Lx: masks = cv2.resize(masks, (Lx, Ly), interpolation=cv2.INTER_NEAREST) masks_pred.append(masks) ap, tp, fp, fn = metrics.average_precision(masks_true_rsz, masks_pred) if sz==90 and j==2: ap *= np.nan else: print(ap.mean(axis=0)) aps[j].append(ap) if j==0: masks_preds.append(masks_pred) ``` -------------------------------- ### Run Cyto3 Segformer and Cellsam Benchmarks Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb Reloads the benchmarks module and runs benchmark tests for Cyto3 Segformer and Cellsam. Requires the 'benchmarks' module and necessary installations. ```python importlib.reload(benchmarks) io.logger_setup() benchmarks.run_cyto3_segformer() benchmarks.run_cellsam() ``` -------------------------------- ### Run Cellpose Model Evaluation Source: https://github.com/mouseland/cellpose/blob/main/docs/notebook.md This snippet shows how to set up and run the Cellpose model for image segmentation in a notebook. Ensure you have the necessary libraries installed and specify the correct path to your image files. ```python import numpy as np import matplotlib.pyplot as plt from cellpose import models, io from cellpose.io import imread io.logger_setup() model = models.CellposeModel(gpu=True) # list of files # PUT PATH TO YOUR FILES HERE! files = ['/media/carsen/DATA1/TIFFS/onechan.tif'] imgs = [imread(f) for f in files] nimg = len(imgs) masks, flows, styles = model.eval(imgs) ``` -------------------------------- ### CLI Segmentation using GPU Source: https://context7.com/mouseland/cellpose/llms.txt Enables GPU acceleration for segmentation tasks, significantly speeding up processing time. Ensure CUDA is properly installed and configured. ```bash # Use GPU python -m cellpose --dir /path/to/images/ --use_gpu --save_png ``` -------------------------------- ### Cellpose Execution Log Output Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb This log output indicates the start of a Cellpose run, including the version, platform, Python version, and PyTorch version. It also shows that CUDA is installed and working, and that a specific model ('cyto3') is being used with a specified mean diameter. ```log 2025-04-19 16:50:49,355 [INFO] WRITING LOG OUTPUT TO /home/carsen/.cellpose/run.log 2025-04-19 16:50:49,357 [INFO] cellpose version: 3.1.1.2.dev23+g9854949 platform: linux python version: 3.11.12 torch version: 2.0.0+cu117 ['cyto2', 'bact_phase'] cyto2 2025-04-19 16:50:49,570 [INFO] ** TORCH CUDA version installed and working. ** 2025-04-19 16:50:49,571 [INFO] >>>> using GPU (CUDA) 2025-04-19 16:50:49,572 [INFO] >> cyto3 << model set to be used 2025-04-19 16:50:49,632 [INFO] >>>> loading model /home/carsen/.cellpose/models/cyto3 2025-04-19 16:50:49,690 [INFO] >>>> model diam_mean = 30.000 (ROIs rescaled to this size during training) ``` -------------------------------- ### Download and Unzip Sample Images Source: https://github.com/mouseland/cellpose/blob/main/notebooks/train_Cellpose-SAM.ipynb Downloads a zip file containing sample images from a Google Drive URL and then unzips it. Sets up training and test directories and defines the mask file extension. ```python from natsort import natsorted from cellpose import utils from pathlib import Path url = "https://drive.google.com/uc?id=1HXpLczf7TPCdI1yZY5KV3EkdWzRrgvhQ" utils.download_url_to_file(url, "human_in_the_loop.zip") !unzip human_in_the_loop train_dir = "human_in_the_loop/train/" test_dir = "human_in_the_loop/test/" masks_ext = "_seg.npy" ``` -------------------------------- ### Display Help Message for make_train.py Source: https://github.com/mouseland/cellpose/blob/main/docs/do3d.md Use this command to view all available options and arguments for the `make_train.py` script. This is useful for understanding how to configure image processing and training parameters. ```default python cellpose\gui\make_train.py --help ``` -------------------------------- ### Install nomkl for OpenMP/libiomp5 Errors Source: https://github.com/mouseland/cellpose/blob/main/docs/installation.md If you face errors related to OpenMP and libiomp5, try installing the 'nomkl' package via Conda. ```bash conda install nomkl ``` -------------------------------- ### Use User-Trained Model via Command Line Source: https://github.com/mouseland/cellpose/blob/main/docs/models.md Utilize a user-trained model directly from the command line, specifying either its name or its full file path. ```bash python -m cellpose --pretrained_model name_in_gui ``` ```bash python -m cellpose --pretrained_model /full/path/to/model ``` -------------------------------- ### Initialize DenoiseModel Source: https://github.com/mouseland/cellpose/blob/main/docs/restore.md Initialize a DenoiseModel for image restoration. Specify the model type and whether to use GPU. ```python from cellpose import denoise dn = denoise.DenoiseModel(model_type="denoise_cyto3", gpu=True) ``` -------------------------------- ### Install notebook and matplotlib for venv Source: https://github.com/mouseland/cellpose/blob/main/README.md Installs the 'notebook' and 'matplotlib' packages into the active conda environment, enabling the use of Jupyter notebooks and plotting capabilities. ```sh python -m pip install notebook ``` ```sh python -m pip install matplotlib ``` -------------------------------- ### Install Cellpose without GUI (conda) Source: https://github.com/mouseland/cellpose/blob/main/README.md Use this command to install Cellpose without the graphical user interface. This is suitable for users who prefer a command-line interface or are integrating Cellpose into scripts. Ensure your conda environment is activated. ```sh python -m pip install cellpose ``` -------------------------------- ### CLI Model Training Source: https://context7.com/mouseland/cellpose/llms.txt Initiates the training process for a new Cellpose model. Requires specifying training and testing directories, learning rate, weight decay, number of epochs, and batch size. ```bash # Train a new model python -m cellpose \ --train \ --dir /path/to/train/ \ --test_dir /path/to/test/ \ --learning_rate 0.00001 \ --weight_decay 0.1 \ --n_epochs 100 \ --train_batch_size 1 \ --model_name_out my_trained_model ``` -------------------------------- ### cellpose.vit_sam.Transformer.device Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Gets the device of the Transformer model. ```APIDOC ## Transformer.device ### Description Get the device of the model. ### Returns The device of the model. ### Return type torch.device ``` -------------------------------- ### cellpose.vit_sam.Transformer.dtype Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Gets the data type of the Transformer model. ```APIDOC ## Transformer.dtype ### Description Get the data type of the model. ### Returns The data type of the model. ### Return type torch.dtype ``` -------------------------------- ### Load and Display Sample Noisy Images Source: https://github.com/mouseland/cellpose/blob/main/notebooks/run_cellpose3.ipynb Downloads and loads a sample dataset of noisy images from a URL and displays them. This helps in visualizing the input data before processing. ```python import numpy as np import time, os, sys from urllib.parse import urlparse import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline mpl.rcParams['figure.dpi'] = 200 from cellpose import utils, io # download noisy images from website url = "http://www.cellpose.org/static/data/test_poisson.npz" filename = "test_poisson.npz" utils.download_url_to_file(url, filename) dat = np.load(filename, allow_pickle=True)["arr_0"].item() imgs = dat["test_noisy"] plt.figure(figsize=(8,3)) for i, iex in enumerate([2, 18, 20]): img = imgs[iex].squeeze() plt.subplot(1,3,1+i) plt.imshow(img, cmap="gray", vmin=0, vmax=1) plt.axis('off') plt.tight_layout() plt.show() ``` -------------------------------- ### cellpose.plot.interesting_patch Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Get patch of size bsize x bsize with most masks. ```APIDOC ## cellpose.plot.interesting_patch(mask, bsize=130) ### Description Get patch of size bsize x bsize with most masks. ### Parameters #### Path Parameters - **mask** (ndarray) - Required - Input mask. - **bsize** (int) - Optional - Size of the patch. Defaults to 130. ### Returns Patch coordinates (y, x). ### Return type tuple ``` -------------------------------- ### cellpose.utils.outlines_list_single Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Get outlines of masks as a list to loop over for plotting for a single process. ```APIDOC ## cellpose.utils.outlines_list_single(masks) ### Description Get outlines of masks as a list to loop over for plotting. ### Parameters #### Path Parameters - **masks** (ndarray) - Required - masks (0=no cells, 1=first cell, 2=second cell,…) ### Returns List of outlines as pixel coordinates. ### Return type list ``` -------------------------------- ### Initialize Cellpose Model with GPU Support Source: https://github.com/mouseland/cellpose/blob/main/notebooks/run_Cellpose-SAM.ipynb This code snippet checks for GPU access and instantiates the Cellpose model. It requires necessary imports and will download model weights upon first use. ```python import numpy as np from cellpose import models, core, io, plot from pathlib import Path from tqdm import trange import matplotlib.pyplot as plt from natsort import natsorted io.logger_setup() # run this to get printing of progress #Check if colab notebook instance has GPU access if core.use_gpu()==False: raise ImportError("No GPU access, change your runtime") model = models.CellposeModel(gpu=True) ``` -------------------------------- ### Load Images from Directory Source: https://github.com/mouseland/cellpose/blob/main/notebooks/run_Cellpose-SAM.ipynb Configure the input directory and image extension to load image files. The code verifies the directory's existence and lists all matching image files, excluding mask and flow files. ```python # *** change to your google drive folder path *** dir = "/content/gdrive/MyDrive/PATH-TO-FILES/" dir = Path(dir) if not dir.exists(): raise FileNotFoundError("directory does not exist") # *** change to your image extension *** image_ext = ".tif" # list all files files = natsorted([f for f in dir.glob("*"+image_ext) if "_masks" not in f.name and "_flows" not in f.name]) if(len(files)==0): raise FileNotFoundError("no image files found, did you specify the correct folder and extension?") else: print(f"{len(files)} images in folder:") for f in files: print(f.name) ``` -------------------------------- ### cellpose.utils.outlines_list_multi Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Get outlines of masks as a list to loop over for plotting using multiprocessing. ```APIDOC ## cellpose.utils.outlines_list_multi(masks, num_processes=None) ### Description Get outlines of masks as a list to loop over for plotting. ### Parameters #### Path Parameters - **masks** (ndarray) - Required - masks (0=no cells, 1=first cell, 2=second cell,…) - **num_processes** (int) - Optional - Number of processes to use for multiprocessing. ### Returns List of outlines as pixel coordinates. ### Return type list ``` -------------------------------- ### cellpose.utils.outlines_list Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Get outlines of masks as a list to loop over for plotting. This function is a wrapper for outlines_list_single and outlines_list_multi. ```APIDOC ## cellpose.utils.outlines_list(masks, multiprocessing_threshold=1000, multiprocessing=None) ### Description Get outlines of masks as a list to loop over for plotting. ### Parameters #### Path Parameters - **masks** (ndarray) - Required - Array of masks. - **multiprocessing_threshold** (int) - Optional - Threshold for enabling multiprocessing. Defaults to 1000. - **multiprocessing** (bool) - Optional - Flag to enable multiprocessing. Defaults to None. ### Returns List of outlines. ### Return type list ### Raises **None** ``` -------------------------------- ### Initialize and Run Cellpose Segmentation Source: https://context7.com/mouseland/cellpose/llms.txt Initializes the CellposeModel with GPU support and segments a single 2D image. Demonstrates basic segmentation with default parameters and custom parameter tuning for difficult images. Also shows batch processing of multiple images. ```python from cellpose import models, io import numpy as np # Initialize model with GPU support model = models.CellposeModel(gpu=True) # Load and segment a single 2D image img = io.imread("cell_image.tif") masks, flows, styles = model.eval(img, diameter=30, flow_threshold=0.4) # masks: labeled array where 0=background, 1,2,...=cell labels # flows: list containing [RGB flow visualization, XY flows, cell probability, pixel destinations] # styles: style vector (zeros in v4+) print(f"Found {masks.max()} cells") # Segment with custom parameters for difficult images masks, flows, styles = model.eval( img, diameter=50, # Expected cell diameter in pixels cellprob_threshold=-1.0, # Lower threshold finds more/larger masks flow_threshold=0.6, # Higher threshold = stricter quality control min_size=25, # Minimum mask size in pixels normalize=True # Normalize intensity to 1st-99th percentile ) # Batch processing multiple images images = [io.imread(f"image_{i}.tif") for i in range(10)] results = [model.eval(img, diameter=30) for img in images] all_masks = [r[0] for r in results] ``` -------------------------------- ### Run Cellpose-SAM on Your Data (Google Drive) Source: https://github.com/mouseland/cellpose/blob/main/README.md This notebook demonstrates how to run Cellpose-SAM on your own data by mounting your Google Drive. It's useful for users who want to process their images directly within the Colab environment. ```python from cellpose import models import matplotlib.pyplot as plt import skimage.io # Load the model model = models.Cellpose(model_type='cyto') # or 'nuclei', or 'cyto3d', or 'nuclei3d' # Define image path img = skimage.io.imread('path/to/your/image.tif') # Run segmentation masks, flows, styles, diams = model.eval(img, diameter=None, flow_threshold=0.4, cellprob_threshold=0.0, ambient_threshold=0.0) # Plot results plt.figure(figsize=(10,10)) plt.imshow(masks, cmap='magma') plt.show() ``` -------------------------------- ### Activate conda environment Source: https://github.com/mouseland/cellpose/blob/main/README.md Activates the 'cellpose' conda environment, making its installed packages accessible in your current terminal session. ```sh conda activate cellpose ``` -------------------------------- ### Get Mask Edges Source: https://context7.com/mouseland/cellpose/llms.txt Identifies the edges of masks based on a specified distance threshold. This can be used to refine mask boundaries. ```python from cellpose import utils import numpy as np # Get mask edges with distance threshold edges = utils.masks_to_edges(masks, threshold=1.0) ``` -------------------------------- ### Add User-Trained Model via Command Line Source: https://github.com/mouseland/cellpose/blob/main/docs/models.md Add a user-trained model to the Cellpose path using the command line interface. This makes the model available in the GUI. ```bash python -m cellpose --add_model /full/path/to/model ``` -------------------------------- ### Get Mask Outlines Source: https://context7.com/mouseland/cellpose/llms.txt Extracts the outlines of segmented masks, useful for visualization or further processing. Multiprocessing can speed up this operation on large datasets. ```python from cellpose import utils import numpy as np # Get mask outlines for visualization outlines = utils.outlines_list(masks, multiprocessing=True) ``` -------------------------------- ### Export Cellpose Model Help Source: https://github.com/mouseland/cellpose/blob/main/docs/models.md Display help information for the export.py script to understand its usage and available options for model export. ```bash python export.py --help ``` -------------------------------- ### Get Mask Statistics Source: https://context7.com/mouseland/cellpose/llms.txt Calculates morphological statistics for each mask, including convexity, solidity, and compactness. These metrics can help characterize cell shapes. ```python from cellpose import utils import numpy as np # Get mask statistics convexity, solidity, compactness = utils.get_mask_stats(masks) ``` -------------------------------- ### Cellpose Training Script Arguments Source: https://github.com/mouseland/cellpose/blob/main/docs/do3d.md This is the full help message for the `make_train.py` script, detailing input image arguments and algorithm parameters. Configure options like `--dir`, `--anisotropy`, `--crop_size`, and `--nimg_per_tif` to customize data preparation. ```default python cellpose\gui\make_train.py --help usage: make_train.py [-h] [--dir DIR] [--image_path IMAGE_PATH] [--look_one_level_down] [--img_filter IMG_FILTER] [--channel_axis CHANNEL_AXIS] [--z_axis Z_AXIS] [--chan CHAN] [--chan2 CHAN2] [--invert] [--all_channels] [--anisotropy ANISOTROPY] [--sharpen_radius SHARPEN_RADIUS] [--tile_norm TILE_NORM] [--nimg_per_tif NIMG_PER_TIF] [--crop_size CROP_SIZE] cellpose parameters options: -h, --help show this help message and exit input image arguments: --dir DIR folder containing data to run or train on. --image_path IMAGE_PATH if given and --dir not given, run on single image instead of folder (cannot train with this option) --look_one_level_down run processing on all subdirectories of current folder --img_filter IMG_FILTER end string for images to run on --channel_axis CHANNEL_AXIS axis of image which corresponds to image channels --z_axis Z_AXIS axis of image which corresponds to Z dimension --chan CHAN channel to segment; 0: GRAY, 1: RED, 2: GREEN, 3: BLUE. Default: 0 --chan2 CHAN2 nuclear channel (if cyto, optional); 0: NONE, 1: RED, 2: GREEN, 3: BLUE. Default: 0 --invert invert grayscale channel --all_channels use all channels in image if using own model and images with special channels --anisotropy ANISOTROPY anisotropy of volume in 3D algorithm arguments: --sharpen_radius SHARPEN_RADIUS high-pass filtering radius. Default: 0.0 --tile_norm TILE_NORM tile normalization block size. Default: 0 --nimg_per_tif NIMG_PER_TIF number of crops in XY to save per tiff. Default: 10 --crop_size CROP_SIZE size of random crop to save. Default: 512 ``` -------------------------------- ### Check GPU and Import Libraries Source: https://github.com/mouseland/cellpose/blob/main/notebooks/run_cellpose3.ipynb Verifies GPU availability and imports essential libraries for Cellpose operations. This step is crucial for performance. ```python !nvcc --version !nvidia-smi import os, shutil import numpy as np import matplotlib.pyplot as plt from cellpose import core, utils, io, models, metrics from glob import glob use_GPU = core.use_gpu() yn = ['NO', 'YES'] print(f'>>> GPU activated? {yn[use_GPU]}') ``` -------------------------------- ### Command Line Model Training Source: https://github.com/mouseland/cellpose/blob/main/docs/restore.md Train image restoration models from the command line. Specify image directory, noise type, segmentation model, and mean diameter. ```bash python cellpose/denoise.py --dir /path/to/images --noise_type poisson --seg_model_type cyto2 --diam_mean 30. ``` -------------------------------- ### Get Mask Outlines with Cellpose Utils Source: https://context7.com/mouseland/cellpose/llms.txt Extracts outlines from segmentation masks for visualization or further processing. The `outlines_list` function returns a list of outlines, where each outline is a set of points. ```python # Get mask outlines for plotting outlines = utils.outlines_list(masks) for o in outlines: print(f"Outline has {len(o)} points") ``` -------------------------------- ### Run SAMCell and Omnipose Models Source: https://github.com/mouseland/cellpose/blob/main/paper/cpsam/benchmark_all_sam.ipynb This code snippet demonstrates how to run the SAMCell and Omnipose models by inserting the SAMCell source path and calling their respective run functions. Ensure the SAMCell source directory is correctly added to the system path. ```python import sys sys.path.insert(0, "/github/SAMCell/src/") benchmarks.run_samcell() benchmarks.run_omnipose() ``` -------------------------------- ### Basic CLI Segmentation Source: https://context7.com/mouseland/cellpose/llms.txt Performs basic cell segmentation on all images within a specified directory and saves the results as PNG files. This is a starting point for batch processing. ```bash # Basic segmentation on a folder of images python -m cellpose --dir /path/to/images/ --save_png ``` -------------------------------- ### Initialize DenoiseModel with Nuclear Channel Support Source: https://github.com/mouseland/cellpose/blob/main/docs/restore.md Initialize DenoiseModel with support for a nuclear channel (chan2=True). This allows restoration of a specific nuclear channel in two-channel images. ```python from cellpose import denoise dn = denoise.DenoiseModel(model_type="denoise_cyto3", gpu=True, chan2=True) imgs_dn = dn.eval(imgs, channels=[1,2], diameter=50.) ``` -------------------------------- ### Calculate Object Diameters Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Calculates the median diameter and an array of individual diameters for objects within a given set of masks. Assumes masks are labeled with integers starting from 1. ```python import numpy as np masks = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0]]) diameters(masks) ``` -------------------------------- ### Configure Image Directories and Mask Extension Source: https://github.com/mouseland/cellpose/blob/main/notebooks/train_Cellpose-SAM.ipynb Set the input directory for your images and optionally a directory for test files. Specify the extension for mask files, which can be '.npy' for Cellpose GUI output or '.masks.tif' for TIFF labels. ```python # *** change to your google drive folder path *** train_dir = "/content/gdrive/MyDrive/PATH-TO-FILES/" if not Path(train_dir).exists(): raise FileNotFoundError("directory does not exist") test_dir = None # optionally you can specify a directory with test files # *** change to your mask extension *** masks_ext = "_seg.npy" # ^ assumes images from Cellpose GUI, if labels are tiffs, then "_masks.tif" ``` -------------------------------- ### Load and Batch Process Folder of Images Source: https://github.com/mouseland/cellpose/blob/main/notebooks/run_Cellpose-SAM.ipynb Loads all images from a folder into memory first, then runs Cellpose-SAM segmentation in batches. This approach is efficient for smaller images that can be batched together on the GPU. Masks are then saved. ```python print("loading images") imgs = [io.imread(files[i]) for i in trange(len(files))] print("running cellpose-SAM") masks, flows, styles = model.eval(imgs, batch_size=32, flow_threshold=flow_threshold, cellprob_threshold=cellprob_threshold, normalize={"tile_norm_blocksize": tile_norm_blocksize}) print("saving masks") for i in trange(len(files)): f = files[i] io.imsave(dir / (f.stem + "_masks" + masks_ext), masks[i]) ``` -------------------------------- ### Logging Functions Source: https://github.com/mouseland/cellpose/blob/main/docs/api.md Functions for setting up and managing logging. ```APIDOC ## cellpose.io.logger_setup(cp_path='.cellpose', logfile_name='run.log', stdout_file_replacement=None) ### Description Set up logging to a file and stdout (or a file replacement). Creates the log directory if it doesn’t exist, removes any existing log file, and configures the root logger to write INFO-level and above messages to both a log file and stdout (or a replacement file). ### Parameters #### Path Parameters - **cp_path** (str) - Optional - Directory name under the user’s home directory for log output. Default is ".cellpose". #### Query Parameters - **logfile_name** (str) - Optional - Name of the log file created inside cp_path. Default is "run.log". - **stdout_file_replacement** (str or None) - Optional - If provided, log output is written to this file path instead of stdout. ### Returns - **logger** (logging.Logger) - Configured logger for this module. Only INFO and above messages are emitted by default. To enable debug output, call `logger.setLevel(logging.DEBUG)` on the returned logger. ### Notes The log file is deleted and recreated on each call. ``` -------------------------------- ### Reinstall PyQt5 to Resolve SIP Issues Source: https://github.com/mouseland/cellpose/blob/main/docs/installation.md If you encounter a 'No module named PyQt5.sip' error, try uninstalling and then reinstalling PyQt5 and related tools. ```bash pip uninstall pyqt5 pyqt5-tools pip install pyqt5 pyqt5-tools pyqt5.sip ``` -------------------------------- ### Cellpose CLI Training Option: --test_dir Source: https://github.com/mouseland/cellpose/blob/main/docs/train.md Specifies the folder containing test data. This option is optional. ```bash --test_dir TEST_DIR ``` -------------------------------- ### Run Distributed Cellpose on Workstation Source: https://github.com/mouseland/cellpose/blob/main/docs/distributed.md Execute distributed Cellpose segmentation on a local workstation by specifying worker and CPU resources. This example demonstrates how to configure Cellpose model parameters and evaluation settings for large datasets. ```python from cellpose.contrib.distributed_segmentation import distributed_eval # parameterize cellpose however you like model_kwargs = {'gpu':True, 'model_type':'cyto3'} # can also use 'pretrained_model' eval_kwargs = {'diameter':30, 'z_axis':0, 'channels':[0,0], 'do_3D':True, } # define compute resources for local workstation cluster_kwargs = { 'n_workers':1, # if you only have 1 gpu, then 1 worker is the right choice 'ncpus':8, 'memory_limit':'64GB', 'threads_per_worker':1, } # run segmentation # outputs: # segments: zarr array containing labels # boxes: list of bounding boxes around all labels (very useful for navigating big data) segments, boxes = distributed_eval( input_zarr=large_zarr_array, blocksize=(256, 256, 256), write_path='/where/zarr/array/containing/results/will/be/written.zarr', model_kwargs=model_kwargs, eval_kwargs=eval_kwargs, cluster_kwargs=cluster_kwargs, ) ``` -------------------------------- ### Initialize CellposeModel and Evaluate Images Source: https://github.com/mouseland/cellpose/blob/main/docs/settings.md Initializes the CellposeModel and runs segmentation on a list of images. Ensure CellposeModel is used instead of the deprecated Cellpose class. ```python from cellpose import models from cellpose.io import imread model = models.CellposeModel(gpu=True) files = ['img0.tif', 'img1.tif'] imgs = [imread(f) for f in files] masks, flows, styles, diams = model.eval(imgs, flow_threshold=0.4, cellprob_threshold=0.0) ``` -------------------------------- ### Check GPU and Instantiate Cellpose Model Source: https://github.com/mouseland/cellpose/blob/main/notebooks/test_Cellpose-SAM.ipynb Checks for GPU availability and instantiates the Cellpose model. This code requires GPU access and will download model weights upon initialization. Ensure your runtime has GPU enabled. ```python import numpy as np from cellpose import models, core, io, plot from pathlib import Path from tqdm import trange import matplotlib.pyplot as plt io.logger_setup() # run this to get printing of progress #Check if colab notebook instance has GPU access if core.use_gpu()==False: raise ImportError("No GPU access, change your runtime") model = models.CellposeModel(gpu=True) ``` -------------------------------- ### Run Windows Executable with CLI Arguments Source: https://github.com/mouseland/cellpose/blob/main/README.md Execute Cellpose on Windows using the command-line interface with specified arguments for batch processing. ```bash cellpose.exe --dir Pictures/ --chan 2 --save_png ```