micro_sam.sam_annotator.object_classifier
1from multiprocessing import cpu_count 2from typing import List, Optional, Tuple, Union 3 4import numpy as np 5import imageio.v3 as imageio 6from skimage.measure import regionprops_table 7 8from sklearn.decomposition import PCA 9from sklearn.pipeline import Pipeline 10from sklearn.preprocessing import StandardScaler 11from sklearn.ensemble import RandomForestClassifier 12 13import torch 14 15import napari 16from qtpy import QtWidgets 17from magicgui.widgets import ComboBox 18 19from .. import util 20from . import _widgets as widgets 21from ._state import AnnotatorState 22from ._tooltips import get_tooltip 23from ._titles import get_dock_title 24from ._annotator import _ClassifierBase 25from .util import _sync_embedding_widget 26from ._batch import load_batch_image, run_batch 27from ..classical_features import OBJECT_FEATURES 28from ._batch_classification import ClassificationBatchTask 29from ..v2.util import DEFAULT_MODEL, resolve_default_tiling 30from ..object_classification import compute_object_features, project_prediction_to_segmentation 31 32# Object features are the object area plus the per-channel mean of the 256-channel SAM/SAM2 image 33# embedding, i.e. 257 features. PCA can reduce to at most this many components. 34N_OBJECT_FEATURES = 257 35INTERNAL_LABEL_LAYER_NAMES = {"annotations", "prediction"} 36 37 38def _accumulate_labels(segmentation, annotations, seg_ids): 39 40 def majority_label(mask, annotation): 41 ids, counts = np.unique(annotation[mask], return_counts=True) 42 if len(ids) == 1 and ids[0] == 0: 43 return 0 44 if ids[0] == 0: 45 ids, counts = ids[1:], counts[1:] 46 return ids[np.argmax(counts)] 47 48 all_features = regionprops_table( 49 segmentation, intensity_image=annotations, properties=("label",), 50 extra_properties=[majority_label], 51 ) 52 labels = dict(zip(all_features["label"], all_features["majority_label"].astype("int"))) 53 # Match the rows of the features, which leave out the objects that vanish in the embedding resize. 54 return np.array([labels[seg_id] for seg_id in seg_ids], dtype="int") 55 56 57def _train_rf( 58 features, labels, previous_features=None, previous_labels=None, n_components=None, random_state=0, **rf_kwargs 59): 60 assert len(features) == len(labels) 61 valid = labels != 0 62 X, y = features[valid], labels[valid] 63 64 if previous_features is not None: 65 assert previous_labels is not None and len(previous_features) == len(previous_labels) 66 X = np.concatenate([previous_features, X], axis=0) 67 y = np.concatenate([previous_labels, y], axis=0) 68 69 rf = RandomForestClassifier(random_state=random_state, **rf_kwargs) 70 71 # Optionally reduce the features to the top-n PCA components. We clamp n_components to the 72 # number of features and samples. If it covers all features, we skip PCA and use the plain RF. 73 # Object features mix area (large magnitude) with embedding means (small), so we standardize 74 # them before PCA to keep area from dominating the components. 75 n_features = X.shape[1] 76 k = min(int(n_components), n_features, len(X)) if n_components else 0 77 if 0 < k < n_features: 78 model = Pipeline( 79 [("scaler", StandardScaler()), ("pca", PCA(n_components=k, random_state=random_state)), ("rf", rf)] 80 ) 81 else: 82 model = rf 83 84 model.fit(X, y) 85 return model 86 87 88class ObjectClassifier(_ClassifierBase): 89 """GUI for the object classifier: trains a random forest on per-object SAM/SAM2 embedding features.""" 90 91 rf_attr = "object_rf" 92 features_attr = "object_features" 93 aux_attr = "seg_ids" 94 label_widget_title = "Object label names:" 95 max_components = N_OBJECT_FEATURES 96 tool_key = "object" 97 classical_feature_choices = OBJECT_FEATURES 98 supports_apply_to_volume = False # object classification always runs over the full image/volume 99 100 def _get_selected_segmentation_layer(self): 101 state = AnnotatorState() 102 segmentation_layer = None if state.segmentation_selection is None else state.segmentation_selection.get_value() 103 if segmentation_layer is None: 104 widgets._generate_message("error", "You have to select a segmentation labels layer.") 105 return None 106 return segmentation_layer 107 108 def _compute_features(self): 109 # Returns (features, seg_ids) for the current image+segmentation, computing/caching if needed. 110 state = AnnotatorState() 111 if state.object_features is None: 112 if widgets._validate_embeddings(self._viewer): 113 return None, None 114 segmentation_layer = self._get_selected_segmentation_layer() 115 if segmentation_layer is None: 116 return None, None 117 image, upsampler, classical_features, ok = self._resolve_feature_inputs() 118 if not ok: 119 return None, None 120 seg_ids, features = compute_object_features( 121 state.image_embeddings, segmentation_layer.data, image=image, upsampler=upsampler, 122 classical_features=classical_features, 123 ) 124 state.seg_ids, state.object_features = seg_ids, features 125 return state.object_features, state.seg_ids 126 127 def _compute_training_labels(self, aux): 128 segmentation_layer = self._get_selected_segmentation_layer() 129 if segmentation_layer is None: 130 return None 131 return _accumulate_labels(segmentation_layer.data, self._viewer.layers["annotations"].data, aux) 132 133 def _train(self, features, labels, previous_features, previous_labels, n_components, random_state): 134 return _train_rf( 135 features, labels, previous_features=previous_features, previous_labels=previous_labels, 136 n_estimators=200, max_depth=10, n_jobs=cpu_count(), n_components=n_components, random_state=random_state, 137 ) 138 139 def _project_prediction(self, prediction, aux): 140 segmentation_layer = self._get_selected_segmentation_layer() 141 if segmentation_layer is None: 142 return None 143 return project_prediction_to_segmentation(segmentation_layer.data, prediction, aux) 144 145 # 146 # The segmentation-layer selector (object classifier only). 147 # 148 149 def _is_segmentation_layer(self, layer): 150 return isinstance(layer, napari.layers.Labels) and layer.name.lower() not in INTERNAL_LABEL_LAYER_NAMES 151 152 def _find_default_segmentation_layer(self): 153 candidates = [layer for layer in self._viewer.layers if self._is_segmentation_layer(layer)] 154 if not candidates: 155 return None 156 157 for layer in candidates: 158 if layer.name == "segmentation": 159 return layer 160 161 for layer in candidates: 162 if "seg" in layer.name.lower(): 163 return layer 164 165 return candidates[0] 166 167 def _select_default_segmentation_layer(self): 168 default_layer = self._find_default_segmentation_layer() 169 if default_layer is not None: 170 self.segmentation_selection.value = default_layer 171 172 def _segmentation_layer_choices(self): 173 return [(layer.name, layer) for layer in self._viewer.layers if self._is_segmentation_layer(layer)] 174 175 def _reset_segmentation_layer_choices(self, *args): 176 previous_selection = self.segmentation_selection.value 177 self.segmentation_selection.reset_choices() 178 choices = self.segmentation_selection.choices 179 if any(layer is previous_selection for layer in choices): 180 self.segmentation_selection.value = previous_selection 181 else: 182 self._select_default_segmentation_layer() 183 if self.segmentation_selection.value is not previous_selection: 184 self._invalidate_features() 185 186 def _create_segmentation_layer_section(self): 187 segmentation_selection = QtWidgets.QVBoxLayout() 188 seg_label = QtWidgets.QLabel("Segmentation:") 189 seg_label.setToolTip(get_tooltip("classification", "segmentation")) 190 segmentation_selection.addWidget(seg_label) 191 self.segmentation_selection = ComboBox(choices=lambda _: self._segmentation_layer_choices()) 192 self.segmentation_selection.native.setToolTip(get_tooltip("classification", "segmentation")) 193 self._select_default_segmentation_layer() 194 self.segmentation_selection.changed.connect(self._invalidate_features) 195 AnnotatorState().segmentation_selection = self.segmentation_selection 196 segmentation_selection.addWidget(self.segmentation_selection.native) 197 # Keep the choices in sync as layers are added, removed or reordered. 198 self._viewer.layers.events.inserted.connect(self._reset_segmentation_layer_choices) 199 self._viewer.layers.events.removed.connect(self._reset_segmentation_layer_choices) 200 self._viewer.layers.events.reordered.connect(self._reset_segmentation_layer_choices) 201 202 @self._viewer.bind_key("Shift-S", overwrite=True) 203 def _toggle_segmentation(event=None): 204 layer = self.segmentation_selection.value 205 if layer is not None: 206 layer.visible = not layer.visible 207 208 return segmentation_selection 209 210 def _extra_classification_sections(self): 211 return [self._create_segmentation_layer_section()] 212 213 214def object_classifier( 215 image: np.ndarray, 216 segmentation: np.ndarray, 217 embedding_path: Optional[Union[str, util.ImageEmbeddings]] = None, 218 model_type: str = DEFAULT_MODEL, 219 tile_shape: Optional[Tuple[int, int]] = None, 220 halo: Optional[Tuple[int, int]] = None, 221 return_viewer: bool = False, 222 viewer: Optional["napari.viewer.Viewer"] = None, 223 checkpoint_path: Optional[str] = None, 224 device: Optional[Union[str, torch.device]] = None, 225 ndim: Optional[int] = None, 226) -> Optional["napari.viewer.Viewer"]: 227 """Start the object classifier for a given image and segmentation. 228 229 Args: 230 image: The image data. 231 segmentation: The segmentation data. 232 embedding_path: Filepath where to save the embeddings 233 or the precompted image embeddings computed by `precompute_image_embeddings`. 234 model_type: The Segment Anything model to use. For details on the available models check out 235 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 236 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 237 already cached embeddings, else use the default tiling for images exceeding the in-plane 238 size threshold, and pass smaller images to Segment Anything without tiling. 239 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 240 If `None`, use the default overlap whenever tiling is active. 241 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 242 By default, does not return the napari viewer. 243 viewer: The viewer to which the Segment Anything functionality should be added. 244 This enables using a pre-initialized viewer. 245 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 246 device: The computational device to use for the SAM model. 247 By default, automatically chooses the best available device. 248 ndim: The dimensionality of the data. If not given will be derived from the data. 249 250 Returns: 251 The napari viewer, only returned if `return_viewer=True`. 252 """ 253 # Prepare the image in the same way as the annotator: squeeze singletons and map the channels to RGB. 254 image, ndim, rgb = util.prepare_annotation_image(image, ndim=ndim) 255 256 state = AnnotatorState() 257 state.image_shape = image.shape[:ndim] 258 state.ndim = ndim 259 260 # The API / CLI computes embeddings before creating the widget, so apply the same size 261 # heuristic here. Reuse these resolved settings when syncing the widget below. 262 tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path) 263 264 state.initialize_predictor( 265 image, model_type=model_type, save_path=embedding_path, 266 halo=halo, tile_shape=tile_shape, precompute_autoseg_state=False, 267 ndim=ndim, checkpoint_path=checkpoint_path, device=device, 268 use_cli=True, 269 ) 270 271 if viewer is None: 272 viewer = napari.Viewer() 273 274 viewer.add_image(image, name="image", rgb=rgb) 275 viewer.add_labels(util.match_image_shape(segmentation, state.image_shape), name="segmentation") 276 277 annotator = ObjectClassifier(viewer) 278 279 # Trigger layer update of the annotator so that layers have the correct shape. 280 annotator._update_image() 281 282 # Add the annotator widget to the viewer and sync widgets. 283 viewer.window.add_dock_widget(annotator, name=get_dock_title("object_classification")) 284 _sync_embedding_widget( 285 widget=state.widgets["embeddings"], 286 model_type=model_type if checkpoint_path is None else state.predictor.model_type, 287 save_path=embedding_path, 288 checkpoint_path=checkpoint_path, 289 device=device, 290 tile_shape=tile_shape, 291 halo=halo, 292 ) 293 294 if return_viewer: 295 return viewer 296 297 napari.run() 298 299 300class ObjectClassificationBatchTask(ClassificationBatchTask): 301 """Batch task for the object classifier: per-item segmentation layer + projected prediction.""" 302 303 dock_name = get_dock_title("batch_object_classification") 304 classifier_class = ObjectClassifier 305 features_attr = "object_features" 306 aux_attr = "seg_ids" 307 rf_attr = "object_rf" 308 309 def __init__(self, *, segmentations, **kwargs): 310 super().__init__(**kwargs) 311 self.segmentations = segmentations 312 self.visited_segmentations = {} 313 314 def on_leave_item(self, viewer, entry, index): 315 # Keep the segmentation, which may be edited or produced in-tool, for going back to this item. 316 self.visited_segmentations[index] = viewer.layers["segmentation"].data.copy() 317 super().on_leave_item(viewer, entry, index) 318 319 def _set_layers(self, viewer, index): 320 # Load (or carry over) the per-item segmentation. When none is provided, start from an empty 321 # segmentation the user can fill in-tool (the 'produce' path). 322 seg = None if self.segmentations is None else self.segmentations[index] 323 seg = self.visited_segmentations.get(index, seg) 324 if seg is not None and not isinstance(seg, np.ndarray): 325 seg = imageio.imread(seg) 326 if seg is not None: 327 seg = util.match_image_shape(seg, AnnotatorState().image_shape) 328 # Without a segmentation, an empty one, so the objects of the previous item are not carried over. 329 if seg is None: 330 seg = np.zeros(tuple(AnnotatorState().image_shape), dtype="uint32") 331 if "segmentation" in viewer.layers: 332 viewer.layers["segmentation"].data = seg 333 else: 334 viewer.add_labels(seg, name="segmentation") 335 336 337def batch_object_classifier( 338 images: List[np.ndarray], 339 segmentations: List[np.ndarray], 340 output_folder: str, 341 embedding_paths: Optional[List[Union[str, util.ImageEmbeddings]]] = None, 342 model_type: str = DEFAULT_MODEL, 343 tile_shape: Optional[Tuple[int, int]] = None, 344 halo: Optional[Tuple[int, int]] = None, 345 checkpoint_path: Optional[str] = None, 346 device: Optional[Union[str, torch.device]] = None, 347 ndim: Optional[int] = None, 348 viewer: Optional["napari.viewer.Viewer"] = None, 349 return_viewer: bool = False, 350 skip_done: bool = False, 351 batch_size: Optional[int] = 1, 352) -> Optional["napari.viewer.Viewer"]: 353 """Start the object classifier for a list of images and segmentations. 354 355 This function saves the features and labels for annotated objects across the batch, so a random 356 forest can be trained on multiple images, plus the per-image prediction and the trained classifier. 357 358 Args: 359 images: The input images. 360 segmentations: The input segmentations, one per image. 361 output_folder: The folder where predictions, the trained random forest and the accumulated 362 features/labels are saved. 363 embedding_paths: Filepaths where to save/load the embeddings, one per image. 364 model_type: The Segment Anything model to use. For details on the available models check out 365 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 366 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 367 already cached embeddings, else use the default tiling for images exceeding the in-plane 368 size threshold, and pass smaller images to Segment Anything without tiling. 369 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 370 If `None`, use the default overlap whenever tiling is active. 371 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 372 device: The computational device to use for the SAM model. 373 By default, automatically chooses the best available device. 374 ndim: The dimensionality of the data. If not given will be derived from the data. 375 viewer: The viewer to which the functionality should be added. 376 return_viewer: Whether to return the napari viewer instead of starting the event loop. 377 batch_size: The number of tiles / slices per model call when computing the embeddings. 378 Only has an effect on a GPU. Pass None to select it per device from the free VRAM 379 (SAM2 only). By default a single tile / slice is used. 380 skip_done: Whether to skip images whose prediction already exists in `output_folder`. 381 382 Returns: 383 The napari viewer, only returned if `return_viewer=True`. 384 """ 385 if segmentations is not None and len(images) != len(segmentations): 386 raise ValueError( 387 f"Expect the same number of images and segmentations, got {len(images)}, {len(segmentations)}." 388 ) 389 390 have_inputs_as_arrays = isinstance(images[0], np.ndarray) 391 if ndim is None: 392 ndim = load_batch_image(images[0])[1] 393 394 task = ObjectClassificationBatchTask( 395 segmentations=segmentations, ndim=ndim, model_type=model_type, embedding_paths=embedding_paths, 396 tile_shape=tile_shape, halo=halo, checkpoint_path=checkpoint_path, device=device, 397 batch_size=batch_size, 398 ) 399 return run_batch( 400 images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays, 401 viewer=viewer, return_viewer=return_viewer, skip_done=skip_done, 402 )
N_OBJECT_FEATURES =
257
INTERNAL_LABEL_LAYER_NAMES =
{'prediction', 'annotations'}
89class ObjectClassifier(_ClassifierBase): 90 """GUI for the object classifier: trains a random forest on per-object SAM/SAM2 embedding features.""" 91 92 rf_attr = "object_rf" 93 features_attr = "object_features" 94 aux_attr = "seg_ids" 95 label_widget_title = "Object label names:" 96 max_components = N_OBJECT_FEATURES 97 tool_key = "object" 98 classical_feature_choices = OBJECT_FEATURES 99 supports_apply_to_volume = False # object classification always runs over the full image/volume 100 101 def _get_selected_segmentation_layer(self): 102 state = AnnotatorState() 103 segmentation_layer = None if state.segmentation_selection is None else state.segmentation_selection.get_value() 104 if segmentation_layer is None: 105 widgets._generate_message("error", "You have to select a segmentation labels layer.") 106 return None 107 return segmentation_layer 108 109 def _compute_features(self): 110 # Returns (features, seg_ids) for the current image+segmentation, computing/caching if needed. 111 state = AnnotatorState() 112 if state.object_features is None: 113 if widgets._validate_embeddings(self._viewer): 114 return None, None 115 segmentation_layer = self._get_selected_segmentation_layer() 116 if segmentation_layer is None: 117 return None, None 118 image, upsampler, classical_features, ok = self._resolve_feature_inputs() 119 if not ok: 120 return None, None 121 seg_ids, features = compute_object_features( 122 state.image_embeddings, segmentation_layer.data, image=image, upsampler=upsampler, 123 classical_features=classical_features, 124 ) 125 state.seg_ids, state.object_features = seg_ids, features 126 return state.object_features, state.seg_ids 127 128 def _compute_training_labels(self, aux): 129 segmentation_layer = self._get_selected_segmentation_layer() 130 if segmentation_layer is None: 131 return None 132 return _accumulate_labels(segmentation_layer.data, self._viewer.layers["annotations"].data, aux) 133 134 def _train(self, features, labels, previous_features, previous_labels, n_components, random_state): 135 return _train_rf( 136 features, labels, previous_features=previous_features, previous_labels=previous_labels, 137 n_estimators=200, max_depth=10, n_jobs=cpu_count(), n_components=n_components, random_state=random_state, 138 ) 139 140 def _project_prediction(self, prediction, aux): 141 segmentation_layer = self._get_selected_segmentation_layer() 142 if segmentation_layer is None: 143 return None 144 return project_prediction_to_segmentation(segmentation_layer.data, prediction, aux) 145 146 # 147 # The segmentation-layer selector (object classifier only). 148 # 149 150 def _is_segmentation_layer(self, layer): 151 return isinstance(layer, napari.layers.Labels) and layer.name.lower() not in INTERNAL_LABEL_LAYER_NAMES 152 153 def _find_default_segmentation_layer(self): 154 candidates = [layer for layer in self._viewer.layers if self._is_segmentation_layer(layer)] 155 if not candidates: 156 return None 157 158 for layer in candidates: 159 if layer.name == "segmentation": 160 return layer 161 162 for layer in candidates: 163 if "seg" in layer.name.lower(): 164 return layer 165 166 return candidates[0] 167 168 def _select_default_segmentation_layer(self): 169 default_layer = self._find_default_segmentation_layer() 170 if default_layer is not None: 171 self.segmentation_selection.value = default_layer 172 173 def _segmentation_layer_choices(self): 174 return [(layer.name, layer) for layer in self._viewer.layers if self._is_segmentation_layer(layer)] 175 176 def _reset_segmentation_layer_choices(self, *args): 177 previous_selection = self.segmentation_selection.value 178 self.segmentation_selection.reset_choices() 179 choices = self.segmentation_selection.choices 180 if any(layer is previous_selection for layer in choices): 181 self.segmentation_selection.value = previous_selection 182 else: 183 self._select_default_segmentation_layer() 184 if self.segmentation_selection.value is not previous_selection: 185 self._invalidate_features() 186 187 def _create_segmentation_layer_section(self): 188 segmentation_selection = QtWidgets.QVBoxLayout() 189 seg_label = QtWidgets.QLabel("Segmentation:") 190 seg_label.setToolTip(get_tooltip("classification", "segmentation")) 191 segmentation_selection.addWidget(seg_label) 192 self.segmentation_selection = ComboBox(choices=lambda _: self._segmentation_layer_choices()) 193 self.segmentation_selection.native.setToolTip(get_tooltip("classification", "segmentation")) 194 self._select_default_segmentation_layer() 195 self.segmentation_selection.changed.connect(self._invalidate_features) 196 AnnotatorState().segmentation_selection = self.segmentation_selection 197 segmentation_selection.addWidget(self.segmentation_selection.native) 198 # Keep the choices in sync as layers are added, removed or reordered. 199 self._viewer.layers.events.inserted.connect(self._reset_segmentation_layer_choices) 200 self._viewer.layers.events.removed.connect(self._reset_segmentation_layer_choices) 201 self._viewer.layers.events.reordered.connect(self._reset_segmentation_layer_choices) 202 203 @self._viewer.bind_key("Shift-S", overwrite=True) 204 def _toggle_segmentation(event=None): 205 layer = self.segmentation_selection.value 206 if layer is not None: 207 layer.visible = not layer.visible 208 209 return segmentation_selection 210 211 def _extra_classification_sections(self): 212 return [self._create_segmentation_layer_section()]
GUI for the object classifier: trains a random forest on per-object SAM/SAM2 embedding features.
def
object_classifier( image: numpy.ndarray, segmentation: 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]:
215def object_classifier( 216 image: np.ndarray, 217 segmentation: np.ndarray, 218 embedding_path: Optional[Union[str, util.ImageEmbeddings]] = None, 219 model_type: str = DEFAULT_MODEL, 220 tile_shape: Optional[Tuple[int, int]] = None, 221 halo: Optional[Tuple[int, int]] = None, 222 return_viewer: bool = False, 223 viewer: Optional["napari.viewer.Viewer"] = None, 224 checkpoint_path: Optional[str] = None, 225 device: Optional[Union[str, torch.device]] = None, 226 ndim: Optional[int] = None, 227) -> Optional["napari.viewer.Viewer"]: 228 """Start the object classifier for a given image and segmentation. 229 230 Args: 231 image: The image data. 232 segmentation: The segmentation data. 233 embedding_path: Filepath where to save the embeddings 234 or the precompted image embeddings computed by `precompute_image_embeddings`. 235 model_type: The Segment Anything model to use. For details on the available models check out 236 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 237 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 238 already cached embeddings, else use the default tiling for images exceeding the in-plane 239 size threshold, and pass smaller images to Segment Anything without tiling. 240 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 241 If `None`, use the default overlap whenever tiling is active. 242 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 243 By default, does not return the napari viewer. 244 viewer: The viewer to which the Segment Anything functionality should be added. 245 This enables using a pre-initialized viewer. 246 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 247 device: The computational device to use for the SAM model. 248 By default, automatically chooses the best available device. 249 ndim: The dimensionality of the data. If not given will be derived from the data. 250 251 Returns: 252 The napari viewer, only returned if `return_viewer=True`. 253 """ 254 # Prepare the image in the same way as the annotator: squeeze singletons and map the channels to RGB. 255 image, ndim, rgb = util.prepare_annotation_image(image, ndim=ndim) 256 257 state = AnnotatorState() 258 state.image_shape = image.shape[:ndim] 259 state.ndim = ndim 260 261 # The API / CLI computes embeddings before creating the widget, so apply the same size 262 # heuristic here. Reuse these resolved settings when syncing the widget below. 263 tile_shape, halo = resolve_default_tiling(state.image_shape, tile_shape, halo, embedding_path) 264 265 state.initialize_predictor( 266 image, model_type=model_type, save_path=embedding_path, 267 halo=halo, tile_shape=tile_shape, precompute_autoseg_state=False, 268 ndim=ndim, checkpoint_path=checkpoint_path, device=device, 269 use_cli=True, 270 ) 271 272 if viewer is None: 273 viewer = napari.Viewer() 274 275 viewer.add_image(image, name="image", rgb=rgb) 276 viewer.add_labels(util.match_image_shape(segmentation, state.image_shape), name="segmentation") 277 278 annotator = ObjectClassifier(viewer) 279 280 # Trigger layer update of the annotator so that layers have the correct shape. 281 annotator._update_image() 282 283 # Add the annotator widget to the viewer and sync widgets. 284 viewer.window.add_dock_widget(annotator, name=get_dock_title("object_classification")) 285 _sync_embedding_widget( 286 widget=state.widgets["embeddings"], 287 model_type=model_type if checkpoint_path is None else state.predictor.model_type, 288 save_path=embedding_path, 289 checkpoint_path=checkpoint_path, 290 device=device, 291 tile_shape=tile_shape, 292 halo=halo, 293 ) 294 295 if return_viewer: 296 return viewer 297 298 napari.run()
Start the object classifier for a given image and segmentation.
Arguments:
- image: The image data.
- segmentation: The segmentation 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
ObjectClassificationBatchTask(micro_sam.sam_annotator._batch_classification.ClassificationBatchTask):
301class ObjectClassificationBatchTask(ClassificationBatchTask): 302 """Batch task for the object classifier: per-item segmentation layer + projected prediction.""" 303 304 dock_name = get_dock_title("batch_object_classification") 305 classifier_class = ObjectClassifier 306 features_attr = "object_features" 307 aux_attr = "seg_ids" 308 rf_attr = "object_rf" 309 310 def __init__(self, *, segmentations, **kwargs): 311 super().__init__(**kwargs) 312 self.segmentations = segmentations 313 self.visited_segmentations = {} 314 315 def on_leave_item(self, viewer, entry, index): 316 # Keep the segmentation, which may be edited or produced in-tool, for going back to this item. 317 self.visited_segmentations[index] = viewer.layers["segmentation"].data.copy() 318 super().on_leave_item(viewer, entry, index) 319 320 def _set_layers(self, viewer, index): 321 # Load (or carry over) the per-item segmentation. When none is provided, start from an empty 322 # segmentation the user can fill in-tool (the 'produce' path). 323 seg = None if self.segmentations is None else self.segmentations[index] 324 seg = self.visited_segmentations.get(index, seg) 325 if seg is not None and not isinstance(seg, np.ndarray): 326 seg = imageio.imread(seg) 327 if seg is not None: 328 seg = util.match_image_shape(seg, AnnotatorState().image_shape) 329 # Without a segmentation, an empty one, so the objects of the previous item are not carried over. 330 if seg is None: 331 seg = np.zeros(tuple(AnnotatorState().image_shape), dtype="uint32") 332 if "segmentation" in viewer.layers: 333 viewer.layers["segmentation"].data = seg 334 else: 335 viewer.add_labels(seg, name="segmentation")
Batch task for the object classifier: per-item segmentation layer + projected prediction.
classifier_class =
<class 'ObjectClassifier'>
def
on_leave_item(self, viewer, entry, index):
315 def on_leave_item(self, viewer, entry, index): 316 # Keep the segmentation, which may be edited or produced in-tool, for going back to this item. 317 self.visited_segmentations[index] = viewer.layers["segmentation"].data.copy() 318 super().on_leave_item(viewer, entry, index)
Hook called when navigating away from an item (e.g. classifier feature/RF accumulation).
Inherited Members
def
batch_object_classifier( images: List[numpy.ndarray], segmentations: 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]:
338def batch_object_classifier( 339 images: List[np.ndarray], 340 segmentations: List[np.ndarray], 341 output_folder: str, 342 embedding_paths: Optional[List[Union[str, util.ImageEmbeddings]]] = None, 343 model_type: str = DEFAULT_MODEL, 344 tile_shape: Optional[Tuple[int, int]] = None, 345 halo: Optional[Tuple[int, int]] = None, 346 checkpoint_path: Optional[str] = None, 347 device: Optional[Union[str, torch.device]] = None, 348 ndim: Optional[int] = None, 349 viewer: Optional["napari.viewer.Viewer"] = None, 350 return_viewer: bool = False, 351 skip_done: bool = False, 352 batch_size: Optional[int] = 1, 353) -> Optional["napari.viewer.Viewer"]: 354 """Start the object classifier for a list of images and segmentations. 355 356 This function saves the features and labels for annotated objects across the batch, so a random 357 forest can be trained on multiple images, plus the per-image prediction and the trained classifier. 358 359 Args: 360 images: The input images. 361 segmentations: The input segmentations, one per image. 362 output_folder: The folder where predictions, the trained random forest and the accumulated 363 features/labels are saved. 364 embedding_paths: Filepaths where to save/load the embeddings, one per image. 365 model_type: The Segment Anything model to use. For details on the available models check out 366 https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 367 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 368 already cached embeddings, else use the default tiling for images exceeding the in-plane 369 size threshold, and pass smaller images to Segment Anything without tiling. 370 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 371 If `None`, use the default overlap whenever tiling is active. 372 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 373 device: The computational device to use for the SAM model. 374 By default, automatically chooses the best available device. 375 ndim: The dimensionality of the data. If not given will be derived from the data. 376 viewer: The viewer to which the functionality should be added. 377 return_viewer: Whether to return the napari viewer instead of starting the event loop. 378 batch_size: The number of tiles / slices per model call when computing the embeddings. 379 Only has an effect on a GPU. Pass None to select it per device from the free VRAM 380 (SAM2 only). By default a single tile / slice is used. 381 skip_done: Whether to skip images whose prediction already exists in `output_folder`. 382 383 Returns: 384 The napari viewer, only returned if `return_viewer=True`. 385 """ 386 if segmentations is not None and len(images) != len(segmentations): 387 raise ValueError( 388 f"Expect the same number of images and segmentations, got {len(images)}, {len(segmentations)}." 389 ) 390 391 have_inputs_as_arrays = isinstance(images[0], np.ndarray) 392 if ndim is None: 393 ndim = load_batch_image(images[0])[1] 394 395 task = ObjectClassificationBatchTask( 396 segmentations=segmentations, ndim=ndim, model_type=model_type, embedding_paths=embedding_paths, 397 tile_shape=tile_shape, halo=halo, checkpoint_path=checkpoint_path, device=device, 398 batch_size=batch_size, 399 ) 400 return run_batch( 401 images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays, 402 viewer=viewer, return_viewer=return_viewer, skip_done=skip_done, 403 )
Start the object classifier for a list of images and segmentations.
This function saves the features and labels for annotated objects 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.
- segmentations: The input segmentations, one per image.
- 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.