micro_sam

Segment Anything for Microscopy

Segment Anything for Microscopy implements automatic and interactive analysis for microscopy data. It is built on Segment Anything 2 (SAM2) by Meta AI and specializes it for microscopy and other biomedical imaging data. Its core components are:

  • The micro_sam tools for interactive image analysis, built as napari plugin.
  • The micro-sam2 models, which are trained on publicly available microscopy data.
  • The micro_sam library to apply μSAM2 to 2d and 3d data, to track objects over time, and to finetune it on your data.

Based on these components micro_sam enables interactive and automatic segmentation, classification, and tracking in microscopy. Such as interactive cell segmentation from bounding boxes:

box-prompts

The current version of micro_sam (micro-sam2) is based on SAM2. The functionality of the previous version, based on the original Segment Anything model (SAM1), is still available in the micro_sam.v1 subpackage and in the micro_sam v1 command line tools.

If you run into any problems or have questions, please open an issue or contact us via image.sc using the tag micro-sam. You can follow recent updates on micro_sam in our news feed.

Quickstart

You can install micro_sam in a new environment via mamba:

mamba create -n micro-sam -c conda-forge "micro_sam>=2" python=3.12
mamba activate micro-sam

If you have an NVIDIA GPU, use the command for your system from the installation section, which also contains the other installation options.

After installing micro_sam, you can start napari from within your environment using

napari

After starting napari, you can select the annotation tool you want to use from Plugins -> Segment Anything for Microscopy. See the annotation tool section for details.

You can also start the annotation tools and the automatic segmentation from the command line:

# Interactive segmentation of a 2d or 3d image.
micro_sam annotator segmentation -i image.tif
# Automatic segmentation of an image.
micro_sam inference segmentation -i image.tif -o segmentation.tif

See the command line section for details.

The micro_sam python library can be imported via

import micro_sam

It is explained in more detail here.

We also have a quick start notebook here.

We provide different finetuned models for microscopy. See finetuned models for details on the available models. You can also train models on your own data, see here for details.

Citation

Please refer to the citation section of our README for the up-to-date citation guidelines.

Installation

There are three ways to install micro_sam:

  • From pip to use all functionality and install via pip.
  • From conda to use all functionality and install in an encapsulated environment.
  • From source for setting up a development environment to use the latest version and to change and contribute to our software.

You can find more information on the installation and how to troubleshoot it in the FAQ section.

From pip

pip is the default python package manager. You can install micro_sam via pip with the command:

pip install micro_sam

Note: when using pip you have to manage your python environments yourself. For example, you could create a conda environment and install micro_sam via pip in there, or use venv for this. uv is a faster alternative to pip that also creates the environment for you:

uv venv --python 3.12
uv pip install micro_sam

Check these points for your system before you install via pip:

  • Windows with an NVIDIA GPU: the PyTorch packages on PyPI only support the CPU on Windows. Install PyTorch for your GPU from pytorch.org first, e.g. pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126, and then install micro_sam.
  • Older NVIDIA GPUs (e.g. V100): the default PyTorch packages on PyPI do not support them any more. Install PyTorch from the cu126 index as described above.
  • Mac with an Intel CPU: PyPI has no recent PyTorch packages for these computers. Install micro_sam from conda instead.

The AnyUp upsampling option of the pixel and object classification tools needs AnyUp. It is not available on PyPI or conda-forge, so it has to be installed from GitHub:

pip install git+https://github.com/wimmerth/anyup

To use the SAM1 vit_t (MobileSAM) model of the previous version (micro_sam.v1), you have to additionally install MobileSAM in the environment where micro_sam was installed via pip. It is not available on PyPI, so it has to be installed from GitHub:

pip install git+https://github.com/ChaoningZhang/MobileSAM.git

From conda

conda is a python package manager. We recommend to install it via Miniforge, which also provides mamba, a faster drop-in replacement for conda. You can also look into our installation FAQs to set it up on your system. We recommend to use mamba from a recent Miniforge (version 25.3.1 or newer) or micromamba to install micro_sam. conda needs a lot more time and memory to install micro_sam (see the installation FAQ). If you use conda, replace mamba by conda in the commands below.

IMPORTANT: Do not install micro_sam in the base conda environment. Create a new environment for it, as described below. Do not use the defaults channel of Anaconda or Miniconda, only conda-forge.

Create a new environment with micro_sam (here called micro-sam) with the command for your system:

  • Computers without an NVIDIA GPU (including Macs):
mamba create -n micro-sam -c conda-forge "micro_sam>=2" python=3.12
  • Linux with an NVIDIA GPU:
mamba create -n micro-sam -c conda-forge "micro_sam>=2" python=3.12 "pytorch=*=cuda*" "cuda-version=12"
  • Windows with an NVIDIA GPU:
mamba create -n micro-sam -c conda-forge "micro_sam>=2" python=3.12 "pytorch=*=cuda*"

and then activate it via

mamba activate micro-sam

The NVIDIA GPU commands make sure that a GPU version of PyTorch is installed. Without "pytorch=*=cuda*", conda / mamba can install a PyTorch version that only supports the CPU, even on a computer with a GPU. "cuda-version=12" selects a PyTorch version that supports all NVIDIA drivers for CUDA 12 or newer and older GPUs such as the V100. You can check that micro_sam uses the GPU with micro_sam info.

"micro_sam>=2" makes sure that you get the current version: if the current version cannot be installed together with other packages, e.g. in an existing environment, you get an error instead of an old version.

The AnyUp upsampling option of the pixel and object classification tools needs AnyUp. Install it with pip in the conda environment, since it is not available on PyPI or conda-forge:

pip install git+https://github.com/wimmerth/anyup

From source

To install micro_sam from source, we recommend to first set up an environment with the necessary requirements:

To create one of these environments and install micro_sam into it follow these steps

  1. Clone the repository:
git clone https://github.com/computational-cell-analytics/micro-sam
  1. Enter it:
cd micro-sam
  1. Create the respective environment:
conda env create -f environment.yaml
  1. Activate the environment:
conda activate sam2
  1. Install micro_sam:
pip install --no-deps -e .

The environment already contains all dependencies. --no-deps stops pip from installing the PyPI sam2 on top of conda-forge's sam-2.

Annotation Tools

micro_sam provides applications for fast interactive 2d and 3d segmentation, tracking, and object and pixel classification. See an example for interactive cell segmentation in phase-contrast microscopy (left), interactive segmentation of mitochondria in volume EM (middle) and interactive tracking of cells (right).

The annotation tools can be started from the napari plugin menu (Plugins -> Segment Anything for Microscopy), the command line or from python scripts. They are built as napari plugin and make use of existing napari functionality wherever possible. If you are not familiar with napari, we recommend to start here. The micro_sam tools mainly use the point layer, shape layer and label layer.

The plugin menu contains the following tools:

The plugin menu also contains sample data, and Set cache directory for choosing where the models and embeddings are stored.

You can find additional information on the annotation tools in the FAQ section.

HINT: If you would like to start napari to use micro-sam from the plugin menu, you must start it by activating the environment where micro-sam has been installed using:

conda activate <ENVIRONMENT_NAME>
napari

All tools need the image embeddings, which you compute with Compute Embeddings after selecting the image and the model. Tiling (in Embedding Settings) is the most important setting for large images, see the question on high-resolution images in the FAQ. Keep the image layer at the bottom of the napari layer list, so that the prompts, annotations and segmentations are shown on top of it.

The segmentation and tracking tools work best with a GPU or on a Mac with an M-series chip. On a CPU they are slow, and 3d segmentation and automatic tracking take very long. The classifiers also work well on a CPU.

The videos for the previous version show the general workflow, but the user interface has changed since then: 2d annotation, 3d annotation and tracking.

Segmentation Annotator

The segmentation annotator is used for 2d images and 3d volumes. It can be started by

The tool detects if the image is 2d, 2d with color channels, or 3d. You can change this in the embedding menu if the detection is wrong, for example for a 3d array that is a 2d image with channels.

