micro_sam.sam_annotator._annotator
1import os 2from datetime import datetime 3from typing import List, Optional 4from joblib import dump, hash as joblib_hash, load 5 6import numpy as np 7 8import napari 9from napari.utils.notifications import show_info, show_warning 10from napari.utils.colormaps import DirectLabelColormap, label_colormap 11 12from qtpy import QtCore, QtGui, QtWidgets 13from magicgui.widgets import CheckBox, ComboBox, Container, FileEdit, FunctionGui, Label, PushButton, SpinBox, Widget 14 15from . import util as vutil 16from . import _widgets as widgets 17from ._state import AnnotatorState 18from ._tooltips import get_tooltip 19from ..__version__ import __version__ as micro_sam_version 20 21# Placeholder shapes used to seed the annotator layers before a real image is loaded. 22# Only the dimensionality matters. The tool resets the values to the image shape on load. 23PLACEHOLDER_SHAPE = {2: (256, 256), 3: (16, 256, 256)} 24 25 26class _AnnotatorBase(QtWidgets.QScrollArea): 27 """Base class for micro_sam annotation plugins. 28 29 Implements the logic for the 2d, 3d and tracking annotator. 30 The annotators differ in their data dimensionality and the widgets. 31 """ 32 33 def _require_layers(self, layer_choices: Optional[List[str]] = None): 34 35 # Check whether the image is initialized already. And use the image shape and scale for the layers. 36 state = AnnotatorState() 37 shape = self._shape if state.image_shape is None else state.image_shape 38 39 # Add the label layers for the current object, the automatic segmentation and the committed segmentation. 40 dummy_data = np.zeros(shape, dtype="uint32") 41 image_scale = state.image_scale 42 43 # Before adding new layers, we always check whether a layer with this name already exists or not. 44 if "current_object" not in self._viewer.layers: 45 if ( 46 layer_choices and "current_object" in layer_choices 47 ): # Check at 'commit' call button. 48 widgets._validation_window_for_missing_layer("current_object") 49 self._viewer.add_labels(data=dummy_data, name="current_object") 50 if image_scale is not None: 51 self._viewer.layers["current_object"].scale = image_scale 52 53 if "auto_segmentation" not in self._viewer.layers: 54 if ( 55 layer_choices and "auto_segmentation" in layer_choices 56 ): # Check at 'commit' call button. 57 widgets._validation_window_for_missing_layer( 58 "auto_segmentation" 59 ) 60 self._viewer.add_labels(data=dummy_data, name="auto_segmentation") 61 if image_scale is not None: 62 self._viewer.layers["auto_segmentation"].scale = image_scale 63 64 if "committed_objects" not in self._viewer.layers: 65 if ( 66 layer_choices and "committed_objects" in layer_choices 67 ): # Check at 'commit' call button. 68 widgets._validation_window_for_missing_layer( 69 "committed_objects" 70 ) 71 self._viewer.add_labels(data=dummy_data, name="committed_objects") 72 # Randomize colors so it is easy to see when object committed. 73 self._viewer.layers["committed_objects"].new_colormap() 74 if image_scale is not None: 75 self._viewer.layers["committed_objects"].scale = image_scale 76 77 # Add the point layer for point prompts. 78 self._point_labels = ["positive", "negative"] 79 if "point_prompts" in self._viewer.layers: 80 self._point_prompt_layer = self._viewer.layers["point_prompts"] 81 else: 82 self._point_prompt_layer = self._viewer.add_points( 83 name="point_prompts", 84 property_choices={"label": self._point_labels}, 85 border_color="label", 86 border_color_cycle=vutil.LABEL_COLOR_CYCLE, 87 symbol="o", 88 face_color="transparent", 89 border_width=0.5, 90 size=12, 91 ndim=self._ndim, 92 ) 93 self._point_prompt_layer.border_color_mode = "cycle" 94 95 if "prompts" in self._viewer.layers: 96 self._shape_prompt_layer = self._viewer.layers["prompts"] 97 else: 98 # Add the shape layer for box and other shape prompts. 99 self._shape_prompt_layer = self._viewer.add_shapes( 100 face_color="transparent", 101 edge_color="label", 102 edge_color_cycle=vutil.LABEL_COLOR_CYCLE, 103 edge_width=4, 104 name="prompts", 105 ndim=self._ndim, 106 property_choices={"label": self._point_labels}, 107 ) 108 self._shape_prompt_layer.edge_color_mode = "cycle" 109 110 # Migrate a pre-existing prompt layer and keep boxes / dense mask prompts green. Open 111 # paths retain their positive / negative property and use the same colors as point prompts. 112 if "label" not in self._shape_prompt_layer.properties: 113 properties = dict(self._shape_prompt_layer.properties) 114 properties["label"] = np.full(len(self._shape_prompt_layer.data), "positive", dtype=object) 115 self._shape_prompt_layer.properties = properties 116 current_properties = self._shape_prompt_layer.current_properties 117 current_properties["label"] = np.array(["positive"]) 118 self._shape_prompt_layer.current_properties = current_properties 119 self._shape_prompt_layer.edge_color_cycle = vutil.LABEL_COLOR_CYCLE 120 self._shape_prompt_layer.edge_color = "label" 121 self._shape_prompt_layer.edge_color_mode = "cycle" 122 if not self._shape_prompt_layer.metadata.get("micro_sam_prompt_labels_configured", False): 123 self._shape_prompt_layer.events.data.connect(vutil.normalize_prompt_shape_labels) 124 self._shape_prompt_layer.events.mode.connect(vutil.sync_prompt_shape_current_color) 125 self._shape_prompt_layer.events.current_properties.connect(vutil.sync_prompt_shape_current_color) 126 self._shape_prompt_layer.metadata["micro_sam_prompt_labels_configured"] = True 127 vutil.normalize_prompt_shape_labels(self._shape_prompt_layer) 128 vutil.sync_prompt_shape_current_color(self._shape_prompt_layer) 129 130 # Child classes have to implement this function and create a dictionary with the widgets. 131 def _get_widgets(self): 132 raise NotImplementedError( 133 "The child classes of _AnnotatorBase have to implement _get_widgets." 134 ) 135 136 def _create_embedding_widget(self): 137 return widgets.EmbeddingWidget() 138 139 def _create_widgets(self): 140 # Create the embedding widget and connect all events related to it. 141 self._embedding_widget = self._create_embedding_widget() 142 # Connect events for the image selection box. 143 self._viewer.layers.events.inserted.connect( 144 self._embedding_widget.image_selection.reset_choices 145 ) 146 self._viewer.layers.events.removed.connect( 147 self._embedding_widget.image_selection.reset_choices 148 ) 149 # Connect the run button with the function to update the image. 150 self._embedding_widget.run_button.clicked.connect(self._update_image) 151 152 # Create the prompt widget. (The same for all plugins.) 153 # Child plugins decide whether to expose it as a separate group (e.g. tracking) or to 154 # embed it into another widget (e.g. the interactive segmentation widget). 155 shape_prompt_layer = self._viewer.layers["prompts"] 156 linked_layers = [shape_prompt_layer] if "label" in shape_prompt_layer.current_properties else None 157 self._prompt_widget = widgets.create_prompt_menu( 158 self._point_prompt_layer, self._point_labels, linked_layers=linked_layers, 159 viewer=self._viewer, 160 ) 161 162 # Create the dictionary for the widgets and get the widgets of the child plugin. 163 self._widgets = {"embeddings": self._embedding_widget} 164 self._widgets.update(self._get_widgets()) 165 self._connect_commit_layer_selection() 166 167 def _create_keybindings(self): 168 @self._viewer.bind_key("s", overwrite=True) 169 def _segment(viewer): 170 self._widgets["segment"](viewer) 171 172 # Note: we also need to over-write the keybindings for specific layers. 173 # See https://github.com/napari/napari/issues/7302 for details. 174 # Here, we need to over-write the 's' keybinding for both of the prompt layers. 175 prompt_layer = self._viewer.layers["prompts"] 176 point_prompt_layer = self._viewer.layers["point_prompts"] 177 178 @prompt_layer.bind_key("s", overwrite=True) 179 def _segment_prompts(event): 180 self._widgets["segment"](self._viewer) 181 182 @point_prompt_layer.bind_key("s", overwrite=True) 183 def _segment_point_prompts(event): 184 self._widgets["segment"](self._viewer) 185 186 # The layer the key reached is the active one, so it goes first: only it relabels a selected 187 # scribble. The viewer-level fallback below has no active prompt layer, so it relabels none. 188 @prompt_layer.bind_key("t", overwrite=True) 189 def _toggle_shape_prompt_label(event=None): 190 vutil.toggle_label(self._shape_prompt_layer, self._point_prompt_layer) 191 192 @point_prompt_layer.bind_key("t", overwrite=True) 193 def _toggle_point_prompt_label(event=None): 194 vutil.toggle_label(self._point_prompt_layer, self._shape_prompt_layer) 195 196 @self._viewer.bind_key("c", overwrite=True) 197 def _commit(viewer): 198 self._widgets["commit"](viewer) 199 200 @self._viewer.bind_key("t", overwrite=True) 201 def _toggle_label(event=None): 202 vutil.toggle_label(self._point_prompt_layer, self._shape_prompt_layer) 203 204 @self._viewer.bind_key("Shift-C", overwrite=True) 205 def _clear_annotations(viewer): 206 self._widgets["clear"](viewer) 207 208 # We could implement a better way of initializing the segmentation result, 209 # so that instead of just passing a numpy array an existing layer from the napari 210 # viewer can be chosen. 211 # See https://github.com/computational-cell-analytics/micro-sam/issues/335 212 def __init__(self, viewer: "napari.viewer.Viewer", ndim: int) -> None: 213 """Create the annotator GUI. 214 215 Args: 216 viewer: The napari viewer. 217 ndim: The number of spatial dimension of the image data (2 or 3). 218 """ 219 super().__init__() 220 self._viewer = viewer 221 222 # Guard against re-entrant image-selection handling while we replace the image 223 # layer during normalization (the replacement itself fires selection events). 224 self._suppress_selection_rebuild = False 225 226 # Add the layers for prompts and segmented obejcts. 227 # Initialize with a dummy shape, which is reset to the correct shape once an image is set. 228 self._ndim = ndim 229 self._shape = PLACEHOLDER_SHAPE[ndim] 230 self._require_layers() 231 232 # Create all the widgets and populate the layout. 233 self._create_widgets() 234 AnnotatorState().widgets = self._widgets 235 236 # Add the key bindings in common between all annotators. 237 self._create_keybindings() 238 239 # Build the scroll area content from the current set of widgets. 240 self._populate_widget_layout() 241 242 def _populate_widget_layout(self): 243 # Build the scroll area content from the current set of widgets in 'self._widgets'. 244 # This can be called again to rebuild the layout, e.g. when the image dimensionality 245 # changes and the dimension-specific widgets have to be replaced. 246 annotator_widget = QtWidgets.QWidget() 247 annotator_widget.setLayout(QtWidgets.QVBoxLayout()) 248 for widget in self._widgets.values(): 249 widget_frame = QtWidgets.QGroupBox() 250 widget_layout = QtWidgets.QVBoxLayout() 251 if isinstance(widget, (Container, FunctionGui, Widget)): 252 # This is a magicgui type and we need to get the native qt widget. 253 widget_layout.addWidget(widget.native) 254 else: 255 # This is a qt type and we add the widget directly. 256 widget_layout.addWidget(widget) 257 widget_frame.setLayout(widget_layout) 258 annotator_widget.layout().addWidget(widget_frame) 259 260 # Each container keeps the height of its contents. Without this the leftover space of the 261 # dock is spread over the containers, which pulls their rows apart. 262 annotator_widget.layout().addStretch() 263 264 self._annotator_widget = annotator_widget 265 # Allow widget to resize within scroll area. 266 self.setWidgetResizable(True) 267 # Replacing the inner widget deletes the previous one (and its now-orphaned children). 268 self.setWidget(self._annotator_widget) 269 270 def _maybe_normalize_image_layer(self, image_layer, ndim=None): 271 """Normalize the selected image layer in place so all layers stay aligned. 272 273 Squeezes singleton axes and maps the channel axis to RGB (see 274 ``util.prepare_annotation_image``). When this changes the data shape or the rgb 275 flag, the image layer is replaced with the normalized version. Replacement passes 276 the normalized array by reference (napari does not copy), so it does not duplicate 277 the image buffer. Returns the (possibly new) layer and its spatial dimensionality. 278 279 Args: 280 image_layer: The selected napari image layer. 281 ndim: Optional image-dimensionality override forwarded to ``prepare_annotation_image`` 282 (``None`` = auto-detect, else 2 or 3). 283 """ 284 # Re-derive from the original (pre-normalization) data when available, so toggling the ndim 285 # override reinterprets the raw image instead of an already-reduced one. 286 source = image_layer.metadata.get("micro_sam_original_data", image_layer.data) 287 data, detected_ndim, rgb = vutil.prepare_annotation_image(source, ndim=ndim) 288 289 # Nothing changed: keep the existing layer. 290 if data.shape == tuple(image_layer.data.shape) and bool(image_layer.rgb) == rgb: 291 return image_layer, detected_ndim 292 293 name = image_layer.name 294 scale = image_layer.scale 295 # Carry over the scale only when it still matches the normalized dimensionality. 296 keep_scale = len(scale) == (data.ndim - 1 if rgb else data.ndim) 297 298 self._suppress_selection_rebuild = True 299 try: 300 del self._viewer.layers[name] 301 new_layer = self._viewer.add_image(data, name=name, rgb=rgb) 302 if keep_scale: 303 new_layer.scale = scale 304 # Remember the original so a later ndim-override change re-derives from it. 305 new_layer.metadata["micro_sam_original_data"] = source 306 finally: 307 self._suppress_selection_rebuild = False 308 309 return new_layer, detected_ndim 310 311 def _rebuild_for_ndim(self, ndim, force=False): 312 # Rebuild the layers and dimension-specific widgets for a new dimensionality. 313 # This supports loading an image whose dimensionality differs from the one the 314 # annotator was created with, e.g. opening the plugin and then loading a 3D image. 315 # 'force=True' rebuilds even when the dimensionality is unchanged - used on an image 316 # change to reset the widgets (checkboxes, ...) and layers to a fresh-open state. 317 if ndim == self._ndim and not force: 318 return 319 self._ndim = ndim 320 self._shape = PLACEHOLDER_SHAPE[ndim] 321 322 # Remove the existing micro_sam layers so they are recreated with the new ndim and shape. 323 layer_names = ("current_object", "auto_segmentation", "committed_objects", "point_prompts", "prompts") 324 for layer_name in layer_names: 325 if layer_name in self._viewer.layers: 326 del self._viewer.layers[layer_name] 327 self._require_layers() 328 329 # The prompt widget is bound to the point prompt layer, so it is recreated alongside it. 330 shape_prompt_layer = self._viewer.layers["prompts"] 331 linked_layers = [shape_prompt_layer] if "label" in shape_prompt_layer.current_properties else None 332 self._prompt_widget = widgets.create_prompt_menu( 333 self._point_prompt_layer, self._point_labels, linked_layers=linked_layers, 334 viewer=self._viewer, 335 ) 336 337 # Rebuild the dimension-specific widgets, keeping the shared embedding widget. 338 self._widgets = {"embeddings": self._embedding_widget} 339 self._widgets.update(self._get_widgets()) 340 self._connect_commit_layer_selection() 341 AnnotatorState().widgets = self._widgets 342 343 # Rebuild the layout and rebind the keybindings to the new widgets and layers. 344 self._populate_widget_layout() 345 self._create_keybindings() 346 347 # napari 0.9 caps the height of dock widget content at its size hint (napari/napari#9393). 348 def showEvent(self, event): 349 size_policy = self.sizePolicy() 350 size_policy.setVerticalPolicy(QtWidgets.QSizePolicy.Policy.Expanding) 351 self.setSizePolicy(size_policy) 352 super().showEvent(event) 353 354 def _set_commit_layer(self, layer_name): 355 commit_widget = getattr(self, "_widgets", {}).get("commit") 356 if commit_widget is not None: 357 commit_widget.layer.value = layer_name 358 359 def _connect_commit_layer_selection(self): 360 # The commit layer follows the last segmentation: interactive segmentation selects 361 # 'current_object' and automatic segmentation selects 'auto_segmentation'. 362 if not all(name in self._widgets for name in ("interactive", "autosegment", "commit")): 363 return 364 self._widgets["interactive"].segment_requested.connect( 365 lambda: self._set_commit_layer("current_object") 366 ) 367 self._widgets["autosegment"].segmentation_finished.connect( 368 lambda: self._set_commit_layer("auto_segmentation") 369 ) 370 371 def _update_image(self, segmentation_result=None): 372 state = AnnotatorState() 373 374 # Whether embeddings already exist and avoid clearing objects in layers. 375 if state.skip_recomputing_embeddings: 376 return 377 378 # This is encountered when there is no image layer available / selected. 379 # In this case, we need not update the image shape or check for changes. 380 # NOTE: On code-level, this happens when '__init__' method is called by '_AnnotatorBase', 381 # where one of the first steps is to '_create_widgets', which reaches here. 382 if state.image_shape is None: 383 return 384 385 # Update the image shape if it has changed. 386 if state.image_shape != self._shape: 387 if len(state.image_shape) != self._ndim: 388 raise RuntimeError( 389 f"The dim of the annotator {self._ndim} does not match the image data of shape {state.image_shape}." 390 ) 391 self._shape = state.image_shape 392 393 # Before we reset the layers, we ensure all expected layers exist. 394 self._require_layers() 395 396 # Update the image scale. 397 scale = state.image_scale 398 399 # Reset all layers. 400 self._viewer.layers["current_object"].data = np.zeros( 401 self._shape, dtype="uint32" 402 ) 403 self._viewer.layers["current_object"].scale = scale 404 self._viewer.layers["auto_segmentation"].data = np.zeros( 405 self._shape, dtype="uint32" 406 ) 407 self._viewer.layers["auto_segmentation"].scale = scale 408 409 if segmentation_result is None or segmentation_result is False: 410 self._viewer.layers["committed_objects"].data = np.zeros( 411 self._shape, dtype="uint32" 412 ) 413 else: 414 assert segmentation_result.shape == self._shape 415 self._viewer.layers["committed_objects"].data = segmentation_result 416 self._viewer.layers["committed_objects"].scale = scale 417 418 self._viewer.layers["point_prompts"].scale = scale 419 self._viewer.layers["prompts"].scale = scale 420 421 vutil.clear_annotations(self._viewer, clear_segmentations=False) 422 self._set_commit_layer("current_object") 423 424 425class _ClassifierBase(QtWidgets.QScrollArea): 426 """Base class for the pixel and object classifier plugins. 427 428 Holds the shared GUI scaffolding (layers, label widget, settings/train widgets) and the 429 train/predict/clear/load/save/spec logic. Subclasses declare the state-attribute names and 430 implement the per-tool feature computation, label accumulation, training and prediction 431 projection via a small set of hooks. Both tools have an 'annotations' and a 'prediction' label 432 layer; the dimensionality follows the image (2d YX or 3d ZYX). 433 """ 434 435 # Per-tool configuration, set by subclasses. 436 rf_attr = None # state attribute holding the trained classifier 437 features_attr = None # state attribute caching the features 438 aux_attr = None # state attribute caching the per-tool aux data (grid_shape | seg_ids) 439 label_widget_title = "Label names:" 440 max_components = 256 # PCA upper bound (256 pixel channels, 257 object features) 441 tool_key = None # "pixel" | "object", selects the tool-specific tooltips 442 classical_feature_choices = () # the classical features this tool supports 443 supports_apply_to_volume = True # if False the tool always runs over the full image/volume 444 445 # 446 # Hooks the subclasses implement. 447 # 448 449 def _compute_features(self): 450 """Return (features, aux) for the current image, caching on the state; (None, None) on failure.""" 451 raise NotImplementedError 452 453 def _compute_training_labels(self, aux): 454 """Return the per-feature-row training labels (0 = unlabeled), or None on failure.""" 455 raise NotImplementedError 456 457 def _train(self, features, labels, previous_features, previous_labels, n_components, random_state): 458 """Train and return the classifier.""" 459 raise NotImplementedError 460 461 def _project_prediction(self, prediction, aux): 462 """Map the flat per-row prediction back to an image-shaped array, or None on failure.""" 463 raise NotImplementedError 464 465 def _extra_classification_sections(self): 466 """Extra widgets/layouts shown above the settings dropdown (e.g. the segmentation selector).""" 467 return [] 468 469 # 470 # Shared state accessors and helpers. 471 # 472 473 def _invalidate_features(self, *args): 474 state = AnnotatorState() 475 setattr(state, self.features_attr, None) 476 setattr(state, self.aux_attr, None) 477 478 def _get_rf(self): 479 return getattr(AnnotatorState(), self.rf_attr) 480 481 def _set_rf(self, rf): 482 setattr(AnnotatorState(), self.rf_attr, rf) 483 484 def _current_slice(self): 485 # The z index currently shown in the viewer (for 3d per-slice operations). 486 return vutil.current_slice(self._viewer, self._viewer.layers["annotations"]) 487 488 def _get_cached_upsampler(self): 489 # Load the AnyUp model once and cache it on the state (small model, reused across runs). 490 from ..pixel_classification import get_anyup_upsampler 491 state = AnnotatorState() 492 if state.anyup_upsampler is None: 493 device = getattr(state.predictor, "device", None) 494 state.anyup_upsampler = get_anyup_upsampler(device=device) 495 return state.anyup_upsampler 496 497 def _resolve_feature_inputs(self): 498 # Returns (image, upsampler, classical_features, ok). The image is only needed for AnyUp or 499 # the classical features, and is None otherwise. 500 upsampler = None 501 if self._get_use_anyup(): 502 try: 503 upsampler = self._get_cached_upsampler() 504 except ImportError as e: 505 widgets._generate_message("error", str(e)) 506 return None, None, None, False 507 classical_features = self._get_classical_features() 508 use_image = upsampler is not None or classical_features is not None 509 image = self._viewer.layers["image"].data if use_image else None 510 return image, upsampler, classical_features, True 511 512 def _feature_settings(self): 513 # The settings that change the feature values. Training data from other settings is not mixed in. 514 return {"use_anyup": bool(self._get_use_anyup())} 515 516 def store_batch_training_data(self, index): 517 """Store the current image's labeled features as the batch training data of item `index`. 518 519 Replaces any earlier entry of this item, so a revisited image contributes its latest 520 annotations exactly once. Removes the entry when the image has no annotations. 521 """ 522 state = AnnotatorState() 523 features, aux = self._compute_features() 524 if features is None: 525 return 526 labels = self._compute_training_labels(aux) 527 if labels is None: 528 return 529 valid = labels != 0 530 if valid.sum() == 0: 531 state.batch_training_data.pop(index, None) 532 return 533 state.batch_training_data[index] = (features[valid], labels[valid], self._feature_settings()) 534 535 def batch_training_set(self, exclude_index=None): 536 """Return the concatenated batch training data of all items except `exclude_index`. 537 538 Returns (None, None) when there is no such data. Skips items whose features were computed with 539 other feature settings, and warns about them. 540 """ 541 data = AnnotatorState().batch_training_data 542 if not data: 543 return None, None 544 settings = self._feature_settings() 545 entries = [(idx, v) for idx, v in sorted(data.items()) if idx != exclude_index] 546 skipped = [idx for idx, v in entries if v[2] != settings] 547 if skipped: 548 show_warning( 549 f"Skipping the annotations of the images {skipped} for training, because their features were " 550 f"computed with other settings ({[data[idx][2] for idx in skipped]}, current: {settings})." 551 ) 552 entries = [v for idx, v in entries if idx not in skipped] 553 if not entries: 554 return None, None 555 return np.concatenate([v[0] for v in entries], axis=0), np.concatenate([v[1] for v in entries], axis=0) 556 557 def _training_settings(self): 558 return { 559 **self._feature_settings(), 560 "n_components": self._get_n_components(), "random_state": self._get_random_state(), 561 } 562 563 def is_prediction_stale(self): 564 """Whether the annotations or the training settings changed since the last training run.""" 565 if self._trained_annotations is None: 566 return True 567 annotations, settings = self._trained_annotations 568 return settings != self._training_settings() or not np.array_equal( 569 annotations, self._viewer.layers["annotations"].data 570 ) 571 572 # 573 # Layers. 574 # 575 576 def _require_layers(self, layer_choices: Optional[List[str]] = None): 577 # The dimensionality comes from the embedding widget ('state.ndim', RGB-aware) so the label 578 # layers always match the image: 2d (YX) for 2d data, 3d (ZYX) for 3d data. 579 state = AnnotatorState() 580 if state.image_shape is None: 581 ndim, shape = self._ndim, self._shape 582 else: 583 ndim = len(state.image_shape) if state.ndim is None else state.ndim 584 shape = tuple(state.image_shape)[:ndim] 585 586 dummy_data = np.zeros(shape, dtype="uint32") 587 image_scale = None if state.image_scale is None else tuple(state.image_scale)[:ndim] 588 589 # Drop any existing label layer whose dimensionality no longer matches the image. Reassigning 590 # data of a different ndim corrupts the napari layer transforms, so we rebuild from scratch. 591 for name in ("annotations", "prediction"): 592 if name in self._viewer.layers and self._viewer.layers[name].data.ndim != len(shape): 593 del self._viewer.layers[name] 594 595 created = False 596 if "annotations" not in self._viewer.layers: 597 created = True 598 if layer_choices and "annotations" in layer_choices: 599 widgets._validation_window_for_missing_layer("annotations") 600 annotation_layer = self._viewer.add_labels(data=dummy_data, name="annotations") 601 if image_scale is not None: 602 self._viewer.layers["annotations"].scale = image_scale 603 # Reduce the brush size and set the default mode to "paint" brush mode. 604 annotation_layer.brush_size = 3 605 annotation_layer.mode = "paint" 606 # Start painting with label id 1 (id 0 is the unlabeled background). napari already 607 # defaults 'selected_label' to 1, so assigning 1 fires no change-event and the layer 608 # controls spinbox stays at its displayed 0. Toggle to force the event so it shows 1. 609 annotation_layer.selected_label = 2 610 annotation_layer.selected_label = 1 611 612 if "prediction" not in self._viewer.layers: 613 created = True 614 if layer_choices and "prediction" in layer_choices: 615 widgets._validation_window_for_missing_layer("prediction") 616 self._viewer.add_labels(data=dummy_data, name="prediction") 617 if image_scale is not None: 618 self._viewer.layers["prediction"].scale = image_scale 619 620 # A new layer has napari's default colors and no connection to the class widget yet. 621 if created and self._class_group is not None: 622 self._connect_annotations_layer() 623 self._apply_class_colors() 624 625 # Move 'annotations' to the top of the layer stack so scribbles are always visible above the 626 # prediction, and make it the active layer so the controls (incl. the label id) show it and 627 # the user can paint right away rather than on the last-added 'prediction' layer. 628 self._viewer.layers.move(self._viewer.layers.index("annotations"), len(self._viewer.layers)) 629 self._viewer.layers.selection.active = self._viewer.layers["annotations"] 630 631 def _update_image(self, segmentation_result=None): 632 state = AnnotatorState() 633 634 # Whether embeddings already exist and avoid clearing objects in layers. 635 if state.skip_recomputing_embeddings: 636 return 637 638 if state.image_shape is None: 639 return 640 641 # Use the dimensionality determined by the embedding widget ('state.ndim', RGB-aware) so the label 642 # layers always match the image: 2d (YX) for 2d data, 3d (ZYX) for 3d data. '_require_layers' 643 # rebuilds any layer whose dimensionality no longer matches before we reset its data. 644 self._ndim = len(state.image_shape) if state.ndim is None else state.ndim 645 self._shape = tuple(state.image_shape)[:self._ndim] 646 647 # The 'Apply to Volume' checkbox only makes sense for 3d data (and only for tools that have it). 648 if self._apply_to_volume is not None: 649 self._apply_to_volume.visible = self._ndim == 3 650 651 # The features depend on the image, so they have to be recomputed for a new image. 652 self._invalidate_features() 653 self._trained_annotations = None 654 655 # Before we reset the layers, we ensure all expected layers exist at the correct ndim. 656 self._require_layers() 657 658 scale = None if state.image_scale is None else tuple(state.image_scale)[:self._ndim] 659 self._viewer.layers["annotations"].data = np.zeros(self._shape, dtype="uint32") 660 self._viewer.layers["prediction"].data = np.zeros(self._shape, dtype="uint32") 661 if scale is not None: 662 self._viewer.layers["annotations"].scale = scale 663 self._viewer.layers["prediction"].scale = scale 664 665 # 666 # Class widget. 667 # 668 669 def _create_label_widget(self): 670 # One row per class: id, a radio button that selects the class for painting, a color swatch, 671 # a button that removes the class and an optional name. 672 self._class_rows = {} # class id -> (row widget, color swatch, name field) 673 self._class_group = QtWidgets.QButtonGroup() 674 self._class_group.idClicked.connect(self._select_class) 675 # The rows have no scroll area of their own. The dock scrolls, so all classes stay visible. 676 self._class_layout = QtWidgets.QVBoxLayout() 677 self._class_layout.setContentsMargins(0, 0, 0, 0) 678 self._class_layout.setSpacing(0) 679 680 add_button = QtWidgets.QPushButton("Add Class") 681 add_button.setToolTip(get_tooltip("classification", "add_class")) 682 add_button.clicked.connect(lambda: self._select_class(max(self._classes, default=0) + 1)) 683 684 @self._viewer.bind_key("Alt-Right", overwrite=True) 685 def _next_class(event=None): 686 self._cycle_class(1) 687 688 @self._viewer.bind_key("Alt-Left", overwrite=True) 689 def _previous_class(event=None): 690 self._cycle_class(-1) 691 692 layout = QtWidgets.QVBoxLayout() 693 header = QtWidgets.QLabel(self.label_widget_title) 694 header.setToolTip(get_tooltip("classification", "label_names")) 695 layout.addWidget(header) 696 layout.addWidget(QtWidgets.QLabel("Previous / next class [Alt + Left / Right]")) 697 layout.addLayout(self._class_layout) 698 layout.addWidget(add_button) 699 return layout 700 701 def _add_class_row(self, class_id): 702 if class_id not in self._classes: 703 # 'label_colormap(49)' is the default colormap of napari labels layers, so a new class keeps its color. 704 color = QtGui.QColor.fromRgbF(*(float(c) for c in label_colormap(49).map(class_id)[:3])).name() 705 self._classes[class_id] = {"name": "", "color": color} 706 707 row = QtWidgets.QWidget() 708 row_layout = QtWidgets.QHBoxLayout(row) 709 row_layout.setContentsMargins(0, 0, 0, 0) 710 row_layout.setSpacing(4) 711 712 # Fixed sizes keep the columns aligned. The first row is made before napari applies its 713 # stylesheet, which changes the font and the button size hints of the later rows. 714 id_label = QtWidgets.QLabel(str(class_id)) 715 id_label.setFixedWidth(24) 716 id_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) 717 radio = QtWidgets.QRadioButton() 718 radio.setFixedSize(20, 20) 719 radio.setToolTip(get_tooltip("classification", "class_select")) 720 self._class_group.addButton(radio, class_id) 721 swatch = QtWidgets.QPushButton() 722 swatch.setFixedSize(28, 18) 723 swatch.setToolTip(get_tooltip("classification", "class_color")) 724 swatch.setStyleSheet(f"background-color: {self._classes[class_id]['color']}; border: 1px solid #888;") 725 swatch.clicked.connect(lambda: self._pick_class_color(class_id)) 726 # The frame and the red hover color mark the button as a remove action. 727 # The palette colors fit both napari themes. 728 remove = QtWidgets.QToolButton() 729 remove.setText("×") 730 remove.setFixedSize(20, 18) 731 remove.setCursor(QtCore.Qt.PointingHandCursor) 732 remove.setStyleSheet( 733 "QToolButton { padding: 0px; font-size: 14px; font-weight: bold;" 734 " border: 1px solid palette(mid); border-radius: 3px; background-color: palette(button); }" 735 "QToolButton:hover { background-color: #c0392b; border-color: #c0392b; color: white; }" 736 "QToolButton:pressed { background-color: #962d22; }" 737 ) 738 remove.setToolTip(get_tooltip("classification", "class_remove")) 739 remove.clicked.connect(lambda: self._remove_class(class_id)) 740 name = QtWidgets.QLineEdit(self._classes[class_id]["name"]) 741 name.setMaximumWidth(180) 742 name.setToolTip(get_tooltip("classification", "label_name_row")) 743 name.textChanged.connect(lambda text: self._classes[class_id].__setitem__("name", text)) 744 for widget in (id_label, radio, swatch, remove, name): 745 row_layout.addWidget(widget) 746 row_layout.addStretch(1) 747 748 # The rows stay sorted by class id. 749 position = sum(other < class_id for other in self._class_rows) 750 self._class_layout.insertWidget(position, row) 751 self._class_rows[class_id] = (row, swatch, name) 752 753 def _ensure_classes(self, class_ids): 754 new_ids = [int(i) for i in class_ids if int(i) != 0 and int(i) not in self._class_rows] 755 for class_id in new_ids: 756 self._add_class_row(class_id) 757 if new_ids: 758 self._apply_class_colors() 759 760 def _apply_class_colors(self): 761 # An id without a class is white. Each id in the annotations, the training data of the other images 762 # and the classes of the classifier gets a class row, so this is rare. 763 color_dict = {None: "white", 0: "transparent", **{i: c["color"] for i, c in self._classes.items()}} 764 for name in ("annotations", "prediction"): 765 if name in self._viewer.layers: 766 self._viewer.layers[name].colormap = DirectLabelColormap(color_dict=color_dict) 767 768 def _connect_annotations_layer(self): 769 # '_require_layers' recreates the layer when the image dimensionality changes, so connect to the current layer. 770 layer = self._viewer.layers["annotations"] 771 if layer is self._connected_annotations: 772 return 773 layer.events.selected_label.connect(self._on_selected_label) 774 layer.events.data.connect(self._refresh_label_widget) 775 self._connected_annotations = layer 776 777 def _select_class(self, class_id): 778 layer = self._viewer.layers["annotations"] 779 layer.selected_label = class_id 780 layer.mode = "paint" 781 self._viewer.layers.selection.active = layer 782 self._on_selected_label() 783 784 def _cycle_class(self, step): 785 class_ids = sorted(self._classes) 786 if not class_ids or "annotations" not in self._viewer.layers: 787 return 788 current = self._viewer.layers["annotations"].selected_label 789 index = (class_ids.index(current) + step) % len(class_ids) if current in class_ids else 0 790 self._select_class(class_ids[index]) 791 792 def _on_selected_label(self, event=None): 793 # A label id selected in the napari layer controls selects its class here, or creates it. 794 class_id = int(self._viewer.layers["annotations"].selected_label) 795 if class_id == 0: 796 return 797 self._ensure_classes([class_id]) 798 self._class_group.button(class_id).setChecked(True) 799 800 def _pick_class_color(self, class_id): 801 color = QtWidgets.QColorDialog.getColor(QtGui.QColor(self._classes[class_id]["color"]), self) 802 if color.isValid(): 803 self._set_class_color(class_id, color.name()) 804 805 def _set_class_color(self, class_id, color): 806 self._classes[class_id]["color"] = color 807 self._class_rows[class_id][1].setStyleSheet(f"background-color: {color}; border: 1px solid #888;") 808 self._apply_class_colors() 809 810 def _set_class_name(self, class_id, name): 811 self._class_rows[class_id][2].setText(name) 812 813 def _remove_class(self, class_id, confirm=True): 814 # Removes the class and its annotations in the current image. This does not change the training data 815 # of the other images, so a class that is annotated there cannot be removed here. For a class of the current 816 # classifier only the annotations are removed: the prediction can still show it, so its row stays until 817 # the classifier is retrained without it. 818 state = AnnotatorState() 819 rf = self._get_rf() 820 in_classifier = rf is not None and class_id in rf.classes_ 821 822 other_images = [ 823 idx for idx, (_, labels, _) in (state.batch_training_data or {}).items() 824 if idx != state.batch_index and np.any(labels == class_id) 825 ] 826 if other_images: 827 return widgets._generate_message( 828 "error", f"Class {class_id} is annotated in the images {other_images}. Remove it there first." 829 ) 830 831 layer = self._viewer.layers["annotations"] 832 annotated = layer.data == class_id 833 if annotated.any(): 834 if in_classifier: 835 question = f"Remove the annotations of class {class_id} in this image?" 836 else: 837 question = f"Remove class {class_id} and its annotations in this image?" 838 if confirm and widgets._generate_message("info", question): 839 return 840 data = layer.data 841 data[annotated] = 0 842 layer.data = data 843 844 if in_classifier: 845 return show_info( 846 f"Class {class_id} is a class of the current classifier. Retrain the classifier without its " 847 "annotations, then remove the class." 848 ) 849 850 row = self._class_rows.pop(class_id)[0] 851 self._class_group.removeButton(self._class_group.button(class_id)) 852 # Take the row out of the layout now: 'deleteLater' deletes the row only in the next event loop. 853 self._class_layout.removeWidget(row) 854 row.deleteLater() 855 del self._classes[class_id] 856 857 # Paint with the remaining class with the lowest id. If no class remains, '_on_selected_label' creates class 1. 858 if layer.selected_label == class_id: 859 layer.selected_label = min(self._classes, default=1) 860 self._on_selected_label() 861 self._apply_class_colors() 862 863 def _refresh_label_widget(self, event=None): 864 # Add a class row for each id in the annotations, the training data of the other images, the classes 865 # of the classifier and the selected label. Rows are removed only with their 'x' button. 866 state = AnnotatorState() 867 self._connect_annotations_layer() 868 layer = self._viewer.layers["annotations"] 869 ids = [np.unique(layer.data), [layer.selected_label]] 870 for idx, (_, labels, _) in (state.batch_training_data or {}).items(): 871 if idx != state.batch_index: 872 ids.append(np.unique(labels)) 873 rf = self._get_rf() 874 if rf is not None: 875 ids.append(np.asarray(rf.classes_)) 876 self._ensure_classes(np.unique(np.concatenate(ids))) 877 self._on_selected_label() 878 879 # 880 # Settings and train widgets. 881 # 882 883 def _create_train_widget(self): 884 # The 'Train and Predict' button is kept at the top level, outside the settings dropdown. 885 # A single 'Apply to Volume' checkbox governs both 'Train and Predict' and 'Clear Annotations' 886 # (shown only for 3d data, see '_update_image'): when checked they act on the whole volume, 887 # when unchecked (the default) only on the current slice. Tools that do not support it 888 # ('supports_apply_to_volume' False) omit the checkbox and always run over the full image/volume. 889 train_button = PushButton(text="Train and Predict [Shift + T]") 890 train_button.native.setToolTip(get_tooltip("classification", "train_button")) 891 clear_button = PushButton(text="Clear Annotations [Shift + C]") 892 clear_button.native.setToolTip(get_tooltip("classification", "clear_button")) 893 894 apply_to_volume = None 895 if self.supports_apply_to_volume: 896 apply_to_volume = CheckBox(value=False, text="Apply to Volume") 897 apply_to_volume.native.setToolTip(get_tooltip("classification", "apply_to_volume")) 898 899 def _volume_value(): 900 return True if apply_to_volume is None else apply_to_volume.value 901 902 train_button.clicked.connect(lambda: self._run_train_and_predict(_volume_value())) 903 clear_button.clicked.connect(lambda: self._clear_annotations(_volume_value())) 904 905 @self._viewer.bind_key("Shift-T", overwrite=True) 906 def _train_and_predict(event=None): 907 self._run_train_and_predict(_volume_value()) 908 909 @self._viewer.bind_key("Shift-C", overwrite=True) 910 def _clear(event=None): 911 self._clear_annotations(_volume_value()) 912 913 # napari's 'V' toggles only the selected layer, which is 'annotations' while painting. 914 def _toggle_visibility(name): 915 if name in self._viewer.layers: 916 layer = self._viewer.layers[name] 917 layer.visible = not layer.visible 918 919 @self._viewer.bind_key("Alt-A", overwrite=True) 920 def _toggle_annotations(event=None): 921 _toggle_visibility("annotations") 922 923 @self._viewer.bind_key("Alt-P", overwrite=True) 924 def _toggle_prediction(event=None): 925 _toggle_visibility("prediction") 926 927 # The two buttons sit side-by-side and expand to share the row width equally. QSizePolicy.Policy 928 # is nested in Qt6 and top-level in Qt5. 929 button_row = Container(layout="horizontal", widgets=[train_button, clear_button], labels=False) 930 button_row.native.layout().setContentsMargins(0, 0, 0, 0) 931 size_policy = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 932 for button in (train_button, clear_button): 933 button.native.setSizePolicy(size_policy.Expanding, size_policy.Fixed) 934 widgets_ = ([apply_to_volume] if apply_to_volume is not None else []) + [button_row] 935 container = Container(widgets=widgets_, labels=False) 936 return container, apply_to_volume 937 938 def _create_classifier_io_widget(self): 939 # Optional PCA dimensionality reduction. Off by default (all features used); checking it reveals 940 # a number box for the count of top PCA components to reduce the features to before training. 941 use_top_features = CheckBox(value=False, text="Choose top feature channels") 942 use_top_features.native.setToolTip(get_tooltip("classification", f"use_top_features_{self.tool_key}")) 943 944 # Optional AnyUp upsampling. When checked, the SAM/SAM2 embedding is upsampled with AnyUp using 945 # the original image as guidance instead of plain interpolation. Toggling it changes the 946 # features, so the cached features are cleared on change to force a recompute. 947 use_anyup = CheckBox(value=False, text="Upsample with AnyUp") 948 use_anyup.native.setToolTip(get_tooltip("classification", "use_anyup")) 949 950 checkbox_row = Container(layout="horizontal", widgets=[use_top_features, use_anyup], labels=False) 951 checkbox_row.native.layout().setContentsMargins(0, 0, 0, 0) 952 checkbox_row.native.layout().addStretch(1) 953 954 # Optional classical features, appended to the embedding features. Checking it reveals a 955 # dropdown to select the features. Both change the features, so they clear the cached ones. 956 use_classical = CheckBox(value=False, text="Add classical features") 957 use_classical.native.setToolTip(get_tooltip("classification", f"use_classical_features_{self.tool_key}")) 958 classical_tooltip = get_tooltip("classification", f"classical_features_{self.tool_key}") 959 classical_features = widgets.CheckableComboBox( 960 self.classical_feature_choices, labels=[name.replace("_", " ") for name in self.classical_feature_choices], 961 ) 962 classical_features.setToolTip(classical_tooltip) 963 size_policy = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 964 classical_features.setSizePolicy(size_policy.Expanding, size_policy.Fixed) 965 classical_features.setVisible(False) 966 classical_row = Container(layout="horizontal", widgets=[use_classical], labels=False) 967 classical_row.native.layout().addWidget(classical_features) 968 classical_row.native.layout().setContentsMargins(0, 0, 0, 0) 969 classical_row.native.layout().addStretch(1) 970 use_classical.changed.connect(lambda checked: classical_features.setVisible(checked)) 971 use_classical.changed.connect(self._invalidate_features) 972 classical_features.selection_changed.connect(self._invalidate_features) 973 974 top_features_tooltip = get_tooltip("classification", f"top_features_{self.tool_key}") 975 top_features = SpinBox(value=10, min=1, max=self.max_components, step=1) 976 top_features.native.setToolTip(top_features_tooltip) 977 self._top_features_spinbox = top_features 978 top_features_label = Label(value="top feature channels:") 979 top_features_label.native.setToolTip(top_features_tooltip) 980 top_features_row = Container( 981 layout="horizontal", widgets=[top_features_label, top_features], labels=False, 982 ) 983 top_features_row.native.layout().setContentsMargins(0, 0, 0, 0) 984 top_features_row.native.layout().addStretch(1) 985 top_features_row.visible = False 986 use_top_features.changed.connect(lambda checked: setattr(top_features_row, "visible", checked)) 987 use_anyup.changed.connect(self._invalidate_features) 988 989 # Random seed. 'fixed' trains the random forest with a fixed seed so the prediction is 990 # reproducible. 'random' leaves it unseeded so results vary slightly between runs. The exact 991 # seed value does not matter, so this is a simple two-way choice rather than a numeric field. 992 random_seed = ComboBox(value="fixed", choices=["fixed", "random"]) 993 random_seed_tooltip = get_tooltip("classification", "random_seed") 994 random_seed.native.setToolTip(random_seed_tooltip) 995 # Let the dropdown expand to fill the row width (no trailing stretch), matching the path widgets. 996 random_seed.native.setSizePolicy(size_policy.Expanding, size_policy.Fixed) 997 random_seed_label = Label(value="random seed:") 998 random_seed_label.native.setToolTip(random_seed_tooltip) 999 random_seed_row = Container( 1000 layout="horizontal", widgets=[random_seed_label, random_seed], labels=False, 1001 ) 1002 random_seed_row.native.layout().setContentsMargins(0, 0, 0, 0) 1003 1004 def get_n_components(): 1005 return int(top_features.value) if use_top_features.value else 0 1006 1007 def get_use_anyup(): 1008 return bool(use_anyup.value) 1009 1010 def get_classical_features(): 1011 # None switches the classical features off, also when the checkbox is on but nothing is selected. 1012 selected = classical_features.selected() 1013 return selected if use_classical.value and selected else None 1014 1015 def get_random_state(): 1016 return 0 if random_seed.value == "fixed" else None 1017 1018 def set_options( 1019 use_top_features_val, n_top_features, use_anyup_val, random_seed_val=None, classical_features_val=None 1020 ): 1021 # Restore the option controls from a loaded classifier's spec. 1022 use_top_features.value = bool(use_top_features_val) 1023 if n_top_features: 1024 top_features.value = int(n_top_features) 1025 use_anyup.value = bool(use_anyup_val) 1026 use_classical.value = classical_features_val is not None 1027 if classical_features_val is not None: 1028 classical_features.set_selected(classical_features_val) 1029 if random_seed_val is not None: 1030 random_seed.value = random_seed_val 1031 1032 self._get_n_components = get_n_components 1033 self._get_use_anyup = get_use_anyup 1034 self._get_classical_features = get_classical_features 1035 self._get_random_state = get_random_state 1036 self._set_options = set_options 1037 1038 # Classifier load and export. Load takes a stored model file. Export chooses a destination 1039 # folder (the current working directory by default) and saves the model there with an 1040 # auto-generated name. 1041 load_path = FileEdit(label="load classifier path:", mode="r", filter="*.joblib") 1042 load_path.line_edit.native.setPlaceholderText("/path/to/stored_model.joblib") 1043 load_path.native.setToolTip(get_tooltip("classification", "load_path")) 1044 load_button = PushButton(text="Load classifier") 1045 load_button.native.setToolTip(get_tooltip("classification", "load_button")) 1046 load_button.clicked.connect(lambda: self._load_rf(load_path.value)) 1047 1048 export_dir = FileEdit(label="export classifier folder:", mode="d", value=os.getcwd()) 1049 export_dir.native.setToolTip(get_tooltip("classification", "export_dir")) 1050 export_button = PushButton(text="Export classifier") 1051 export_button.native.setToolTip(get_tooltip("classification", "export_button")) 1052 export_button.clicked.connect(lambda: self._save_rf(export_dir.value)) 1053 1054 rows = [ 1055 checkbox_row, top_features_row, classical_row, random_seed_row, 1056 load_path, load_button, export_dir, export_button, 1057 ] 1058 return Container(widgets=rows, labels=False) 1059 1060 def _create_widgets(self): 1061 # Create the embedding widget and connect all events related to it. 1062 self._embedding_widget = widgets.ClassificationEmbeddingWidget() 1063 self._viewer.layers.events.inserted.connect(self._embedding_widget.image_selection.reset_choices) 1064 self._viewer.layers.events.removed.connect(self._embedding_widget.image_selection.reset_choices) 1065 self._embedding_widget.run_button.clicked.connect(self._update_image) 1066 1067 self._train_and_predict_widget, self._apply_to_volume = self._create_train_widget() 1068 if self._apply_to_volume is not None: 1069 self._apply_to_volume.visible = False 1070 self._classifier_io_widget = self._create_classifier_io_widget() 1071 1072 settings = QtWidgets.QWidget() 1073 settings.setLayout(QtWidgets.QVBoxLayout()) 1074 settings.layout().addWidget(self._classifier_io_widget.native) 1075 collapsible = widgets._make_collapsible( 1076 settings, title="Classification Settings", tooltip=get_tooltip("classification", "settings"), 1077 ) 1078 1079 # Any tool-specific sections (e.g. the object classifier's segmentation selector) sit above 1080 # the settings dropdown, with the train/predict button below it. 1081 classification_section = QtWidgets.QWidget() 1082 classification_section.setLayout(QtWidgets.QVBoxLayout()) 1083 for extra in self._extra_classification_sections(): 1084 if isinstance(extra, QtWidgets.QLayout): 1085 extra_container = QtWidgets.QWidget() 1086 extra_container.setLayout(extra) 1087 classification_section.layout().addWidget(extra_container) 1088 else: 1089 classification_section.layout().addWidget(extra) 1090 classification_section.layout().addWidget(collapsible) 1091 classification_section.layout().addWidget(self._train_and_predict_widget.native) 1092 1093 self._label_widget = self._create_label_widget() 1094 1095 self._widgets = { 1096 "embeddings": self._embedding_widget, 1097 "classification": classification_section, 1098 "label_widget": self._label_widget, 1099 } 1100 1101 def __init__(self, viewer: "napari.viewer.Viewer") -> None: 1102 """Create the classifier GUI. 1103 1104 Args: 1105 viewer: The napari viewer. 1106 """ 1107 super().__init__() 1108 self._viewer = viewer 1109 self._trained_annotations = None 1110 self._annotator_widget = QtWidgets.QWidget() 1111 self._annotator_widget.setLayout(QtWidgets.QVBoxLayout()) 1112 1113 # The classes of the class widget: class id -> {"name": str, "color": hex color}. 1114 self._classes = {} 1115 self._class_group = None 1116 self._connected_annotations = None 1117 1118 # Add the layers for annotations and prediction. Initialize with a dummy shape, which is reset 1119 # to the correct shape once an image is set. 1120 self._shape = (256, 256) 1121 self._ndim = len(self._shape) 1122 self._require_layers() 1123 1124 # Create all the widgets and add them to the layout. 1125 self._create_widgets() 1126 1127 for widget_name, widget in self._widgets.items(): 1128 widget_frame = QtWidgets.QGroupBox() 1129 widget_layout = QtWidgets.QVBoxLayout() 1130 if isinstance(widget, (Container, FunctionGui, Widget)): 1131 # This is a magicgui type and we need to get the native qt widget. 1132 widget_layout.addWidget(widget.native) 1133 elif isinstance(widget, QtWidgets.QLayout): 1134 widget_layout.addLayout(widget) 1135 else: 1136 # This is a qt type and we add the widget directly. 1137 widget_layout.addWidget(widget) 1138 widget_frame.setLayout(widget_layout) 1139 self._annotator_widget.layout().addWidget(widget_frame) 1140 1141 # Each container keeps the height of its contents. Without this the leftover space of the 1142 # dock is spread over the containers, which pulls their rows apart. 1143 self._annotator_widget.layout().addStretch() 1144 1145 # Connect the label layer and the refresh function. 1146 self._refresh_label_widget() 1147 1148 # Set the expected annotator class and widgets on the state. 1149 state = AnnotatorState() 1150 state.annotator = self 1151 state.widgets = self._widgets 1152 1153 self.setWidgetResizable(True) 1154 self.setWidget(self._annotator_widget) 1155 1156 # napari 0.9 caps the height of dock widget content at its size hint (napari/napari#9393). 1157 def showEvent(self, event): 1158 size_policy = self.sizePolicy() 1159 size_policy.setVerticalPolicy(QtWidgets.QSizePolicy.Policy.Expanding) 1160 self.setSizePolicy(size_policy) 1161 super().showEvent(event) 1162 1163 # 1164 # Train / predict / clear / load / save / spec. 1165 # 1166 1167 def _update_feature_cap(self, n_features): 1168 """Clamp the PCA top-features control to the actual embedding feature dimension.""" 1169 spinbox = getattr(self, "_top_features_spinbox", None) 1170 if spinbox is None: 1171 return 1172 spinbox.max = int(n_features) 1173 if spinbox.value > n_features: 1174 spinbox.value = int(n_features) 1175 1176 def _run_train_and_predict(self, apply_to_volume=True): 1177 state = AnnotatorState() 1178 self._require_layers() 1179 1180 features, aux = self._compute_features() 1181 if features is None: 1182 return None 1183 self._update_feature_cap(features.shape[1]) 1184 labels = self._compute_training_labels(aux) 1185 if labels is None: 1186 return None 1187 1188 # The batch data of the other images; the current image always contributes its live annotations. 1189 previous_features, previous_labels = self.batch_training_set(exclude_index=state.batch_index) 1190 if (labels == 0).all() and (previous_labels is None): 1191 return widgets._generate_message("error", "You have not provided any annotations.") 1192 if previous_features is not None and previous_features.shape[1] != features.shape[1]: 1193 return widgets._generate_message( 1194 "error", "The features of the previous images do not match the current feature settings." 1195 ) 1196 1197 n_components = self._get_n_components() 1198 random_state = self._get_random_state() 1199 rf = self._train(features, labels, previous_features, previous_labels, n_components, random_state) 1200 self._set_rf(rf) 1201 self._trained_annotations = (self._viewer.layers["annotations"].data.copy(), self._training_settings()) 1202 1203 self._predict_and_show(rf, features, aux, apply_to_volume=apply_to_volume) 1204 1205 def _predict_and_show(self, rf, features, aux, apply_to_volume=True): 1206 try: 1207 pred = rf.predict(features) 1208 except ValueError: 1209 return widgets._generate_message( 1210 "error", "The loaded classifier does not match the current embeddings. Use the same model type." 1211 ) 1212 prediction = self._project_prediction(pred, aux) 1213 if prediction is None: 1214 return None 1215 layer = self._viewer.layers["prediction"] 1216 if apply_to_volume or prediction.ndim < 3: 1217 layer.data = prediction 1218 else: 1219 data = layer.data if layer.data.shape == prediction.shape else np.zeros_like(prediction) 1220 z = self._current_slice() 1221 data[z] = prediction[z] 1222 layer.data = data 1223 # Each predicted class gets a class row, e.g. a class whose annotations were restored with napari's redo. 1224 self._ensure_classes(rf.classes_) 1225 1226 def _clear_annotations(self, apply_to_volume=True): 1227 # Remove the annotation scribbles and the prediction: the whole volume, or only the current 1228 # slice for 3d data when 'apply_to_volume' is False. 1229 if "annotations" not in self._viewer.layers: 1230 return widgets._generate_message("error", "There is no annotations layer to clear.") 1231 whole = apply_to_volume or self._viewer.layers["annotations"].data.ndim < 3 1232 for name in ("annotations", "prediction"): 1233 if name not in self._viewer.layers: 1234 continue 1235 layer = self._viewer.layers[name] 1236 if whole: 1237 layer.data = np.zeros_like(layer.data) 1238 else: 1239 data = layer.data 1240 data[self._current_slice()] = 0 1241 layer.data = data 1242 layer.refresh() 1243 1244 def _load_rf(self, model_path): 1245 # An empty path field resolves to the current directory, so we check for an actual file here. 1246 model_path = str(model_path).strip() 1247 if not model_path or not os.path.isfile(model_path): 1248 return show_warning("There are no classifier weights to load from. Please select a '.joblib' file.") 1249 1250 # Stored as {'rf': ..., 'model_spec': ...}; older files are a bare classifier (no spec). 1251 obj = load(model_path) 1252 if isinstance(obj, dict) and "rf" in obj: 1253 rf, spec = obj["rf"], obj.get("model_spec", {}) 1254 else: 1255 rf, spec = obj, {} 1256 self._set_rf(rf) 1257 # A loaded classifier can contain classes that have no annotations in this session. 1258 self._ensure_classes(rf.classes_) 1259 if spec: 1260 self._restore_from_spec(spec) 1261 1262 # Predict on the current image if embeddings are available. 1263 features, aux = self._compute_features() 1264 if features is None: 1265 return None 1266 self._require_layers() 1267 self._predict_and_show(rf, features, aux) 1268 1269 def _resolve_export_path(self, export_dir, rf): 1270 # Auto-generated name: <image>_<nclasses>classes_<date>_<time>_<hash>.joblib in the chosen folder. 1271 state = AnnotatorState() 1272 name = state.image_name or (self._viewer.layers["image"].name if "image" in self._viewer.layers else "image") 1273 name = os.path.splitext(os.path.basename(str(name)))[0] 1274 n_classes = len(rf.classes_) 1275 stamp = datetime.now().strftime("%Y%m%d_%H%M%S") 1276 fname = f"{name}_{n_classes}classes_{stamp}_{joblib_hash(rf)[:8]}.joblib" 1277 base_dir = str(export_dir).strip() or os.getcwd() 1278 return os.path.join(base_dir, fname) 1279 1280 def _save_rf(self, export_dir): 1281 rf = self._get_rf() 1282 if rf is None: 1283 return widgets._generate_message("error", "You have not trained or loaded a classifier yet.") 1284 out_path = self._resolve_export_path(export_dir, rf) 1285 os.makedirs(os.path.dirname(out_path), exist_ok=True) 1286 # Store the classifier together with its specs, so a load can restore the full config. 1287 dump({"rf": rf, "model_spec": self._classifier_spec(rf)}, out_path) 1288 show_info(f"Exported classifier to {out_path}") 1289 1290 def _gather_class_names(self, rf): 1291 # User-provided class names keyed by class id, for the classes the classifier knows. None if none. 1292 class_names = {i: c["name"] for i, c in self._classes.items() if c["name"] and i in rf.classes_} 1293 return class_names or None 1294 1295 def _classifier_spec(self, rf): 1296 # Specs stored alongside the classifier so a load can restore the full config. 1297 state = AnnotatorState() 1298 ew = state.widgets.get("embeddings") 1299 tiling_on = getattr(ew, "tiling", "no") == "yes" 1300 n_components = self._get_n_components() 1301 use_anyup = bool(self._get_use_anyup()) 1302 classical_features = self._get_classical_features() 1303 random_seed = "random" if self._get_random_state() is None else "fixed" 1304 # The GUI sets 'ew.model_type' only after it computes embeddings. Use the predictor's 1305 # model_type (always set) instead, so a CLI-launched session still records the model. 1306 model_type = getattr(ew, "model_type", None) or getattr(state.predictor, "model_type", None) 1307 return { 1308 "micro_sam_version": micro_sam_version, 1309 "model_family": getattr(ew, "model_family", None), 1310 "model_size": getattr(ew, "model_size", None), 1311 "model_type": model_type, 1312 "custom_weights": getattr(ew, "custom_weights", None) or None, 1313 "tiling": getattr(ew, "tiling", "no"), 1314 "tile_shape": [ew.tile_x, ew.tile_y] if tiling_on else None, 1315 "halo": [ew.halo_x, ew.halo_y] if tiling_on else None, 1316 "use_top_features": n_components > 0, 1317 "n_top_features": n_components if n_components > 0 else None, 1318 "upsampling": "anyup" if use_anyup else "interpolation", 1319 "classical_features": classical_features, 1320 "random_seed": random_seed, 1321 "ndim": getattr(self, "_ndim", None), 1322 "class_ids": [int(c) for c in rf.classes_], 1323 "class_names": self._gather_class_names(rf), 1324 } 1325 1326 def _restore_from_spec(self, spec): 1327 # Push a loaded classifier's stored specs back into the widgets, so the session matches the 1328 # config the classifier was trained with. Warn (but don't recompute) if the current embeddings 1329 # were computed with a different model. 1330 state = AnnotatorState() 1331 ew = state.widgets.get("embeddings") 1332 1333 # Model family / size are set directly from the stored strings (the classifier widget's family 1334 # names don't match '_sync_embedding_widget's model_type -> family inference). Family first, since 1335 # the size options are rebuilt when it changes. 1336 family, size = spec.get("model_family"), spec.get("model_size") 1337 if ew is not None and family is not None: 1338 # The classification widget routes the family to the primary or advanced selector. Other 1339 # widgets set the family dropdown directly. 1340 setter = getattr(ew, "set_model_family_size", None) 1341 if setter is not None: 1342 setter(family, size) 1343 else: 1344 ew.model_family_dropdown.setCurrentText(family) 1345 if size is not None: 1346 ew.model_size_dropdown.setCurrentText(size) 1347 1348 # Tiling, tile and halo params and custom weights via the shared sync helper (these field names match). 1349 # 'ew.model_type' can be unset until the GUI computes embeddings, so read it via getattr. 1350 if ew is not None: 1351 vutil._sync_embedding_widget( 1352 ew, model_type=spec.get("model_type") or getattr(ew, "model_type", None), 1353 save_path=None, checkpoint_path=spec.get("custom_weights"), 1354 device=None, tile_shape=spec.get("tile_shape"), halo=spec.get("halo"), 1355 ) 1356 1357 # Top-feature selection, AnyUp/interpolation upsampling, the random-seed mode and the classical features. 1358 self._set_options( 1359 spec.get("use_top_features", False), spec.get("n_top_features"), 1360 spec.get("upsampling") == "anyup", spec.get("random_seed"), spec.get("classical_features"), 1361 ) 1362 1363 # Class names, restored into the class widget. 1364 for class_id, name in (spec.get("class_names") or {}).items(): 1365 self._ensure_classes([int(class_id)]) 1366 self._set_class_name(int(class_id), name) 1367 1368 # Warn if the current embeddings were computed with a different model than the classifier expects. 1369 stored_model = spec.get("model_type") 1370 current_model = getattr(state.predictor, "model_type", None) if state.predictor is not None else None 1371 if stored_model is not None and current_model is not None and stored_model != current_model: 1372 show_info( 1373 f"The loaded classifier was trained with '{stored_model}', but the current embeddings use " 1374 f"'{current_model}'. Recompute the embeddings with the restored settings before predicting." 1375 )
PLACEHOLDER_SHAPE =
{2: (256, 256), 3: (16, 256, 256)}