micro_sam.sam_annotator.pixel_classifier
1from typing import List, Optional, Tuple, Union 2 3import numpy as np 4 5import torch 6 7import napari 8 9from .. import util 10from . import _widgets as widgets 11from ._state import AnnotatorState 12from ._titles import get_dock_title 13from ._annotator import _ClassifierBase 14from .util import _sync_embedding_widget 15from ._batch import load_batch_image, run_batch 16from ..classical_features import PIXEL_FEATURES 17from ._batch_classification import ClassificationBatchTask 18from ..v2.util import DEFAULT_MODEL, resolve_default_tiling 19from ..pixel_classification import ( 20 accumulate_pixel_labels, compute_pixel_features, project_prediction_to_image, train_pixel_classifier, 21) 22 23# The SAM and SAM2 image encoders project every model size down to a fixed 256-channel image 24# embedding (prompt_embed_dim), so the per-pixel feature dimension is always 256. 25EMBEDDING_CHANNELS = 256 26 27 28class PixelClassifier(_ClassifierBase): 29 """GUI for the pixel classifier: trains a random forest on per-pixel SAM/SAM2 embedding features.""" 30 31 rf_attr = "pixel_rf" 32 features_attr = "pixel_features" 33 aux_attr = "pixel_grid_shape" 34 label_widget_title = "Pixel label names:" 35 max_components = EMBEDDING_CHANNELS 36 tool_key = "pixel" 37 classical_feature_choices = PIXEL_FEATURES 38 39 def _compute_features(self): 40 # Returns (features, grid_shape) for the current image, computing and caching them if needed. 41 state = AnnotatorState() 42 if state.pixel_features is None: 43 if widgets._validate_embeddings(self._viewer): 44 return None, None 45 image, upsampler, classical_features, ok = self._resolve_feature_inputs() 46 if not ok: 47 return None, None 48 features, grid_shape = compute_pixel_features( 49 state.image_embeddings, state.image_shape, image=image, upsampler=upsampler, 50 classical_features=classical_features, 51 ) 52 state.pixel_features, state.pixel_grid_shape = features, grid_shape 53 return state.pixel_features, state.pixel_grid_shape 54 55 def _compute_training_labels(self, aux): 56 return accumulate_pixel_labels(self._viewer.layers["annotations"].data, aux) 57 58 def _train(self, features, labels, previous_features, previous_labels, n_components, random_state): 59 return train_pixel_classifier( 60 features, labels, previous_features=previous_features, previous_labels=previous_labels, 61 n_components=n_components, random_state=random_state, 62 ) 63 64 def _project_prediction(self, prediction, aux): 65 return project_prediction_to_image(prediction, aux, AnnotatorState().image_shape) 66 67 68def pixel_classifier( 69 image: np.ndarray, 70 embedding_path: Optional[Union[str, util.ImageEmbeddings]] = None, 71 model_type: str = DEFAULT_MODEL, 72 tile_shape: Optional[Tuple[int, int]] = None, 73 halo: Optional[Tuple[int, int]] = None, 74 return_viewer: bool = False, 75 viewer: Optional["napari.viewer.Viewer"] = None, 76 checkpoint_path: Optional[str] = None, 77 device: Optional[Union[str, torch.device]] = None, 78 ndim: Optional[int] = None, 79) -> Optional["napari.viewer.Viewer"]: 80 """Start the pixel classifier for a given image. 81 82 Args: 83 image: The image data. 84 embedding_path: Filepath where to save the embeddings 85 or the precompted image embeddings computed by `precompute_image_embeddings`. 86 model_type: The Segment Anything model to use. For details on the available models check out 87 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 88 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 89 already cached embeddings, else use the default tiling for images exceeding the in-plane 90 size threshold, and pass smaller images to Segment Anything without tiling. 91 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 92 If `None`, use the default overlap whenever tiling is active. 93 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 94 By default, does not return the napari viewer. 95 viewer: The viewer to which the Segment Anything functionality should be added. 96 This enables using a pre-initialized viewer. 97 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 98 device: The computational device to use for the SAM model. 99 By default, automatically chooses the best available device. 100 ndim: The dimensionality of the data. If not given will be derived from the data. 101 102 Returns: 103 The napari viewer, only returned if `return_viewer=True`. 104 """ 105 # Prepare the image in the same way as the annotator: squeeze singletons and map the channels to RGB. 106 image, ndim, rgb = util.prepare_annotation_image(image, ndim=ndim) 107 108 state = AnnotatorState() 109 state.image_shape = image.shape[:ndim] 110 state.ndim = ndim 111 112 # The API / CLI computes embeddings before creating the widget, so apply the same size 113 # heuristic here. Reuse these resolved settings when syncing the widget below. 114 tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path) 115 116 state.initialize_predictor( 117 image, model_type=model_type, save_path=embedding_path, 118 halo=halo, tile_shape=tile_shape, precompute_autoseg_state=False, 119 ndim=ndim, checkpoint_path=checkpoint_path, device=device, 120 use_cli=True, 121 ) 122 123 if viewer is None: 124 viewer = napari.Viewer() 125 126 viewer.add_image(image, name="image", rgb=rgb) 127 128 annotator = PixelClassifier(viewer) 129 130 # Trigger layer update of the annotator so that layers have the correct shape. 131 annotator._update_image() 132 133 # Add the annotator widget to the viewer and sync widgets. 134 viewer.window.add_dock_widget(annotator, name=get_dock_title("pixel_classification")) 135 _sync_embedding_widget( 136 widget=state.widgets["embeddings"], 137 model_type=model_type if checkpoint_path is None else state.predictor.model_type, 138 save_path=embedding_path, 139 checkpoint_path=checkpoint_path, 140 device=device, 141 tile_shape=tile_shape, 142 halo=halo, 143 ) 144 145 if return_viewer: 146 return viewer 147 148 napari.run() 149 150 151class PixelClassificationBatchTask(ClassificationBatchTask): 152 """Batch task for the pixel classifier.""" 153 154 dock_name = get_dock_title("batch_pixel_classification") 155 classifier_class = PixelClassifier 156 features_attr = "pixel_features" 157 aux_attr = "pixel_grid_shape" 158 rf_attr = "pixel_rf" 159 160 161def batch_pixel_classifier( 162 images: List[np.ndarray], 163 output_folder: str, 164 embedding_paths: Optional[List[Union[str, util.ImageEmbeddings]]] = None, 165 model_type: str = DEFAULT_MODEL, 166 tile_shape: Optional[Tuple[int, int]] = None, 167 halo: Optional[Tuple[int, int]] = None, 168 checkpoint_path: Optional[str] = None, 169 device: Optional[Union[str, torch.device]] = None, 170 ndim: Optional[int] = None, 171 viewer: Optional["napari.viewer.Viewer"] = None, 172 return_viewer: bool = False, 173 skip_done: bool = False, 174 batch_size: Optional[int] = 1, 175) -> Optional["napari.viewer.Viewer"]: 176 """Start the pixel classifier for a list of images. 177 178 This function saves the per-pixel features and labels across the batch, so a random forest can be 179 trained on multiple images, plus the per-image prediction and the trained classifier. 180 181 Args: 182 images: The input images. 183 output_folder: The folder where predictions, the trained random forest and the accumulated 184 features/labels are saved. 185 embedding_paths: Filepaths where to save/load the embeddings, one per image. 186 model_type: The Segment Anything model to use. For details on the available models check out 187 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 188 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 189 already cached embeddings, else use the default tiling for images exceeding the in-plane 190 size threshold, and pass smaller images to Segment Anything without tiling. 191 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 192 If `None`, use the default overlap whenever tiling is active. 193 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 194 device: The computational device to use for the SAM model. 195 By default, automatically chooses the best available device. 196 ndim: The dimensionality of the data. If not given will be derived from the data. 197 viewer: The viewer to which the functionality should be added. 198 return_viewer: Whether to return the napari viewer instead of starting the event loop. 199 batch_size: The number of tiles / slices per model call when computing the embeddings. 200 Only has an effect on a GPU. Pass None to select it per device from the free VRAM 201 (SAM2 only). By default a single tile / slice is used. 202 skip_done: Whether to skip images whose prediction already exists in `output_folder`. 203 204 Returns: 205 The napari viewer, only returned if `return_viewer=True`. 206 """ 207 have_inputs_as_arrays = isinstance(images[0], np.ndarray) 208 if ndim is None: 209 ndim = load_batch_image(images[0])[1] 210 211 task = PixelClassificationBatchTask( 212 ndim=ndim, model_type=model_type, embedding_paths=embedding_paths, 213 tile_shape=tile_shape, halo=halo, checkpoint_path=checkpoint_path, device=device, 214 batch_size=batch_size, 215 ) 216 return run_batch( 217 images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays, 218 viewer=viewer, return_viewer=return_viewer, skip_done=skip_done, 219 )
EMBEDDING_CHANNELS =
256
29class PixelClassifier(_ClassifierBase): 30 """GUI for the pixel classifier: trains a random forest on per-pixel SAM/SAM2 embedding features.""" 31 32 rf_attr = "pixel_rf" 33 features_attr = "pixel_features" 34 aux_attr = "pixel_grid_shape" 35 label_widget_title = "Pixel label names:" 36 max_components = EMBEDDING_CHANNELS 37 tool_key = "pixel" 38 classical_feature_choices = PIXEL_FEATURES 39 40 def _compute_features(self): 41 # Returns (features, grid_shape) for the current image, computing and caching them if needed. 42 state = AnnotatorState() 43 if state.pixel_features is None: 44 if widgets._validate_embeddings(self._viewer): 45 return None, None 46 image, upsampler, classical_features, ok = self._resolve_feature_inputs() 47 if not ok: 48 return None, None 49 features, grid_shape = compute_pixel_features( 50 state.image_embeddings, state.image_shape, image=image, upsampler=upsampler, 51 classical_features=classical_features, 52 ) 53 state.pixel_features, state.pixel_grid_shape = features, grid_shape 54 return state.pixel_features, state.pixel_grid_shape 55 56 def _compute_training_labels(self, aux): 57 return accumulate_pixel_labels(self._viewer.layers["annotations"].data, aux) 58 59 def _train(self, features, labels, previous_features, previous_labels, n_components, random_state): 60 return train_pixel_classifier( 61 features, labels, previous_features=previous_features, previous_labels=previous_labels, 62 n_components=n_components, random_state=random_state, 63 ) 64 65 def _project_prediction(self, prediction, aux): 66 return project_prediction_to_image(prediction, aux, AnnotatorState().image_shape)
GUI for the pixel classifier: trains a random forest on per-pixel SAM/SAM2 embedding features.
def
pixel_classifier( image: numpy.ndarray, embedding_path: Union[str, Dict[str, Any], NoneType] = None, model_type: str = 'hvit_t_cells', tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, return_viewer: bool = False, viewer: Optional[napari.viewer.Viewer] = None, checkpoint_path: Optional[str] = None, device: Union[str, torch.device, NoneType] = None, ndim: Optional[int] = None) -> Optional[napari.viewer.Viewer]:
69def pixel_classifier( 70 image: np.ndarray, 71 embedding_path: Optional[Union[str, util.ImageEmbeddings]] = None, 72 model_type: str = DEFAULT_MODEL, 73 tile_shape: Optional[Tuple[int, int]] = None, 74 halo: Optional[Tuple[int, int]] = None, 75 return_viewer: bool = False, 76 viewer: Optional["napari.viewer.Viewer"] = None, 77 checkpoint_path: Optional[str] = None, 78 device: Optional[Union[str, torch.device]] = None, 79 ndim: Optional[int] = None, 80) -> Optional["napari.viewer.Viewer"]: 81 """Start the pixel classifier for a given image. 82 83 Args: 84 image: The image data. 85 embedding_path: Filepath where to save the embeddings 86 or the precompted image embeddings computed by `precompute_image_embeddings`. 87 model_type: The Segment Anything model to use. For details on the available models check out 88 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 89 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 90 already cached embeddings, else use the default tiling for images exceeding the in-plane 91 size threshold, and pass smaller images to Segment Anything without tiling. 92 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 93 If `None`, use the default overlap whenever tiling is active. 94 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 95 By default, does not return the napari viewer. 96 viewer: The viewer to which the Segment Anything functionality should be added. 97 This enables using a pre-initialized viewer. 98 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 99 device: The computational device to use for the SAM model. 100 By default, automatically chooses the best available device. 101 ndim: The dimensionality of the data. If not given will be derived from the data. 102 103 Returns: 104 The napari viewer, only returned if `return_viewer=True`. 105 """ 106 # Prepare the image in the same way as the annotator: squeeze singletons and map the channels to RGB. 107 image, ndim, rgb = util.prepare_annotation_image(image, ndim=ndim) 108 109 state = AnnotatorState() 110 state.image_shape = image.shape[:ndim] 111 state.ndim = ndim 112 113 # The API / CLI computes embeddings before creating the widget, so apply the same size 114 # heuristic here. Reuse these resolved settings when syncing the widget below. 115 tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path) 116 117 state.initialize_predictor( 118 image, model_type=model_type, save_path=embedding_path, 119 halo=halo, tile_shape=tile_shape, precompute_autoseg_state=False, 120 ndim=ndim, checkpoint_path=checkpoint_path, device=device, 121 use_cli=True, 122 ) 123 124 if viewer is None: 125 viewer = napari.Viewer() 126 127 viewer.add_image(image, name="image", rgb=rgb) 128 129 annotator = PixelClassifier(viewer) 130 131 # Trigger layer update of the annotator so that layers have the correct shape. 132 annotator._update_image() 133 134 # Add the annotator widget to the viewer and sync widgets. 135 viewer.window.add_dock_widget(annotator, name=get_dock_title("pixel_classification")) 136 _sync_embedding_widget( 137 widget=state.widgets["embeddings"], 138 model_type=model_type if checkpoint_path is None else state.predictor.model_type, 139 save_path=embedding_path, 140 checkpoint_path=checkpoint_path, 141 device=device, 142 tile_shape=tile_shape, 143 halo=halo, 144 ) 145 146 if return_viewer: 147 return viewer 148 149 napari.run()
Start the pixel classifier for a given image.
Arguments:
- image: The image data.
- embedding_path: Filepath where to save the embeddings
or the precompted image embeddings computed by
precompute_image_embeddings. - model_type: The Segment Anything model to use. For details on the available models check out https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
- tile_shape: Shape of tiles for tiled embedding prediction. If
None, reuse the tiling of already cached embeddings, else use the default tiling for images exceeding the in-plane size threshold, and pass smaller images to Segment Anything without tiling. - halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
If
None, use the default overlap whenever tiling is active. - return_viewer: Whether to return the napari viewer to further modify it before starting the tool. By default, does not return the napari viewer.
- viewer: The viewer to which the Segment Anything functionality should be added. This enables using a pre-initialized viewer.
- checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
- device: The computational device to use for the SAM model. By default, automatically chooses the best available device.
- ndim: The dimensionality of the data. If not given will be derived from the data.
Returns:
The napari viewer, only returned if
return_viewer=True.
class
PixelClassificationBatchTask(micro_sam.sam_annotator._batch_classification.ClassificationBatchTask):
152class PixelClassificationBatchTask(ClassificationBatchTask): 153 """Batch task for the pixel classifier.""" 154 155 dock_name = get_dock_title("batch_pixel_classification") 156 classifier_class = PixelClassifier 157 features_attr = "pixel_features" 158 aux_attr = "pixel_grid_shape" 159 rf_attr = "pixel_rf"
Batch task for the pixel classifier.
classifier_class =
<class 'PixelClassifier'>
Inherited Members
def
batch_pixel_classifier( images: List[numpy.ndarray], output_folder: str, embedding_paths: Optional[List[Union[str, Dict[str, Any]]]] = None, model_type: str = 'hvit_t_cells', tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, checkpoint_path: Optional[str] = None, device: Union[str, torch.device, NoneType] = None, ndim: Optional[int] = None, viewer: Optional[napari.viewer.Viewer] = None, return_viewer: bool = False, skip_done: bool = False, batch_size: Optional[int] = 1) -> Optional[napari.viewer.Viewer]:
162def batch_pixel_classifier( 163 images: List[np.ndarray], 164 output_folder: str, 165 embedding_paths: Optional[List[Union[str, util.ImageEmbeddings]]] = None, 166 model_type: str = DEFAULT_MODEL, 167 tile_shape: Optional[Tuple[int, int]] = None, 168 halo: Optional[Tuple[int, int]] = None, 169 checkpoint_path: Optional[str] = None, 170 device: Optional[Union[str, torch.device]] = None, 171 ndim: Optional[int] = None, 172 viewer: Optional["napari.viewer.Viewer"] = None, 173 return_viewer: bool = False, 174 skip_done: bool = False, 175 batch_size: Optional[int] = 1, 176) -> Optional["napari.viewer.Viewer"]: 177 """Start the pixel classifier for a list of images. 178 179 This function saves the per-pixel features and labels across the batch, so a random forest can be 180 trained on multiple images, plus the per-image prediction and the trained classifier. 181 182 Args: 183 images: The input images. 184 output_folder: The folder where predictions, the trained random forest and the accumulated 185 features/labels are saved. 186 embedding_paths: Filepaths where to save/load the embeddings, one per image. 187 model_type: The Segment Anything model to use. For details on the available models check out 188 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 189 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 190 already cached embeddings, else use the default tiling for images exceeding the in-plane 191 size threshold, and pass smaller images to Segment Anything without tiling. 192 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 193 If `None`, use the default overlap whenever tiling is active. 194 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 195 device: The computational device to use for the SAM model. 196 By default, automatically chooses the best available device. 197 ndim: The dimensionality of the data. If not given will be derived from the data. 198 viewer: The viewer to which the functionality should be added. 199 return_viewer: Whether to return the napari viewer instead of starting the event loop. 200 batch_size: The number of tiles / slices per model call when computing the embeddings. 201 Only has an effect on a GPU. Pass None to select it per device from the free VRAM 202 (SAM2 only). By default a single tile / slice is used. 203 skip_done: Whether to skip images whose prediction already exists in `output_folder`. 204 205 Returns: 206 The napari viewer, only returned if `return_viewer=True`. 207 """ 208 have_inputs_as_arrays = isinstance(images[0], np.ndarray) 209 if ndim is None: 210 ndim = load_batch_image(images[0])[1] 211 212 task = PixelClassificationBatchTask( 213 ndim=ndim, model_type=model_type, embedding_paths=embedding_paths, 214 tile_shape=tile_shape, halo=halo, checkpoint_path=checkpoint_path, device=device, 215 batch_size=batch_size, 216 ) 217 return run_batch( 218 images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays, 219 viewer=viewer, return_viewer=return_viewer, skip_done=skip_done, 220 )
Start the pixel classifier for a list of images.
This function saves the per-pixel features and labels across the batch, so a random forest can be trained on multiple images, plus the per-image prediction and the trained classifier.
Arguments:
- images: The input images.
- output_folder: The folder where predictions, the trained random forest and the accumulated features/labels are saved.
- embedding_paths: Filepaths where to save/load the embeddings, one per image.
- model_type: The Segment Anything model to use. For details on the available models check out https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
- tile_shape: Shape of tiles for tiled embedding prediction. If
None, reuse the tiling of already cached embeddings, else use the default tiling for images exceeding the in-plane size threshold, and pass smaller images to Segment Anything without tiling. - halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
If
None, use the default overlap whenever tiling is active. - checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
- device: The computational device to use for the SAM model. By default, automatically chooses the best available device.
- ndim: The dimensionality of the data. If not given will be derived from the data.
- viewer: The viewer to which the functionality should be added.
- return_viewer: Whether to return the napari viewer instead of starting the event loop.
- batch_size: The number of tiles / slices per model call when computing the embeddings. Only has an effect on a GPU. Pass None to select it per device from the free VRAM (SAM2 only). By default a single tile / slice is used.
- skip_done: Whether to skip images whose prediction already exists in
output_folder.
Returns:
The napari viewer, only returned if
return_viewer=True.