The tool uses the following napari layers:

  • prompts: shape layer for box and scribble prompts. A rectangle, ellipse or polygon marks the object, like a box. A path or line (Add path, Add polyline or Add line in the layer controls) is a scribble, which can be positive (on the object) or negative (outside of it).
  • point_prompts: point layer for point prompts. Positive prompts (green points) mark the object you want to segment, negative prompts (red points) mark the outside of the object.
  • current_object: label layer for the object(s) you are currently segmenting.
  • auto_segmentation: label layer with the results of the automatic segmentation.
  • committed_objects: label layer with the objects that you have already segmented.

The tool has the following menus:

  • The embedding menu, for selecting the image and the model, and computing the image embeddings with Compute Embeddings. The Embedding Settings contain the settings for saving the embeddings to a file and loading them from it, for tiled embeddings of large images, for custom model weights and for the device.
  • The menu for interactive segmentation. Segment Object (or S) segments the object from the current prompts and shows it in current_object. Press T (or use the prompt dropdown) to switch the next point or scribble between positive and negative.
    • With Batched, several objects are segmented at once: one object per box or per positive point. Batched is not available for tiled embeddings or with scribble prompts.
    • For 3d data, Apply to Volume extends the segmentation of the current object through the whole volume. Otherwise only the current slice is segmented.
  • The menu for automatic segmentation. Automatic Segmentation segments all objects and shows them in auto_segmentation. The mode selects the method: apg, or AIS with the sparse or dense post-processing (see APG). Use sparse for cells and nuclei in light microscopy and dense for neurites in electron microscopy. apg refines the decoder predictions with automatically generated prompts and can be used for both. Automatic segmentation needs a model with a decoder, for example one of the micro-sam2 models.
    • The Advanced Settings are post-processing parameters. The model predictions are computed only once, so changing them and running again is fast.
    • For 3d data, Apply to Volume segments the whole volume. Otherwise only the current slice is segmented.
  • The menu for committing the segmentation. Commit (or C) transfers the result of the selected layer (current_object or auto_segmentation) to committed_objects. The layer of the last segmentation is selected automatically, but you can change it.
  • The menu for clearing the annotations. Clear Annotations (or Shift + C) clears the current prompts and the current segmentation.

Point, box and scribble prompts can be combined. You can also combine automatic and interactive segmentation: commit the result of Automatic Segmentation, and then segment the missing objects interactively and commit them.

Tracking Annotator

The tracking annotator is used for 2d timeseries. It can be started by

Most elements are the same as in the segmentation annotator:

  • The tracking settings: track_state marks that the object you are tracking divides in the current frame, and track_id selects which of the tracks after a division you are following.
  • The menu for interactive tracking: Segment Object (or S) segments the object in the current frame. With Apply to Volume, the object is tracked through the whole timeseries.
  • The menu for automatic tracking: Automatic Tracking segments each frame and links the objects across frames with trackastra. Keep the segmentation mode at sparse for cells. Automatic tracking can take quite long without a GPU.
  • Commit stores the tracks in committed_objects and shows them in the tracks layer. Export saves the tracking results in the Cell Tracking Challenge (CTC), GEFF or TrackMate XML format.

To track a cell that divides, use point prompts:

  1. Track the mother cell as usual. In the last frame before the division, place a point on it, set track_state to division and run Segment Object again with Apply to Volume.
  2. Go to the first frame after the division and place a point on one of the daughter cells. Set track_state back to track, set track_id to a new id (for example from 1 to 2), and track the daughter cell until its next division or the end of the timeseries.
  3. Go back to the first frame after the division, place a point on the other daughter cell, set track_id to the next new id (for example 3), and track it in the same way.

The tracking annotator only supports 2d image data with a time dimension. Volumetric data with a time dimension is not supported.

Object Classifier

The object classifier classifies segmented objects into the classes you choose. It can be started by:

Load an image and a segmentation (for example from the segmentation annotator), select the segmentation layer in the Segmentation dropdown, and compute the image embeddings as in the other tools. Then mark some objects of each class in the annotations layer with the paint brush: one brush stroke or dot per object is enough. You can add classes with Add Class, and switch to the previous or next class with Alt + Left and Alt + Right. Shift + S shows or hides the segmentation. Train and Predict (or Shift + T) trains a random forest classifier on the objects you have marked, using the image embeddings of each object as features, and applies it to all objects. The result is shown in the prediction layer. You can export the trained classifier and apply it to other images with micro_sam inference object-classification.

The classifiers can use other models than the segmentation and tracking tools. The Model dropdown offers the SAM2 models for Natural Images and the micro-sam2 models for Microscopy. With Advanced Models in the Embedding Settings, you can also select SAM1, SAM3, the micro_sam (SAM1) models, PathoSAM, MedicoSAM, DINOv2, DINOv3, UNI and UNI2-h. This also applies to the pixel classifier.

Pixel Classifier

The pixel classifier assigns a class to every pixel, for example to segment tissue types or cell compartments. It can be started by:

Draw brush strokes for each class in the annotations layer (switch classes as in the object classifier) and click Train and Predict (or Shift + T). A random forest classifier is trained on the image embeddings of the annotated pixels and applied to the whole image. The result is shown in the prediction layer. You can add more strokes where the prediction is wrong and train again. Optional settings add classical image features, or upsample the embeddings with AnyUp for finer details. You can export the trained classifier and apply it to other images with micro_sam inference pixel-classification.

Batch Annotator

The batch annotator runs one of the other tools for all images in a folder, one image after the other. This makes it convenient to annotate many images without having to restart the tool for every image. It can be started by

You select the task (segmentation, tracking, object classification or pixel classification), the folder with your images, a pattern for selecting a subset of the images (for example *.tif), and the folder where the results are saved. For object classification, you can also select a folder with one segmentation per image. The other options are the settings of the embedding menu. Click Annotate Images to start. Next Image (or N) saves the result of the current image and opens the next one. The classification tasks can also go back to the previous image (Shift + N), and with Keep Classifier the classifier is trained on the annotations of all images so far. Images that already have a result in the output folder are skipped, so you can continue an annotation session later. For segmentation, uncheck Continue Annotation to start again at the first image, for example to review the results.

Training a Model

The previous version of micro_sam had a graphical interface for finetuning. We have removed this in version 2. To train a model on your own data, use the command line (micro_sam train) or the python library instead, see training your own model.

Using the Command Line Interface (CLI)

micro_sam provides one command, micro_sam, with subcommands for annotation, automatic segmentation, embedding computation and training. Run micro_sam --help for an overview, and add --help to any subcommand for its options, for example micro_sam annotator segmentation --help.

The subcommands are:

  • micro_sam info: Display micro_sam and system information. micro_sam info --download <MODEL> downloads a model in advance.
  • micro_sam annotator: Start the annotation tools.
    • micro_sam annotator segmentation: Interactive segmentation of a 2d or 3d image.
    • micro_sam annotator tracking: Interactive tracking of cells in a timeseries.
    • micro_sam annotator batch: Annotation of all images in a folder, for segmentation, tracking, or object or pixel classification (--task).
    • micro_sam annotator object-classification: Train and apply an object classifier interactively.
    • micro_sam annotator pixel-classification: Train and apply a pixel classifier interactively.
  • micro_sam inference: Automatic prediction for one or many images.
    • micro_sam inference segmentation: Automatic instance segmentation. Select the method with --engine: ais (the default), apg or amg, see APG.
    • micro_sam inference tracking: Automatic tracking for a timeseries.
    • micro_sam inference object-classification and micro_sam inference pixel-classification: Apply a trained classifier.
  • micro_sam precompute-embeddings: Compute the image embeddings in advance and save them, so that the annotation tools and the automatic segmentation can reuse them.
  • micro_sam train: Train a model on your own data, see training your own model.
  • micro_sam train-generalist: Train a generalist model on the collection of datasets we use for the micro-sam2 models.
  • micro_sam v1: The commands of the previous version for SAM1 models, for example micro_sam v1 automatic_segmentation and micro_sam v1 evaluate.

The automatic segmentation uses the best post-processing parameters for the chosen model by default. You can change a parameter by passing it to micro_sam inference segmentation as --<PARAMETER_NAME> <VALUE>, for example --min_size 100 to remove smaller objects. The defaults are listed by micro_sam.v2.postprocessing.default_postprocessing (AIS) and micro_sam.v2.automatic_prompt_generation.default_prompt_generation (APG).

Some examples:

# Automatic segmentation of all tif images in a folder (quote the pattern so that the shell does not expand it).
micro_sam inference segmentation -i images/ -o segmentations/ --pattern '*.tif'

# Automatic segmentation with APG and a larger model.
micro_sam inference segmentation -i image.tif -o segmentation.tif -m hvit_b_cells --engine apg

# Automatic tracking of a timeseries, saved in the Cell Tracking Challenge format.
micro_sam inference tracking -i timeseries.tif -o tracking_result/

# Precompute the embeddings and start the annotator with them.
micro_sam precompute-embeddings -i image.tif -e embeddings.zarr -m hvit_t_cells
micro_sam annotator segmentation -i image.tif -e embeddings.zarr -m hvit_t_cells

# Train a model for interactive and automatic segmentation on your own data.
micro_sam train -i images/ --image_key '*.tif' -l labels/ --label_key '*.tif' --mode joint

Using the Python Library

The python library can be imported via

import micro_sam

The functionality for SAM2 and the micro-sam2 models is in the micro_sam.v2 subpackage:

micro_sam.object_classification and micro_sam.pixel_classification implement the object and pixel classifiers, and micro_sam.sam_annotator implements the annotation tools, which can also be started from python.

For example, automatic segmentation of an image with the micro-sam2 model for cells:

from micro_sam.v2.automatic_segmentation import automatic_instance_segmentation, get_predictor_and_segmenter

predictor, segmenter = get_predictor_and_segmenter(model_type="hvit_t_cells", segmentation_mode="ais")
segmentation = automatic_instance_segmentation(predictor, segmenter, input_path="image.tif")

The functionality of the previous version for SAM1 models is in the micro_sam.v1 subpackage, for example micro_sam.v1.instance_segmentation and micro_sam.v1.training.

We provide jupyter notebooks that demonstrate how to use the library here, and example scripts here. You can find the full library documentation by scrolling to the end of this page.

Training your Own Model

You can finetune the micro-sam2 models, or the SAM2 models, on your own data. We use this functionality to train the finetuned microscopy models. In fact the best results can be expected when finetuning on your own data, and it does not require much annotated training data to get significant improvements in model performance. So a good strategy is to annotate a few images with one of the provided models using our interactive annotation tools and, if the model does not work as well as required for your use-case, finetune it on the annotated data.

You need images and the corresponding label images, for example annotations created with the micro_sam annotation tools. The data can be:

  • image files, such as tif or png, given as single files, lists of files, or a folder and a pattern like *.tif.
  • container files, such as hdf5, zarr, n5 or OME-Zarr, given as the file path and the key of the data in the file.

The data can be 2d or 3d. The labels are instance segmentations, where each object has its own id, or class labels for semantic segmentation.

There are four training modes:

  • interactive: train for interactive segmentation (micro_sam.v2.training.train_sam2).
  • automatic: train the decoder for automatic segmentation (AIS, APG) together with the image encoder (micro_sam.v2.training.train_automatic).
  • joint: train for both interactive and automatic segmentation (micro_sam.v2.training.train_joint_sam2).
  • semantic: train for semantic segmentation into a given number of classes (micro_sam.v2.training.train_semantic).

When you start from a micro-sam2 model, for example hvit_t_cells, the training starts from its image encoder and its decoder. For semantic segmentation, only the output layer for the classes is new. A model trained in the interactive mode has no decoder, so it cannot be used for automatic segmentation.

micro_sam.v2.training.default_sam2_loader creates the data loaders for all modes. For example, to train for interactive and automatic segmentation on tif images:

from micro_sam.v2.training import default_sam2_loader, train_joint_sam2

loader_kwargs = dict(patch_shape=(512, 512), mode="joint", batch_size=1)
train_loader = default_sam2_loader("train/images", "*.tif", "train/labels", "*.tif", **loader_kwargs)
val_loader = default_sam2_loader("val/images", "*.tif", "val/labels", "*.tif", is_train=False, **loader_kwargs)
train_joint_sam2("my_model", "hvit_t_cells", train_loader=train_loader, val_loader=val_loader)

For a container file, pass the file path and the key, for example default_sam2_loader("data.h5", "raw", "data.h5", "labels", ...). For 3d training, pass a 3d patch_shape, for example (8, 512, 512).

The same is available in the command line with micro_sam train. For example:

# Train for interactive and automatic segmentation, with 10% of the files split off for validation.
micro_sam train -i images/ --image_key '*.tif' -l labels/ --label_key '*.tif' --mode joint

# Train for automatic segmentation on 3d data in hdf5 files.
micro_sam train -i train.h5 --image_key raw -l train.h5 --label_key labels \
    --val_images val.h5 --val_labels val.h5 --mode automatic --patch_shape 8,512,512

# Train for semantic segmentation into three classes.
micro_sam train -i images/ --image_key '*.png' -l labels/ --label_key '*.png' --mode semantic --num_classes 3

Run micro_sam train --help for all options.

The trained model is saved as checkpoints/<NAME>/best.pt. You can use it in the annotation tools and the automatic segmentation with the checkpoint_path argument in python, or with -c in the command line. The model size is read from the checkpoint.

To share your model, export it to the BioImage.IO model format with micro_sam.v2.bioimageio.export_sam2_model, see the export example. The exported model does interactive segmentation and, if it has a decoder, automatic segmentation.

Check out the finetuning notebook and the finetuning examples for more details. The training needs a GPU for reasonable training times. The number of objects per image (max_num_objects), the batch size, the patch shape and the model size have a strong impact on the GPU memory that is needed. If the training runs out of memory, reduce them. You can find further information on model training in the FAQ section.

Finetuned Models

In addition to the original SAM2 models, we provide micro-sam2 models that are finetuned on microscopy data. They are downloaded automatically the first time you use them.

In the annotation tools, you can select the model in the embedding menu: the Model dropdown selects the kind of model, and the model size dropdown (in the Embedding Settings) selects its size.

If you are using the CLI or the python library, then you can specify the model via the model_type parameter (-m in the CLI), which is a single name composed of the model size and the kind of model, for example hvit_t_cells.

We provide the following models (Model dropdown name in brackets):

  • The original SAM2 models (Natural Images): hvit_t, hvit_s, hvit_b and hvit_l. The letter after hvit is the size of the image encoder: tiny, small, base or large. These models support interactive segmentation and automatic mask generation (AMG), but not AIS or APG, because they have no decoder.
  • The micro-sam2 models for cells and nuclei in light microscopy and neurites in electron microscopy, in 2D and 3D (Microscopy): hvit_t_cells, hvit_s_cells, hvit_b_cells and hvit_l_cells.
  • The micro-sam2 model for mitochondria in electron microscopy (Mitochondria (EM)): hvit_s_em_mito.
  • The micro-sam2 model for nuclei in electron microscopy (Nuclei (EM)): hvit_s_em_nuclei.

The micro-sam2 models support interactive segmentation and all automatic segmentation methods (AMG, AIS and APG, see APG). The default model is hvit_t_cells.

Choosing a Model

As a rule of thumb:

  • Use the Microscopy models (hvit_*_cells) for segmenting cells or nuclei in light microscopy and neurites in electron microscopy, in 2D and 3D.
    • hvit_t_cells is the fastest and the default. The larger models (hvit_b_cells, hvit_l_cells) are more accurate, especially for automatic segmentation, but need more computational resources.
  • Use hvit_s_em_mito for segmenting mitochondria and hvit_s_em_nuclei for segmenting nuclei in electron microscopy.
  • For other use-cases, try one of the micro-sam2 models first, or one of the original SAM2 models (hvit_b, hvit_l) for interactive segmentation.
  • If none of the models works well enough for your data, finetune a model on your own data, see training your own model.

Models of the Previous Version

The SAM1 models of the previous version of micro_sam are still available in the micro_sam.v1 subpackage and the micro_sam v1 command line tools:

  • The original Segment Anything models: vit_h, vit_l, vit_b and vit_t (from MobileSAM).
  • The light microscopy models from Segment Anything for Microscopy: vit_l_lm, vit_b_lm and vit_t_lm.
  • The electron microscopy models: vit_l_em_organelles, vit_b_em_organelles and vit_t_em_organelles.
  • The medical imaging model from MedicoSAM: vit_b_medical_imaging.
  • The histopathology models from PathoSAM: vit_h_histopathology, vit_l_histopathology and vit_b_histopathology.

These models are also available in the BioImage.IO Model Zoo.

Older SAM1 Models

Older versions of the SAM1 models are available on Zenodo or on the BioImage.IO modelzoo:

v3 Models

An improved version of the light microscopy that were trained on a larger dataset compared to the v2 light microscopy models:

  • vit_t_lm: the ViT-Tiny model for segmenting cells and nuclei in LM.
  • vit_b_lm: the ViT-Base model for segmenting cells and nuclei in LM.
  • vit_l_lm: the ViT-Large model for segmenting cells and nuclei in LM.

v2 Models

The models at the point of the publication. The results reported in the paper refer to these models:

  • vit_t_lm: the ViT-Tiny model for segmenting cells and nuclei in LM.
  • vit_b_lm: the ViT-Base model for segmenting cells and nuclei in LM.
  • vit_l_lm: the ViT-Large model for segmenting cells and nuclei in LM.
  • vit_t_em_organelles: the ViT-Base model for segmenting mitochondria and nuclei in EM.
  • vit_b_em_organelles: the ViT-Base model for segmenting mitochondria and nuclei in EM.
  • vit_l_em_organelles: the ViT-Large model for segmenting mitochondria and nuclei in EM.

v1 Models

The initial models published with our preprint:

  • vit_b_em_boundaries: for segmenting compartments delineated by boundaries such as cells or neurites in EM.
  • vit_b_em_organelles: for segmenting mitochondria, nuclei or other organelles in EM.
  • vit_b_lm: for segmenting cells and nuclei in LM.
  • vit_h_em: for general EM segmentation.
  • vit_h_lm: for general LM segmentation.

We do not recommend to use these models since our new models improve upon them significantly. But we provide the links here in case they are needed to reproduce older segmentation workflows.

We provide additional models that were used for experiments in our publication on Zenodo:

APG

micro_sam supports three different methods for automatic instance segmentation:

  • Automatic Mask Generation (AMG) covers the image with a grid of points. These points are used as prompts and the resulting masks are merged via non-maximum suppression (NMS) to obtain the instance segmentation. This method has been introduced by the original SAM publication. It works with every model, also with the SAM2 models without a decoder.
  • Automatic Instance Segmentation (AIS) uses an additional segmentation decoder, which we introduced in the micro_sam publication. This decoder predicts the foreground probability, the distances to the object centers and boundaries, and the object boundaries. The post-processing derives the instances from these predictions.
  • Automatic Prompt Generation (APG) is an instance segmentation approach that we introduced in our μSAM++ paper. It derives point prompts from the predictions of the segmentation decoder (see AIS) and segments each object with the interactive part of the model. In 3d, it propagates the prompts through the volume.

AIS and APG need a model with a decoder, for example the micro-sam2 models (see finetuned models) or a model that you trained for automatic segmentation (see training your own model). A model that was trained for interactive segmentation only has no decoder, so AIS and APG are not available with it.

In our experiments, APG yields the best overall instance segmentation results, and AIS is the fastest. APG on volumes and timeseries needs a GPU.

The segmentation method can be selected in the annotation tools (the mode of the automatic segmentation menu), with --engine in the CLI and with segmentation_mode in micro_sam.v2.automatic_segmentation.get_predictor_and_segmenter. For details on how to use the different methods check out the automatic segmentation notebook and examples/automatic_segmentation.py.

Community Data Submissions

We are looking to further improve the micro_sam models by training on more diverse microscopy data. For this, we want to collect data where the models don't work well yet, and need your help!

If you are using micro_sam for a task where the current models don't do a good job, but you have annotated data and successfully fine-tuned a model, then you can submit this data to us, so that we can use it to train our next version of improved microscopy models. To do this, please either create an issue on github or a post on image.sc and:

  • Use a title "Data submission for micro_sam: ..." ("..." should be a title for your data, e.g. "cells in brightfield microscopy")
  • Briefly describe your data and add an image that shows the microscopy data and the segmentation masks you have.
  • Make sure to describe:
    • The imaging modality and the structure(s) that you have segmented.
    • The micro_sam model you have used for finetuning and segmenting the data.
      • You can also submit data that was not segmented with micro_sam, as long as you have sufficient annotations we are happy to include it!
    • How many images and annotations you have / can submit and how you have created the annotations.
      • You should submit at least 5 images / 100 annotated objects to have a meaningful impact. If you are unsure if you have enough data please go ahead and create the issue / post and we can discuss the details.
    • Which data-format your images and annotations are stored in. We recommend using either tif images or ome.zarr files.
  • Please indicate that you are willing to share the data for training purpose (see also next paragraph).

Once you have created the post / issue, we will check if your data is suitable for submission or discuss with you how it could be extended to be suitable. Then:

  • We will share an agreement for data sharing. You can find a draft here.
  • You will be able to choose how you want to submit / publish your data.
    • Share it under a CC0 license. In this case, we will use the data for re-training and also make it publicly available as soon as the next model versions become available.
    • Share it for training with the option to publish it later. For example, if your data is unpublished and you want to only published once the respective publication is available. In this case, we will use the data for re-training, but not make it freely available yet. We will check with you peridiodically to see if your data can now be published.
    • Share it for training only. In this case, we will re-train the model on it, but not make it publicly available.
  • We encourage you to choose the first option (making the data available under CC0).
  • We will then send you a link to upload your data, after you have agreed to these terms.

FAQ

Here we provide frequently asked questions and common issues. If you encounter a problem or question not addressed here feel free to open an issue or to ask your question on image.sc with the tag micro-sam.

Installation questions

0. I am not familiar with conda / mamba / micromamba and would like to get started with a python package manager.

If you are getting started from scratch, we recommend using micromamba to setup your own package manager and creating a new environment with the required dependencies. You can install micromamba by following the instructions here under the Automatic install section. If you are using Linux, macOS, or Git Bash on Windows, the simplest way to of installing micromamba is to simply execute the installation script below in your preferred shell:

"${SHELL}" <(curl -L micro.mamba.pm/install.sh)

If you are using Windows PowerShell, you should be able to install micromamba by running the following command:

Invoke-Expression ((Invoke-WebRequest -Uri https://micro.mamba.pm/install.ps1 -UseBasicParsing).Content)

Once you have micromamba installed, you can create a new environment with the required dependencies by following the installation instructions for micro_sam (remember to replace conda by micromamba in the installation commands. For example: to check the list of available environments, conda env list becomes micromamba env list).

If you have any troubles in the aforementioned steps, remember to first check the official documentation for troubleshooting details.

1. How to install micro_sam?

The installation for micro_sam is supported in four ways: from pip, from conda, from source, and from installers. We recommend installation from pip or conda for most users. Check out our tutorial video to get started with micro_sam, briefly walking you through the installation process and how to start the tool.

2. I cannot install micro_sam using the installer, I am getting some errors.

The installer should work out-of-the-box on Windows and Linux platforms. Please open an issue to report the error you encounter.

NOTE: The installers enable using micro_sam without conda. However, we recommend the installation from pip, from conda, or from source to use all its features seamlessly. Specifically, the installers are out-of-date and currently only support the CPU and won't enable you to use the GPU (if you have one).

3. What is the minimum system requirement for micro_sam?

micro_sam works best with a GPU or on a Mac with an M-series chip, and with more than 8GB RAM. On a CPU, interactive 2d segmentation and the classifiers work, but they are slower. 3d segmentation and automatic tracking are too slow on a CPU for practical use. The resources the annotation tools of the previous version (based on SAM1) have been tested on are:

  • Windows:
    • Windows 10 Pro, Intel i5 7th Gen, 8GB RAM
    • Windows 10 Enterprise LTSC, Intel i7 13th Gen, 32GB RAM
    • Windows 10 Pro for Workstations, Intel Xeon W-2295, 128GB RAM
  • Linux:

    • Ubuntu 20.04, Intel i7 11th Gen, 32GB RAM
    • Ubuntu 22.04, Intel i7 12th Gen, 32GB RAM
  • Mac:

    • macOS Sonoma 14.4.1
      • M1 Chip, 8GB RAM
      • M3 Max Chip, 36GB RAM

Having a GPU will significantly speed up the annotation tools and especially the model finetuning.

micro_sam needs PyTorch 2.5 or newer. Apart from that, the tool and the library are not constrained to a specific PyTorch or CUDA version, so they should work fine with the standard PyTorch installation for your system.

5. I am missing a few packages (eg. ModuleNotFoundError: No module named 'elf.io). What should I do?

With the latest release 1.0.0, the installation from conda and source should take care of this and install all the relevant packages for you. So please reinstall micro_sam, following the installation guide.

6. Can I install micro_sam using pip?

Yes! We recently made available micro_sam with pip. Check out the installation guide for details.

7. I get the following error: importError: cannot import name 'UNETR' from 'torch_em.model'.

It's possible that you have an older version of torch-em installed. Similar errors could often be raised from other libraries, the reasons being: a) Outdated packages installed, or b) Some non-existent module being called. If the source of such error is from micro_sam, then a) is most likely the reason . We recommend installing the latest version following the installation instructions.

8. My system does not have a internet connection. Where should I put the model checkpoints for the micro-sam models?

The simplest way is to download the models on a computer with internet connection with micro_sam info --download <MODEL>, for example micro_sam info --download hvit_t_cells, and to copy the model cache directory to the computer without internet connection. You can find the model cache directory by running python -c "from micro_sam import util; print(util.get_model_cache_directory())".

You can also download the checkpoints by hand and move them to the model cache directory. The files must be named like the keys of FINETUNED_URLS in micro_sam/v2/util.py. A micro-sam2 model has two files, for example hvit_t_cells and hvit_t_cells_decoder.

# Find the model cache directory.
python -c "from micro_sam import util; print(util.get_model_cache_directory())"
# Create it, if it does not exist, and move the checkpoints there with the expected names.
mkdir -p <MODEL_CACHE_DIRECTORY>
mv <DOWNLOADED_MODEL> <MODEL_CACHE_DIRECTORY>/hvit_t_cells
mv <DOWNLOADED_DECODER> <MODEL_CACHE_DIRECTORY>/hvit_t_cells_decoder

9. napari crashes with a segmentation fault (Fatal Python error: Segmentation fault) when I open one of the micro_sam annotators (Linux).

This is caused by a corrupted or stale system font cache, not by micro_sam itself. Qt segfaults inside fontconfig while laying out text. This shows up in two common variants:

  • On launch, before any widget appears, while Qt renders the napari welcome screen. The crash traceback ends in libfontconfig (e.g. FcCharSetHasChar / FcCharSetFindLeafForward), reached via QFontEngineMultiFontConfig::shouldLoadFontEngineForCharacter during font fallback.
  • After the annotator opens, when the collapsible "Settings" section (from superqt) draws small arrow glyphs (▲ / ▼). Here Qt may resolve the default font to an unusable font file (e.g. a .woff web font) and Qt's bundled FreeType/HarfBuzz segfaults rendering those glyphs. The traceback ends in superqt/collapsible/_collapsible.py in _convert_string_to_icon.

Both have the same cause and the same fix. The most reliable fix is to clear the user font cache directory and rebuild it, since a stale cache often holds entries from several fontconfig versions (e.g. *.cache-7, *.cache-10, *.cache-11) that a newer fontconfig then misreads:

rm -rf ~/.cache/fontconfig && fc-cache -f

Rebuilding without clearing (fc-cache -f alone) is sometimes enough for the .woff variant, but is not reliable for the cross-version cache problem. You can verify the fix by checking that the default font no longer resolves to a .woff (or otherwise broken) file:

fc-match "Sans Serif"   # should return a real font such as NotoSans-Regular.ttf, not a .woff

10. napari fails to render with RuntimeError: Cannot FRAMEBUFFER object ... because it does not exist or OpenGL.error.Error: Attempt to retrieve context when no valid context (Linux / Wayland).

This is an OpenGL context mismatch, not a micro_sam or napari bug. napari renders points with the vispy gl+ backend, which routes OpenGL calls through PyOpenGL. On a Wayland session PyOpenGL defaults to its EGL backend and looks for the current context with eglGetCurrentContext(). However, when the napari window runs under XWayland (Qt falls back to the xcb platform because the Wayland Qt plugin is missing), the actual OpenGL context is a GLX context, which EGL cannot see. PyOpenGL then reports "no valid context" and the draw fails. The crash only appears once the canvas actually draws (e.g. after opening an image), not on the empty welcome screen.

To fix it, tell PyOpenGL to use the GLX backend so it matches the context Qt created. For a single run:

PYOPENGL_PLATFORM=glx napari

Or set it for the whole shell session and then launch napari:

export PYOPENGL_PLATFORM=glx
napari

To make it permanent for a conda / micromamba environment, add it to an activation script so it is set automatically on every activate:

mkdir -p "$CONDA_PREFIX/etc/conda/activate.d"
echo 'export PYOPENGL_PLATFORM=glx' > "$CONDA_PREFIX/etc/conda/activate.d/pyopengl_platform.sh"

11. The installation hangs at "Solving environment".

conda and mamba have to select compatible versions for several hundred packages to install micro_sam. How long this takes depends on the tool:

  • mamba (version 2, part of Miniforge 25.3.1 or newer) and micromamba need about 1 GB of memory and less than a minute.
  • conda needs about 5 GB of memory and several minutes. On a computer with 8 GB of memory this can take much longer, so that it seems to hang.
  • The old "classic" solver of conda (the default before conda 23.10, or if conda config --show solver shows classic) does not finish at all.

So please use mamba from a recent Miniforge or micromamba, and follow the installation instructions. Note that mamba version 1 (from Miniforge before 25.3.1) is as slow as conda.

12. I have an NVIDIA GPU, but micro_sam runs on the CPU.

Check the output of micro_sam info. If it shows a warning that PyTorch cannot use the GPU, conda / mamba installed a PyTorch version that only supports the CPU, or a version that does not support your NVIDIA driver. Create a new environment with the command for your system from the installation instructions, which contains "pytorch=*=cuda*". If you installed via pip on Windows, install PyTorch for your GPU from pytorch.org, see the pip installation instructions.

13. The installation succeeded, but I have an old version of micro_sam.

Check your version with micro_sam --version. conda / mamba install an older version without an error if the current version cannot be installed together with the other packages. This happens for example if you install micro_sam in an existing environment with Python 3.10 (micro_sam 2 needs Python 3.11 or newer). Create a new environment with the commands from the installation instructions. They contain "micro_sam>=2", which gives you an error instead of an old version. Note: micro_sam 2 cannot be installed from conda-forge on Linux with an ARM CPU (e.g. NVIDIA Grace) yet.

Usage questions

1. I have some microscopy images. Can I use the annotator tool for segmenting them?

Yes, you can use the annotator tool for:

  • Segmenting objects in 2d images (using automatic and/or interactive segmentation).
  • Segmenting objects in 3d volumes (using automatic and/or interactive segmentation for the entire object(s)).
  • Tracking objects over time in time-series data.
  • Segmenting objects in a series of 2d / 3d images.
  • In addition, you can finetune the Segment Anything / micro_sam models on your own microscopy data, in case the provided models do not suffice your needs. One caveat: You need to annotate a few objects before-hand (micro_sam has the potential of improving interactive segmentation with only a few annotated objects) to proceed with the supervised finetuning procedure.

2. Which model should I use for my data?

We provide the original SAM2 models (hvit_t, hvit_s, hvit_b and hvit_l) and the micro-sam2 models: hvit_t_cells, hvit_s_cells, hvit_b_cells and hvit_l_cells for cells and nuclei in light microscopy and neurites in electron microscopy (2D and 3D), hvit_s_em_mito for mitochondria and hvit_s_em_nuclei for nuclei in electron microscopy. You should first try the micro-sam2 model that best fits your segmentation task. If your segmentation problem does not meet these descriptions, or if these models don't work well, you can try one of the original SAM2 models for interactive segmentation, or finetune a model on your data. The letter after hvit denotes the size of the image encoder: t (tiny), s (small), b (base) and l (large). The smaller models are faster, the larger models are more accurate, especially for automatic segmentation. You can find more information on model choice here.

3. I have high-resolution microscopy images, micro_sam does not seem to work.

The model resizes every input to 1024 x 1024 pixels. Applying it to a much larger image shrinks the objects and leads to inferior results. To address this, micro_sam implements tiling: it cuts the input image into tiles of a fixed size (with a fixed overlap) and runs the model on the individual tiles. Tiling is turned on by default for images that are larger than 768 pixels, with a tile shape of 512 x 512 and an overlap (halo) of 128 pixels. You can change the tiling with the tile_shape and halo parameters:

  • In the annotation tools, set tile_x, tile_y, halo_x and halo_y in the Embedding Settings.
  • In a python script, pass them as tuples, e.g. tile_shape=(1024, 1024), halo=(256, 256). See also the wholeslide annotator example.
  • In the command line, pass them with --tile_shape and --overlap, e.g. --tile_shape 1024 1024 --overlap 256 256 for micro_sam annotator and --tile_shape 1024,1024 --overlap 256,256 for micro_sam inference.

NOTE: It's recommended to choose the halo so that it is larger than half of the maximal radius of the objects you want to segment.

4. The computation of image embeddings takes very long in napari.

micro_sam pre-computes the image embeddings produced by the image encoder, and (optionally) stores them on disc. If you are using a CPU, this step can take a while for 3d data or time-series (you will see a progress bar on the bottom right of napari). If you have access to a GPU without graphical interface (e.g. via a local computer cluster or a cloud provider), you can also pre-compute the embeddings there and then copy them over to your laptop / local machine to speed this up.

  • You can use the command micro_sam precompute-embeddings for this (it is installed with the rest of the software). You can specify the location of the pre-computed embeddings via the -e / --embedding_path argument.
  • You can cache the computed embedding in the napari tool (to avoid recomputing the embeddings again) by passing the path to store the embeddings in the embeddings_save_path option in the Embedding Settings drop-down. You can later load the pre-computed image embeddings by entering the path to the stored embeddings there as well.

5. Can I use micro_sam on a CPU?

Yes. Interactive segmentation of a 2d image is fast on a CPU. Computing the embeddings, automatic segmentation, and segmenting or tracking objects in volumes and time-series take longer without a GPU. Automatic prompt generation (APG) for volumes and time-series needs a GPU.

6. I generated some segmentations from another tool, can I use it as a starting point in micro_sam?

You can save and load the results from the committed_objects layer to correct segmentations you obtained from another tool (e.g. CellPose) or save intermediate annotation results. The results can be saved via File -> Save Selected Layers (s) ... in the napari menu-bar on top (see the tutorial videos for details). They can be loaded again by specifying the corresponding location via the segmentation_result parameter in the CLI or python script (2d and 3d segmentation). If you are using an annotation tool you can load the segmentation you want to edit as segmentation layer and rename it to committed_objects.

7. I am using micro_sam for segmenting objects. I would like to report the steps for reproducability. How can this be done?

The annotation steps and segmentation results can be saved to a Zarr file by providing the commit_path in the commit widget. This file will contain all relevant information to reproduce the segmentation.

NOTE: This feature is still under development and we have not implemented rerunning the segmentation from this file yet. See this issue for details.

8. I want to segment objects with complex structures. Both the default Segment Anything models and the micro_sam generalist models do not work for my data. What should I do?

micro_sam supports interactive annotation using positive and negative point prompts, box prompts and polygon drawing. You can combine multiple types of prompts to improve the segmentation quality. In case the aforementioned suggestions do not work as desired, micro_sam also supports finetuning a model on your data (see the next section on finetuning). We recommend the following: a) Check which of the provided models performs relatively good on your data, b) Choose the best model as the starting point to train your own specialist model for the desired segmentation task.

9. I am using the annotation tool and napari outputs the following error: While emmitting signal ... an error ocurred in callback ... This is not a bug in psygnal. See ... above for details.

These messages occur when an internal error happens in micro_sam. In most cases this is due to inconsistent annotations and you can fix them by clearing the annotations. We want to remove these errors, so we would be very grateful if you can open an issue and describe the steps you did when encountering it.

10. The objects are not segmented in my 3d data using the interactive annotation tool.

The first thing to check is: a) make sure you are using the latest version of micro_sam (pull the latest commit from main if your installation is from source, or update the installation from conda using conda update micro_sam), and b) make sure the tool treats your data as a 3d volume: you can check and change this in the embedding menu. For 3d images, it's important to pass the inputs in the python axis convention, ZYX. c) try using a different model, and add prompts in more slices of the object before you segment it in the volume with Apply to Volume.

11. I have very small or fine-grained structures in my high-resolution microscopic images. Can I use micro_sam to annotate them?

The models do not work well for very small or fine-grained objects (e.g. filaments). In these cases, you could try to use tiling to improve results (see question 3 above for details).

12. napari seems to be very slow for large images.

Editing (drawing / erasing) very large 2d images or 3d volumes is known to be slow at the moment, as the objects in the layers are stored in-memory. See the related issue.

13. While computing the embeddings (and / or automatic segmentation), a window stating: "napari" is not responding pops up.

This can happen for long running computations. You just need to wait a bit longer and the computation will finish.

14. I have 3D RGB microscopy volumes. How does micro_sam handle these images?

The expected shape of a 3D volume with channels is (Z, Y, X, C), with the channels in the last axis. A volume with 2 or 4 channels is mapped to 3 channels: 2 channels are padded with an empty channel, and of 4 channels the first 3 are used. A volume with a single channel is replicated to 3 channels, because the model expects 3-channel inputs.

15. I want to use a model stored in a different directory than the micro_sam cache. How can I do this?

The micro_sam command line tools (micro_sam annotator, micro_sam inference and micro_sam precompute-embeddings) accept the argument -c / --checkpoint to pass a model checkpoint. If you start a micro_sam annotator from the napari plugin menu, you can provide the path to the model checkpoint under the Embedding Settings drop-down in the custom weights path option. In python, pass it as checkpoint_path.

The model size is read from the checkpoint, so you do not have to match it with the model type.

For automatic segmentation, the model also needs its decoder. Give a checkpoint that holds the decoder, such as the best.pt of joint or automatic training, or a model file with its decoder file next to it: for example hvit_t_cells.pt with hvit_t_cells_decoder.pt. The decoder file is found by its name. In python and in the command line of the annotators, you can also give the decoder file with decoder_path (--decoder_path).

16. Some parameters in the annotation tools are unclear to me.

micro-sam has tooltips for menu options across all widgets (i.e. an information window will appear if you hover over name of the menu), which briefly describe the utility of the specific menu option.

17. I want to use an older version of the pretrained models.

The SAM1 models of the previous version are available in the micro_sam.v1 subpackage and the micro_sam v1 command line tools. Older versions of these models are still available on zenodo. You can find the download links for all of them here.

18. I would like to evaluate the instance segmentation quantitatively. Can you suggest how to do that?

micro_sam v1 evaluate computes the mean segmentation accuracy (introduced in the Pascal VOC challenge) of predicted instance segmentations with the corresponding ground-truth annotations. It works for segmentations from any method. Please see our paper (Methods -> Inference and Evaluation for more details about it) and micro_sam v1 evaluate --help for more details.

19. I get RuntimeError: GET was unable to find an engine to execute this computation or CUDA error: no kernel image is available for execution on the device on a V100 GPU ("or any older GPU").

PyTorch versions built for CUDA 13 (and the PyTorch packages for CUDA 13 on PyPI) do not support older GPUs such as the V100 any more. Here's what you can do to solve this issue:

  • conda / mamba: create the environment with "pytorch=*=cuda*" "cuda-version=12", see the installation instructions.
  • pip: install PyTorch from the cu126 index before installing micro_sam: pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126.
  • Run on CPU (slower, but works).

20. The automatic instance segmentation does a very poor job for my microscopy images.

This can have multiple reasons that you can address by choosing the best settings for your image:

  • First, choose the most suitable model for your image type and segmentation task:
    • hvit_t_cells (or a larger hvit_*_cells model) for any cell or nucleus segmentation task in light microscopy or related tasks such as segmentation of organoids or similar structures.
    • hvit_s_em_mito for segmenting mitochondria and hvit_s_em_nuclei for segmenting nuclei in electron microscopy.
  • Try the other automatic segmentation methods: APG is often more accurate than AIS, see APG.
  • If you have multi-channel images then you have to pass those in a format and channel order compatible with micro_sam:
    • If your image has 2 or 3 channels you can use it as is. The channels must be given in the last axis.
      • If you have images with a fluorescent marker staining the cytosol or membrane and another marker staining the nucleus, then pass the cytosol/membrane maker as first channel and the nucleus marker as second channel.
    • If you have more than 3 channels then you have to reduce the number of channels to 3, either by selecting the most relevant channels (see previous item) or by averaging or otherwise combining channels in a suitable fashion.
  • Large images are tiled by default (see question 3 above). If the objects are very large or very small compared to the tiles, change the tile shape and the halo.
  • If your image contains very small objects that you want to segment then decrease the minimum object size by passing a low value (e.g. 10) for min_size to the CLI / python function you are using.

If none of these steps help then the available micro_sam models are likely not well suited for your data. Note that you can still use micro_sam for your segmentation problem, but you will have to fine-tune your own model (see the next section).

Fine-tuning questions

1. I have a microscopy dataset I would like to fine-tune Segment Anything for. Is it possible using micro_sam?

Yes, you can finetune the micro-sam2 and SAM2 models on your own dataset. Here's how you can do it:

2. I would like to fine-tune Segment Anything on open-source cloud services (e.g. Kaggle Notebooks), is it possible?

Yes, you can fine-tune Segment Anything on your custom datasets on Kaggle (and BAND). Check out our tutorial notebook for this.

3. What kind of annotations do I need to finetune Segment Anything?

You need instance segmentation labels, i.e. each object of interest in your microscopy images has an individual id to uniquely identify it. You can obtain them with micro_sam's annotation tools. For training the decoder for automatic segmentation (the automatic and joint training modes), the segmentations must be dense (i.e. all objects per image are annotated). For training interactive segmentation only (the interactive mode), sparse segmentations (i.e. few objects per image are annotated) are fine. For semantic segmentation (the semantic mode), you need class labels.

4. I have finetuned Segment Anything on my microscopy data. How can I use it for annotating new images?

You can load your finetuned model by entering the path to its checkpoint in the custom weights path field in the Embedding Settings drop-down menu. If you are using the python library you can specify this path with the checkpoint_path parameter, and in the command line with -c / --checkpoint. A model that you trained in the interactive mode has no decoder, so you can use it for interactive segmentation, but not for automatic segmentation.

5. What is the background of the AIS (Automatic Instance Segmentation) feature in micro_sam?

micro_sam adds a segmentation decoder to the image encoder, for enabling faster and accurate automatic instance segmentation. The decoder predicts the foreground, the directed distances to the object center and boundary, and the object boundaries. The post-processing derives the instances from these predictions, see APG.

6. What is the background of the new APG (Automatic Prompt Generation) feature in micro_sam?

APG (automatic prompt generation) is an automatic instance segmentation method. It derives point prompts from the predictions of the segmentation decoder, and segments each object with these prompts with the interactive part of the model. You can use it with micro_sam inference segmentation --engine apg, with segmentation_mode="apg" in python, and in the annotation tools. See APG for details.

7. I want to finetune only the Segment Anything model without the additional instance decoder.

The decoder for automatic segmentation is optional. Train with the interactive mode to finetune only for interactive segmentation, with the automatic mode to finetune only the decoder and the image encoder, or with the joint mode for both. Training with the decoder will increase training times, but will enable you to use AIS and APG. See training your own model for details.

8. I have a NVIDIA RTX 4090Ti GPU with 24GB VRAM. Can I finetune Segment Anything?

Yes, finetuning is possible on most consumer-grade GPUs. The number of objects per image (max_num_objects, --max_num_objects in the command line) has the biggest impact on the GPU memory consumption and the quality of the finetuned model. The batch size, the patch shape and the model size also matter. If the training runs out of memory, reduce them, for example the number of objects per image.

9. I want to create a dataloader for my data, to finetune Segment Anything.

micro_sam.v2.training.default_sam2_loader creates the data loaders for image files (e.g. tif or png) and for container files (e.g. hdf5, zarr, n5, OME-Zarr), for all training modes, see training your own model. It is based on torch-em. See the tutorial notebook on how to create dataloaders using torch-em and the documentation for details on creating your own datasets and dataloaders.

NOTE: If you have images with large input shapes with a sparse density of instance segmentations, we recommend using a sampler for choosing the patches with valid segmentation. You can pass it to default_sam2_loader with the sampler argument.

10. How can I evaluate a model I have finetuned?

To validate a model for your data, you have different options, depending on the task you want to solve and whether you have segmentation annotations for your data.

We provide an example notebook that shows how to use this evaluation functionality.

Contribution Guide

Everyone who takes part in this project must follow our Code of Conduct.

Discuss your ideas

We welcome new contributions! First, discuss your idea by opening a new issue in micro-sam. This allows you to ask questions, and have the current developers make suggestions about the best way to implement your ideas.

Clone the repository

We use git for version control.

Clone the repository, and check out the development branch:

$ git clone https://github.com/computational-cell-analytics/micro-sam.git
$ cd micro-sam
$ git checkout dev

Create your development environment

We use conda to manage our environments. If you don't have this already, install miniforge to get started. You can also use mamba or micromamba instead of conda in the commands below.

Create the environment, install the developer dependencies, and install micro-sam as an editable installation:

$ conda env create -f environment.yaml
$ conda activate sam2
$ python -m pip install -r requirements-dev.txt
$ python -m pip install --no-deps -e .

The environment already contains all dependencies. --no-deps stops pip from installing the PyPI sam2 on top of conda-forge's sam-2.

Make your changes

Make your changes on a new branch that starts from the development branch:

$ git checkout dev
$ git checkout -b my-new-feature

We use google style python docstrings to create documentation for all new code.

You may also find it helpful to look at the Python library documentation, which explains the organization of the micro-sam code. The SAM2 code is in micro_sam/v2, the SAM1 code of the previous version is in micro_sam/v1 and the napari tools are in micro_sam/sam_annotator.

Check the code style

We use flake8 to check the code style, with a maximum line length of 120 characters. Run it before you open a pull request:

$ flake8 --max-line-length=120 --per-file-ignores="__init__.py:F401" micro_sam/

Testing

Run the tests

The tests for micro-sam are run with pytest.

To run all tests:

$ pytest

The full test suite takes a long time and downloads several models. While you develop, run only the tests that are relevant for your change, for example:

$ pytest test/test_v2_prompt_based_segmentation.py

The tests use these markers:

  • v1: tests for the SAM1 models in micro_sam/v1. Run them with pytest -m "v1", or skip them with pytest -m "not v1".
  • gui: tests that use napari. Skip them with pytest -m "not gui".
  • slow: tests that take a long time. Skip them with pytest -m "not slow".

The continuous integration runs pytest -m "v1" and pytest -m "not v1" for every pull request.

Writing your own tests

If you have written new code, you will need to write tests to go with it.

Unit tests

Unit tests are the preferred style of tests for user contributions. Unit tests check small, isolated parts of the code for correctness. If your code is too complicated to write unit tests easily, you may need to consider breaking it up into smaller functions that are easier to test.

Tests involving napari

In cases where tests must use the napari viewer, these tips might be helpful (in particular, the make_napari_viewer_proxy fixture). Mark these tests with @pytest.mark.gui.

These kinds of tests should be used only in limited circumstances. Developers are advised to prefer smaller unit tests, and avoid integration tests wherever possible.

Code coverage

Pytest uses the pytest-cov plugin to automatically determine which lines of code are covered by tests.

A short summary report is printed to the terminal output whenever you run pytest. The full results are also automatically written to a file named coverage.xml.

The Coverage Gutters VSCode extension is useful for visualizing which parts of the code need better test coverage. PyCharm professional has a similar feature, and you may be able to find similar tools for your preferred editor.

We also use codecov.io to display the code coverage results from our GitHub Actions continuous integration.

Open a pull request

Once you've made changes to the code and written some tests to go with it, you are ready to open a pull request. You can mark your pull request as a draft if you are still working on it, and still get the benefit of discussing the best approach with maintainers.

Open your pull request against the dev branch, not main. Describe what your pull request changes and why, and link the issue it addresses. The continuous integration runs the tests for your pull request. A maintainer will review it and may ask for changes before merging.

Optional: Build the documentation

We use pdoc to build the documentation.

To build the documentation locally, run this command:

$ python build_doc.py

This will start a local server and display the HTML documentation. Any changes you make to the documentation will be updated in real time (you may need to refresh your browser to see the changes).

If you want to save the HTML files, append --out to the command, like this:

$ python build_doc.py --out

This will save the HTML files into a new directory named tmp.

You can add content to the documentation in two ways:

  1. By adding or updating google style python docstrings in the micro-sam code.
    • pdoc will automatically find and include docstrings in the documentation.
  2. By adding or editing markdown files in the micro-sam doc directory.
    • If you add a new markdown file to the documentation, you must tell pdoc that it exists by adding a line to the micro_sam/__init__.py module docstring (eg: .. include:: ../doc/my_amazing_new_docs_page.md). Otherwise it will not be included in the final documentation build!

The documentation is built and deployed to GitHub Pages automatically by the build_documentation GitHub Action; there is no need to build and deploy it manually. This workflow runs whenever a new release is created, on pushes to main that touch the Python or markdown documentation files, and on manual dispatch from the Actions tab.

Optional: Benchmark performance

There are a number of options you can use to benchmark performance, and identify problems like slow run times or high memory use in micro-sam.

Run the benchmark script

The script development/benchmark.py benchmarks the SAM1 models of the previous version (micro_sam.v1). It measures the image embeddings, the prompt-based segmentation and the automatic mask generation.

To run the benchmark script from the root of the repository:

$ python development/benchmark.py --model_type vit_t --device cpu

For more details about the user input arguments for the micro-sam benchmark script, see the help:

$ python development/benchmark.py --help

Line profiling

For more detailed line by line performance results, we can use line-profiler. It is part of the developer dependencies in requirements-dev.txt.

line_profiler is a module for doing line-by-line profiling of functions. kernprof is a convenient script for running either line_profiler or the Python standard library's cProfile or profile modules, depending on what is available.

To do line-by-line profiling:

  1. Add the @profile decorator to any function in the call stack.
  2. Run kernprof -lv development/benchmark.py --model_type vit_t --device cpu.

For more details about how to use line-profiler and kernprof, see the documentation.

Snakeviz visualization

For more detailed visualizations of profiling results, we use snakeviz. It is part of the developer dependencies in requirements-dev.txt.

SnakeViz is a browser based graphical viewer for the output of Python’s cProfile module.

  1. Generate a profile file: python -m cProfile -o program.prof development/benchmark.py --model_type vit_t --device cpu
  2. Visualize the profile file: snakeviz program.prof

For more details about how to use snakeviz, see the documentation.

Memory profiling with memray

If you need to investigate memory use specifically, we use memray. Install it with python -m pip install memray.

Memray is a memory profiler for Python. It can track memory allocations in Python code, in native extension modules, and in the Python interpreter itself. It can generate several different types of reports to help you analyze the captured memory usage data. While commonly used as a CLI tool, it can also be used as a library to perform more fine-grained profiling tasks.

For more details about how to use memray, see the documentation.

Creating a new release

Only maintainers create releases.

To create a new release:

  1. Update the version number in micro_sam/__version__.py and add an entry for the new version to RELEASE_OVERVIEW.md.
  2. Merge these changes into main with a pull request.

The CI then tags the new version, publishes the GitHub release and uploads the package to PyPI.

Pre-releases of a new major version, such as 2.0.0a1, are only annotated tags on the dev branch. They do not have a GitHub release or a PyPI upload.

Using micro_sam on BAND

BAND is a service offered by EMBL Heidelberg under the "The German Network for Bioinformatics Infrastructure" (de.NBI) that gives access to a virtual desktop for image analysis tasks. It is free to use and micro_sam is installed there. In order to use BAND and start micro_sam on it follow these steps:

Start BAND

  • Go to https://bandv1.denbi.uni-tuebingen.de/ (another site available at https://band.vm.fedcloud.eu/, choose either) and click Login. If you have not used BAND before you will need to register for BAND. Currently you can only sign up via a Google account. NOTE: It takes a couple of seconds for the "Launch Desktops" window to appear.
  • Launch a BAND desktop with sufficient resources. It's particularly important to select a GPU. The settings from the image below are a good choice.
  • Go to the desktop by clicking GO TO DESKTOP in the Running Desktops menu. See also the screenshot below.

Start micro_sam in BAND

  • Select Applications -> Image Analysis -> microSAM (see screenshot) image

  • This will open the napari GUI, where you can select the images and annotator tools you want to use (see screenshot). NOTE: this may take a few minutes.

  • For testing if the tool works, it's best to use the Segmentation Annotator first.

    • You can find an example image to use by selection File -> Open Sample -> Segment Anything for Microscopy -> HeLa 2d example data (see screenshot)
  • Then select Plugins -> Segment Anything for Microscopy -> Segmentation Annotator, and the tool will start.

Transfering data to BAND

To copy data to and from BAND you can use any cloud storage, e.g. ownCloud, dropbox or google drive. For this, it's important to note that copy and paste, which you may need for accessing links on BAND, works a bit different in BAND:

  • To copy text into BAND you first need to copy it on your computer (e.g. via selecting it + Ctrl + C).
  • Then go to the browser window with BAND and press Ctrl + Shift + Alt. This will open a side window where you can paste your text via Ctrl + V.
  • Then select the text in this window and copy it via Ctrl + C.
  • Now you can close the side window via Ctrl + Shift + Alt and paste the text in band via Ctrl + V

The video below shows how to copy over a link from owncloud and then download the data on BAND using copy and paste:

https://github.com/computational-cell-analytics/micro-sam/assets/4263537/825bf86e-017e-41fc-9e42-995d21203287

 1"""
 2.. include:: ../doc/start_page.md
 3.. include:: ../doc/installation.md
 4.. include:: ../doc/annotation_tools.md
 5.. include:: ../doc/cli_tools.md
 6.. include:: ../doc/python_library.md
 7.. include:: ../doc/finetuned_models.md
 8.. include:: ../doc/apg.md
 9.. include:: ../doc/data_submission.md
10.. include:: ../doc/faq.md
11.. include:: ../doc/contributing.md
12.. include:: ../doc/band.md
13"""
14
15import os
16
17from .__version__ import __version__
18
19os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"