micro_sam.sam_annotator._widgets
Implements the widgets used in the annotation plugins.
1"""Implements the widgets used in the annotation plugins.""" 2 3import gc 4import os 5import json 6import hashlib 7from pathlib import Path 8from typing import Optional 9import multiprocessing as mp 10 11import z5py 12import numpy as np 13 14import napari 15# We have disabled the thread workers for now because they result in a 16# massive slowdown in napari >= 0.5. 17# See also https://forum.image.sc/t/napari-thread-worker-leads-to-massive-slowdown/103786 18# from napari.qt.threading import thread_worker 19from napari.utils import progress 20from napari.utils.notifications import show_info 21 22from qtpy import QtWidgets 23from qtpy.QtCore import QObject, Signal, Qt 24from qtpy.QtGui import QStandardItem, QStandardItemModel 25 26from magicgui import magic_factory 27from magicgui.widgets import ComboBox, Container, create_widget 28 29from superqt import QCollapsible, QLabeledRangeSlider 30 31import elf.parallel 32 33from bioimage_cpp.utils import segmentation_overlap 34 35from .. import util 36from . import util as vutil 37from ._state import AnnotatorState 38from ._tooltips import get_tooltip 39from ..v1.multi_dimensional_segmentation import ( 40 export_tracking_result_to_ctc, 41 export_tracking_result_to_geff, 42 export_tracking_result_to_trackmate_xml, 43 get_napari_track_data, 44 track_across_frames, 45) 46 47# 48# Convenience functionality for creating QT UI and manipulating the napari viewer. 49# 50 51 52def _select_layer(viewer, layer_name): 53 viewer.layers.selection.select_only(viewer.layers[layer_name]) 54 55 56# Create a collapsible around the widget 57def _make_collapsible(widget, title, tooltip=None): 58 parent_widget = QtWidgets.QWidget() 59 parent_widget.setLayout(QtWidgets.QVBoxLayout()) 60 collapsible = QCollapsible(title, parent_widget) 61 if tooltip: 62 collapsible.setToolTip(tooltip) 63 # Also set it on the header toggle button, since that is what the user hovers (Qt does not 64 # fall back to the parent's tooltip for child widgets). 65 toggle_btn = getattr(collapsible, "_toggle_btn", None) 66 if toggle_btn is not None: 67 toggle_btn.setToolTip(tooltip) 68 collapsible.addWidget(widget) 69 parent_widget.layout().addWidget(collapsible) 70 return parent_widget 71 72 73class CheckableComboBox(QtWidgets.QComboBox): 74 """A dropdown with a checkbox per item, to select several items at once. 75 76 Args: 77 items: The item names. 78 labels: Optional display text per item. By default the item names are shown. 79 parent: The parent widget. 80 """ 81 selection_changed = Signal() 82 83 def __init__(self, items, labels=None, parent=None): 84 super().__init__(parent) 85 self._items = list(items) 86 labels = self._items if labels is None else list(labels) 87 self._model = QStandardItemModel(self) 88 for label in labels: 89 item = QStandardItem(label) 90 # The click handler toggles the state, so the item itself is not user-checkable. 91 item.setFlags(Qt.ItemIsEnabled) 92 item.setData(Qt.Checked, Qt.CheckStateRole) 93 self._model.appendRow(item) 94 self.setModel(self._model) 95 self.view().pressed.connect(self._toggle) 96 self._keep_open = False 97 # The closed box only shows a short summary, so the long item names must not widen the panel. 98 self.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) 99 self.setMinimumContentsLength(12) 100 self.view().setMinimumWidth(self.view().sizeHintForColumn(0) + 40) 101 102 def _toggle(self, index): 103 item = self._model.itemFromIndex(index) 104 checked = item.data(Qt.CheckStateRole) == Qt.Checked 105 item.setData(Qt.Unchecked if checked else Qt.Checked, Qt.CheckStateRole) 106 self._keep_open = True 107 self.update() 108 self.selection_changed.emit() 109 110 def hidePopup(self): 111 # Keep the popup open while the user toggles items. 112 if self._keep_open: 113 self._keep_open = False 114 return 115 super().hidePopup() 116 117 def selected(self): 118 """Return the names of the checked items.""" 119 return [ 120 name for row, name in enumerate(self._items) 121 if self._model.item(row).data(Qt.CheckStateRole) == Qt.Checked 122 ] 123 124 def set_selected(self, names): 125 """Check exactly the items in `names`.""" 126 for row, name in enumerate(self._items): 127 self._model.item(row).setData(Qt.Checked if name in names else Qt.Unchecked, Qt.CheckStateRole) 128 self.update() 129 self.selection_changed.emit() 130 131 def paintEvent(self, event): 132 # Show a summary of the selection instead of the current item. 133 n_selected = len(self.selected()) 134 if n_selected == len(self._items): 135 text = "all features" 136 elif n_selected == 0: 137 text = "no features" 138 else: 139 text = f"{n_selected} of {len(self._items)} features" 140 painter = QtWidgets.QStylePainter(self) 141 option = QtWidgets.QStyleOptionComboBox() 142 self.initStyleOption(option) 143 option.currentText = text 144 painter.drawComplexControl(QtWidgets.QStyle.CC_ComboBox, option) 145 painter.drawControl(QtWidgets.QStyle.CE_ComboBoxLabel, option) 146 147 148# Base class for a widget with convenience functionality for adding parameters. 149class _WidgetBase(QtWidgets.QWidget): 150 def __init__(self, parent=None): 151 super().__init__(parent) 152 self.setLayout(QtWidgets.QVBoxLayout()) 153 154 def _add_boolean_param(self, name, value, title=None, tooltip=None): 155 checkbox = QtWidgets.QCheckBox(name if title is None else title) 156 checkbox.setChecked(value) 157 checkbox.stateChanged.connect(lambda val: setattr(self, name, val)) 158 if tooltip: 159 checkbox.setToolTip(tooltip) 160 return checkbox 161 162 def _update_batched_visibility(self): 163 """Hide the 'Batched' checkbox while embeddings are tiled (batched prompting is unsupported 164 with tiling). No-op for widgets without a batched checkbox.""" 165 checkbox = getattr(self, "batched_checkbox", None) 166 if checkbox is None: 167 return 168 is_tiled = _embeddings_are_tiled(AnnotatorState()) 169 if is_tiled and getattr(self, "batched", False): 170 checkbox.setChecked(False) # reset to single-object (also updates 'self.batched') 171 checkbox.setVisible(not is_tiled) 172 173 def _add_string_param( 174 self, 175 name, 176 value, 177 title=None, 178 placeholder=None, 179 layout=None, 180 tooltip=None, 181 ): 182 if layout is None: 183 layout = QtWidgets.QHBoxLayout() 184 label = QtWidgets.QLabel(title or name) 185 if tooltip: 186 label.setToolTip(tooltip) 187 layout.addWidget(label) 188 param = QtWidgets.QLineEdit() 189 param.setText("" if value is None else str(value)) 190 if placeholder is not None: 191 param.setPlaceholderText(placeholder) 192 param.textChanged.connect(lambda val: setattr(self, name, val)) 193 if tooltip: 194 param.setToolTip(tooltip) 195 layout.addWidget(param) 196 return param, layout 197 198 def _add_float_param( 199 self, 200 name, 201 value, 202 title=None, 203 min_val=0.0, 204 max_val=1.0, 205 decimals=2, 206 step=0.01, 207 layout=None, 208 tooltip=None, 209 ): 210 if layout is None: 211 layout = QtWidgets.QHBoxLayout() 212 label = QtWidgets.QLabel(title or name) 213 if tooltip: 214 label.setToolTip(tooltip) 215 layout.addWidget(label) 216 param = QtWidgets.QDoubleSpinBox() 217 param.setRange(min_val, max_val) 218 param.setDecimals(decimals) 219 param.setValue(value) 220 param.setSingleStep(step) 221 param.valueChanged.connect(lambda val: setattr(self, name, val)) 222 if tooltip: 223 param.setToolTip(tooltip) 224 layout.addWidget(param) 225 return param, layout 226 227 def _add_int_param( 228 self, 229 name, 230 value, 231 min_val, 232 max_val, 233 title=None, 234 step=1, 235 layout=None, 236 tooltip=None, 237 ): 238 if layout is None: 239 layout = QtWidgets.QHBoxLayout() 240 label = QtWidgets.QLabel(title or name) 241 if tooltip: 242 label.setToolTip(tooltip) 243 layout.addWidget(label) 244 param = QtWidgets.QSpinBox() 245 param.setRange(min_val, max_val) 246 param.setValue(value) 247 param.setSingleStep(step) 248 param.valueChanged.connect(lambda val: setattr(self, name, val)) 249 if tooltip: 250 param.setToolTip(tooltip) 251 layout.addWidget(param) 252 return param, layout 253 254 def _make_int_field(self, name, value, min_val, max_val, step=1, title=None, tooltip=None): 255 # A single labeled int spinbox wrapped in its own widget, so it can be placed inside a row 256 # next to other fields and shown / hidden independently (e.g. the z fields, which only apply 257 # to 3d data). Returns the spinbox and the wrapping widget. 258 field = QtWidgets.QWidget() 259 field_layout = QtWidgets.QVBoxLayout() 260 field_layout.setContentsMargins(0, 0, 0, 0) 261 param, _ = self._add_int_param( 262 name, value, min_val=min_val, max_val=max_val, step=step, 263 layout=field_layout, title=title, tooltip=tooltip, 264 ) 265 field.setLayout(field_layout) 266 return param, field 267 268 def _add_choice_param( 269 self, 270 name, 271 value, 272 options, 273 title=None, 274 layout=None, 275 update=None, 276 tooltip=None, 277 ): 278 if layout is None: 279 layout = QtWidgets.QHBoxLayout() 280 label = QtWidgets.QLabel(title or name) 281 if tooltip: 282 label.setToolTip(tooltip) 283 layout.addWidget(label) 284 285 # Create the dropdown menu via QComboBox, set the available values. 286 dropdown = QtWidgets.QComboBox() 287 dropdown.addItems(options) 288 if update is None: 289 # Read the label off the live dropdown rather than the list captured here: the items are 290 # swapped later (the model sizes depend on the family), which makes that list stale. 291 def bind_selection(index, box=dropdown, attribute=name): 292 if index >= 0: 293 setattr(self, attribute, box.itemText(index)) 294 295 dropdown.currentIndexChanged.connect(bind_selection) 296 else: 297 dropdown.currentIndexChanged.connect(update) 298 299 # Set the correct value for the value. 300 dropdown.setCurrentIndex(dropdown.findText(value)) 301 302 if tooltip: 303 dropdown.setToolTip(tooltip) 304 305 layout.addWidget(dropdown) 306 return dropdown, layout 307 308 def _add_shape_param( 309 self, names, values, min_val, max_val, step=1, title=None, tooltip=None 310 ): 311 layout = QtWidgets.QHBoxLayout() 312 313 x_layout = QtWidgets.QVBoxLayout() 314 x_param, _ = self._add_int_param( 315 names[0], 316 values[0], 317 min_val=min_val, 318 max_val=max_val, 319 layout=x_layout, 320 step=step, 321 title=title[0] if title is not None else title, 322 tooltip=tooltip, 323 ) 324 layout.addLayout(x_layout) 325 326 y_layout = QtWidgets.QVBoxLayout() 327 y_param, _ = self._add_int_param( 328 names[1], 329 values[1], 330 min_val=min_val, 331 max_val=max_val, 332 layout=y_layout, 333 step=step, 334 title=title[1] if title is not None else title, 335 tooltip=tooltip, 336 ) 337 layout.addLayout(y_layout) 338 339 return x_param, y_param, layout 340 341 def _add_path_param( 342 self, 343 name, 344 value, 345 select_type, 346 title=None, 347 placeholder=None, 348 tooltip=None, 349 ): 350 assert select_type in ("directory", "file", "both") 351 352 layout = QtWidgets.QHBoxLayout() 353 label = QtWidgets.QLabel(title or name) 354 if tooltip: 355 label.setToolTip(tooltip) 356 layout.addWidget(label) 357 358 path_textbox = QtWidgets.QLineEdit() 359 path_textbox.setText("" if value is None else str(value)) 360 if placeholder is not None: 361 path_textbox.setPlaceholderText(placeholder) 362 363 # An empty path means that no optional path was selected. Keep this as ``None`` in the 364 # widget state instead of an empty (or whitespace-only) string: downstream model loading 365 # distinguishes ``None`` (use the registered model) from a custom checkpoint path. 366 path_textbox.textChanged.connect( 367 lambda val: setattr(self, name, val if val.strip() else None) 368 ) 369 if tooltip: 370 path_textbox.setToolTip(tooltip) 371 372 layout.addWidget(path_textbox) 373 374 def add_path_button(select_type, tooltip=None): 375 # Adjust button text. 376 button_text = f"Select {select_type.capitalize()}" 377 path_button = QtWidgets.QPushButton(button_text) 378 379 # Call appropriate function based on select_type. 380 path_button.clicked.connect( 381 lambda: getattr(self, f"_get_{select_type}_path")( 382 name, path_textbox 383 ) 384 ) 385 if tooltip: 386 path_button.setToolTip(tooltip) 387 layout.addWidget(path_button) 388 389 if select_type == "both": 390 add_path_button("file") 391 add_path_button("directory") 392 393 else: 394 add_path_button(select_type) 395 396 return path_textbox, layout 397 398 def _get_directory_path(self, name, textbox, tooltip=None): 399 directory = QtWidgets.QFileDialog.getExistingDirectory( 400 self, "Select Directory", "", QtWidgets.QFileDialog.ShowDirsOnly 401 ) 402 if tooltip: 403 directory.setToolTip(tooltip) 404 if directory and Path(directory).is_dir(): 405 textbox.setText(str(directory)) 406 else: 407 # Handle the case where the selected path is not a directory 408 print("Invalid directory selected. Please try again.") 409 410 def _get_file_path(self, name, textbox, tooltip=None): 411 file_path, _ = QtWidgets.QFileDialog.getOpenFileName( 412 self, "Select File", "", "All Files (*)" 413 ) 414 if tooltip: 415 file_path.setToolTip(tooltip) 416 if file_path and Path(file_path).is_file(): 417 textbox.setText(str(file_path)) 418 else: 419 # Handle the case where the selected path is not a file 420 print("Invalid file selected. Please try again.") 421 422 def _align_widths(self, widgets): 423 # Give a set of widgets a uniform (max) fixed width so rows line up symmetrically. 424 widgets = [w for w in widgets if w is not None] 425 if not widgets: 426 return 427 width = max(w.sizeHint().width() for w in widgets) 428 for w in widgets: 429 w.setFixedWidth(width) 430 431 def _get_model_size_options(self): 432 # The available model sizes depend on the selected family: the base SAM2 family supports all 433 # sizes, while finetuned families can be available only for specific sizes (e.g. 'Microscopy' 434 # is an 'hvit_t' model). We store the UI labels mapped to the corresponding model names. 435 sizes = self.model_family_config[self.model_family]["sizes"] 436 self.model_size_options = [self._model_size_map[k] for k in sizes] 437 self.model_size_mapping = {self._model_size_map[k]: f"hvit_{k}" for k in sizes} 438 439 # We ensure an assorted order of model sizes ('tiny' to 'large'). 440 self.model_size_options.sort( 441 key=lambda x: ["tiny", "small", "base", "large"].index(x) 442 ) 443 444 def _update_model_type(self): 445 # Sync the selected family. Both the available sizes and the model-type suffix depend on it. 446 self.model_family = self.model_family_dropdown.currentText() or self.model_family 447 448 # Get currently selected model size (before clearing dropdown) 449 current_selection = self.model_size_dropdown.currentText() 450 self._get_model_size_options() # Update model size options dynamically 451 452 # NOTE: We need to prevent recursive updates for this step temporarily. 453 self.model_size_dropdown.blockSignals(True) 454 455 # Let's clear and recreate the dropdown. 456 self.model_size_dropdown.clear() 457 self.model_size_dropdown.addItems(self.model_size_options) 458 459 # We restore the previous selection, if still valid. 460 if current_selection in self.model_size_options: 461 self.model_size = current_selection 462 else: 463 if ( 464 self.model_size_options 465 ): # Default to the first available model size 466 self.model_size = self.model_size_options[0] 467 468 # Let's map the selection to the correct model type (eg. "tiny" -> "hvit_t"). 469 size_key = next( 470 ( 471 k 472 for k, v in self._model_size_map.items() 473 if v == self.model_size 474 ), 475 "t", 476 ) 477 # Append the family suffix (e.g. 'tiny' + 'Microscopy' -> 'hvit_t_cells'; base -> 'hvit_t'). 478 suffix = self.model_family_config[self.model_family]["suffix"] 479 self.model_type = f"hvit_{size_key}{suffix}" 480 481 self.model_size_dropdown.setCurrentText( 482 self.model_size 483 ) # Apply the selected text to the dropdown 484 485 # We force a refresh for UI here. 486 self.model_size_dropdown.update() 487 488 # NOTE: And finally, we should re-enable signals again. 489 self.model_size_dropdown.blockSignals(False) 490 491 # The batch size depends on the backend and its VRAM cost, so it follows the model selection. 492 if getattr(self, "_batch_size_widget", None) is not None: 493 self._refresh_batch_size() 494 495 def _create_model_section( 496 self, 497 default_model: Optional[str] = None, 498 create_layout: bool = True, 499 ): 500 # The widget encodes its default as the synthetic 'vit_<size><suffix>' selector string. For 501 # SAM2 model ids ('hvit_...') this is just the id without the leading 'h', so we derive it 502 # from the single-source 'DEFAULT_MODEL' (e.g. 'hvit_t_cells' -> 'vit_t_cells' -> Microscopy/tiny). 503 if default_model is None: 504 from ..v2.util import DEFAULT_MODEL 505 default_model = DEFAULT_MODEL[1:] 506 507 # Create a list of supported dropdown values and correspond them to suffixes (used to parse 508 # the synthetic default-model string). Additional SAM2 families can be added here in future. 509 self.supported_dropdown_maps = { 510 "Natural Images": "_sam2", 511 "Microscopy": "_cells", 512 "Mitochondria (EM)": "_em_mito", 513 "Nuclei (EM)": "_em_nuclei", 514 } 515 516 # Per-family backend config: the model-type suffix appended after 'hvit_{size}' and the 517 # available model sizes. The base SAM2 family supports all sizes. Finetuned families (e.g. 518 # 'Microscopy', the joint SAM2 + UniSAM2 'hvit_*_cells' models) can exist only for some sizes. 519 self.model_family_config = { 520 "Natural Images": {"suffix": "", "sizes": ["t", "s", "b", "l"]}, 521 "Microscopy": {"suffix": "_cells", "sizes": ["t", "s", "b", "l"]}, 522 "Mitochondria (EM)": {"suffix": "_em_mito", "sizes": ["s"]}, 523 "Nuclei (EM)": {"suffix": "_em_nuclei", "sizes": ["s"]}, 524 } 525 526 # NOTE: The available SAM2 model sizes are 'tiny', 'small', 'base' and 'large'. 527 self._model_size_map = { 528 "t": "tiny", 529 "s": "small", 530 "b": "base", 531 "l": "large", 532 } 533 534 self._default_model_choice = default_model 535 # Let's set the literally default model choice depending on 'micro-sam'. 536 self.model_family = { 537 v: k for k, v in self.supported_dropdown_maps.items() 538 }[self._default_model_choice[5:]] 539 540 kwargs = {} 541 if create_layout: 542 layout = QtWidgets.QVBoxLayout() 543 kwargs["layout"] = layout 544 545 # NOTE: We stick to the base variant for each model family. 546 # i.e. 'Natural Images (SAM)', 'Light Microscopy', 'Electron Microscopy', 'Medical_Imaging', 'Histopathology'. 547 self.model_family_dropdown, layout = self._add_choice_param( 548 "model_family", 549 self.model_family, 550 list(self.supported_dropdown_maps.keys()), 551 title="Model:", 552 tooltip=get_tooltip("embedding", "model_family"), 553 **kwargs, 554 ) 555 self.model_family_dropdown.currentTextChanged.connect( 556 self._update_model_type 557 ) 558 return layout 559 560 def _create_model_size_section(self): 561 562 # Create UI for the model size. 563 # This combines with the chosen 'self.model_family' and depends on 'self._default_model_choice'. 564 self.model_size = self._model_size_map[self._default_model_choice[4]] 565 566 # Now, we get the available sizes per model family. 567 self._get_model_size_options() 568 569 # Resolve the type for the shown default now. The dropdowns only sync it on a change, and 570 # '_validate_model_type_and_custom_weights' not until the run button, so it would be unset. 571 self.model_type = self._resolve_model_type() 572 573 self.model_size_dropdown, layout = self._add_choice_param( 574 "model_size", 575 self.model_size, 576 self.model_size_options, 577 title="model size:", 578 tooltip=get_tooltip("embedding", "model_size"), 579 ) 580 self.model_size_dropdown.currentTextChanged.connect( 581 self._update_model_type 582 ) 583 return layout 584 585 def _family_for_sam2_model(self, model_type): 586 """The family of a SAM2 model name by its suffix, e.g. 'hvit_s_em_mito' -> 'Mitochondria (EM)'.""" 587 for family, config in self.model_family_config.items(): 588 if config["suffix"] and model_type.endswith(config["suffix"]): 589 return family 590 return "Natural Images" 591 592 def _resolve_model_type(self): 593 """The model type for the selected family and size, e.g. 'tiny' + 'Microscopy' -> 'hvit_t_cells'.""" 594 suffix = self.model_family_config.get(self.model_family, {}).get("suffix", "") 595 return f"hvit_{self.model_size[0]}{suffix}" 596 597 def _validate_model_type_and_custom_weights(self): 598 self.model_type = self._resolve_model_type() 599 600 # For 'custom_weights', we remove the displayed text on top of the drop-down menu. 601 if self.custom_weights: 602 # NOTE: We prevent recursive updates for this step temporarily. 603 self.model_family_dropdown.blockSignals(True) 604 self.model_family_dropdown.setCurrentIndex( 605 -1 606 ) # This removes the displayed text. 607 self.model_family_dropdown.update() 608 # NOTE: And re-enable signals again. 609 self.model_family_dropdown.blockSignals(False) 610 611 def _validate_model_support(self): 612 # The segmentation and tracking annotators support only SAM2. The classification widget overrides this. 613 if not self.model_type.startswith("hvit_"): 614 tool = "tracking" if getattr(self, "is_timeseries", False) else "segmentation" 615 return _generate_message( 616 "error", 617 f"The {tool} annotator does not support the model '{self.model_type}'. " 618 "Use a (µ)SAM2 model ('hvit_*').", 619 ) 620 return False 621 622 def _validate_vfm_requirements(self): 623 # For gated VFM models (DINOv3 via 'transformers', UNI / UNI2-h via 'timm') check that the backend 624 # package is importable and HuggingFace access is set up, surfacing a clear message if not. DINOv2 625 # ('torch_hub') is ungated and auto-downloads, so it is not checked. A no-op for SAM models. 626 import importlib 627 from ..models.vfm import is_vfm_model, VFM_MODELS 628 629 if not is_vfm_model(self.model_type): 630 return False 631 632 backend = VFM_MODELS[self.model_type]["backend"] 633 if backend == "torch_hub": # DINOv2: ungated, weights auto-download. 634 return False 635 636 package = "transformers" if backend == "hf" else "timm" 637 try: 638 importlib.import_module(package) 639 except ImportError: 640 return _generate_message( 641 "error", 642 f"The model '{self.model_type}' requires the '{package}' package, which is not installed. " 643 f"Install it (e.g. 'pip install {package}') and try again." 644 ) 645 646 # These weights are gated on HuggingFace. Warn (but allow continuing, e.g. if already cached). 647 try: 648 from huggingface_hub import get_token 649 has_token = get_token() is not None 650 except Exception: 651 has_token = False 652 if not has_token: 653 return _generate_message( 654 "info", 655 f"'{self.model_type}' is a gated model on Hugging Face. Request access on its Hugging Face " 656 "page and authenticate via 'huggingface-cli login' or the 'HF_TOKEN' environment variable. " 657 "If the weights are already downloaded you can continue. Otherwise the download will fail." 658 ) 659 return False 660 661 662# Custom signals for managing progress updates. 663class PBarSignals(QObject): 664 pbar_total = Signal(int) 665 pbar_update = Signal(int) 666 pbar_description = Signal(str) 667 pbar_stop = Signal() 668 pbar_reset = Signal() 669 670 671class InfoDialog(QtWidgets.QDialog): 672 def __init__(self, title, message, buttons=("OK", "Cancel")): 673 super().__init__() 674 self.setWindowTitle(title) 675 # Label of the button the user clicked (None if the dialog was closed without a button). 676 self.clicked_label = None 677 # The first button accepts the dialog. The rest reject it. 678 self._accept_label = buttons[0] 679 680 layout = QtWidgets.QVBoxLayout() 681 layout.addWidget(QtWidgets.QLabel(message)) 682 683 # The buttons sit side by side. The first is the default, so Enter triggers it. 684 button_box = QtWidgets.QHBoxLayout() 685 for i, label in enumerate(buttons): 686 button = QtWidgets.QPushButton(label) 687 button.clicked.connect(lambda checked=False, lbl=label: self.button_clicked(lbl)) 688 if i == 0: 689 button.setDefault(True) 690 button.setFocus() 691 button_box.addWidget(button) 692 693 layout.addLayout(button_box) 694 self.setLayout(layout) 695 696 def button_clicked(self, label): 697 self.clicked_label = label 698 if label == self._accept_label: 699 self.accept() 700 else: 701 self.reject() 702 703 704# Set up the progress bar. We handle this via custom signals that are passed as callbacks to the 705# function that does the actual work. We need callbacks for initializing the progress bar, 706# updating it and for stopping the progress bar. 707def _create_pbar_for_threadworker(initial_description=None): 708 """Create a napari progress bar, optionally visible in an indeterminate preparation state. 709 710 Supplying the description at construction time ensures napari can paint meaningful status before 711 a synchronous caller reaches the backend callback that provides the final work-item count. 712 """ 713 pbar = progress(desc=initial_description) 714 pbar_signals = PBarSignals() 715 pbar_signals.pbar_total.connect( 716 lambda total: setattr(pbar, "total", total) 717 ) 718 pbar_signals.pbar_update.connect(lambda update: pbar.update(update)) 719 pbar_signals.pbar_description.connect( 720 lambda description: pbar.set_description(description) 721 ) 722 pbar_signals.pbar_stop.connect(lambda: pbar.close()) 723 pbar_signals.pbar_reset.connect(lambda: pbar.reset()) 724 # Paint it now. The callers run on the main thread and only reach the next 'processEvents' after 725 # the model is built, so without this the bar stays invisible for the whole preparation. 726 QtWidgets.QApplication.processEvents() 727 return pbar, pbar_signals 728 729 730def _reset_tracking_state(viewer): 731 """Reset the tracking state. 732 733 This helper function is needed by the widgets clear_track and by commit_track. 734 """ 735 state = AnnotatorState() 736 737 # Reset the lineage and track id. 738 state.current_track_id = 1 739 state.lineage = {1: []} 740 741 # Reset the layer properties. 742 viewer.layers["point_prompts"].property_choices["track_id"] = ["1"] 743 viewer.layers["prompts"].property_choices["track_id"] = ["1"] 744 745 # Reset the choices in the track_id menu (index 2: prompt, track_state, track_id). 746 state.annotator._tracking_widget[2].value = "1" 747 state.annotator._tracking_widget[2].choices = ["1"] 748 749 750# 751# Widgets implemented with magicgui. 752# 753 754 755@magic_factory(call_button="Clear Annotations [Shift + C]") 756def clear(viewer: "napari.viewer.Viewer") -> None: 757 """Widget for clearing the current annotations. 758 759 Args: 760 viewer: The napari viewer. 761 """ 762 vutil.clear_annotations(viewer) 763 764 # Perform garbage collection. 765 gc.collect() 766 767 768@magic_factory(call_button="Clear Annotations [Shift + C]") 769def clear_volume( 770 viewer: "napari.viewer.Viewer", all_slices: bool = True 771) -> None: 772 """Widget for clearing the current annotations in 3D. 773 774 Args: 775 viewer: The napari viewer. 776 all_slices: Choose whether to clear the annotations for all or only the current slice. 777 """ 778 state = AnnotatorState() 779 780 if all_slices: 781 vutil.clear_annotations(viewer) 782 else: 783 i = vutil.current_slice(viewer, viewer.layers["current_object"]) 784 vutil.clear_annotations_slice(viewer, i=i) 785 786 # If this is a SAM2 promptable segmentation workflow, 787 # reset the prompts after the user clicks 'clear annotations'. 788 if state.interactive_segmenter is not None: 789 state.interactive_segmenter.reset_predictor() 790 791 # Perform garbage collection. 792 gc.collect() 793 794 795@magic_factory(call_button="Clear Annotations [Shift + C]") 796def clear_track( 797 viewer: "napari.viewer.Viewer", all_frames: bool = True 798) -> None: 799 """Widget for clearing all tracking annotations and state. 800 801 Args: 802 viewer: The napari viewer. 803 all_frames: Choose whether to clear the annotations for all or only the current frame. 804 """ 805 if all_frames: 806 _reset_tracking_state(viewer) 807 vutil.clear_annotations(viewer) 808 else: 809 i = vutil.current_slice(viewer, viewer.layers["current_object"]) 810 vutil.clear_annotations_slice(viewer, i=i) 811 812 # Perform garbage collection. 813 gc.collect() 814 815 816def _mask_matched_objects(seg, prev_seg, preservation_threshold): 817 prev_ids = np.unique(prev_seg) 818 ovlp = segmentation_overlap(prev_seg, seg) 819 820 mask_ids, prev_mask_ids = [], [] 821 for prev_id in prev_ids: 822 ovlp_table = ovlp.overlaps_for_label_a(prev_id) 823 seg_ids, overlaps = ovlp_table["label"], ovlp_table["count"] 824 if seg_ids[0] != 0 and overlaps[0] >= preservation_threshold: 825 mask_ids.append(seg_ids[0]) 826 prev_mask_ids.append(prev_id) 827 828 preserve_mask = np.logical_or( 829 np.isin(seg, mask_ids), np.isin(prev_seg, prev_mask_ids) 830 ) 831 return preserve_mask 832 833 834def _commit_impl(viewer, layer, preserve_mode, preservation_threshold): 835 state = AnnotatorState() 836 837 # Check whether all layers exist as expected or create new ones automatically. 838 state.annotator._require_layers(layer_choices=[layer, "committed_objects"]) 839 840 # Check if we have a z_range. If yes, use it to set a bounding box. 841 if state.z_range is None: 842 bb = np.s_[:] 843 else: 844 z_min, z_max = state.z_range 845 bb = np.s_[z_min : (z_max + 1)] # noqa 846 847 # Cast the dtype of the segmentation we work with correctly. 848 # Otherwise we run into type conversion errors later. 849 dtype = viewer.layers["committed_objects"].data.dtype 850 seg = viewer.layers[layer].data[bb].astype(dtype) 851 shape = seg.shape 852 853 # We parallelize these operations because they take quite long for large volumes. 854 855 # Compute the max id in the commited objects. 856 # id_offset = int(viewer.layers["committed_objects"].data.max()) 857 full_shape = viewer.layers["committed_objects"].data.shape 858 id_offset = int( 859 elf.parallel.max( 860 viewer.layers["committed_objects"].data, 861 block_shape=util.get_block_shape(full_shape), 862 ) 863 ) 864 865 # Compute the mask for the current object. 866 # mask = seg != 0 867 mask = np.zeros(seg.shape, dtype="bool") 868 mask = elf.parallel.apply_operation( 869 seg, 0, np.not_equal, out=mask, block_shape=util.get_block_shape(shape) 870 ) 871 if preserve_mode != "none": 872 prev_seg = viewer.layers["committed_objects"].data[bb] 873 # The mode 'pixels' corresponds to a naive implementation where only committed pixels are preserved. 874 preserve_mask = prev_seg != 0 875 # If the preserve mask is empty we don't need to do anything else here, because we don't have prev objects. 876 if preserve_mask.sum() != 0: 877 # In the mode 'objects' we preserve committed objects instead, by comparing the overlaps 878 # of already committed and newly committed objects. 879 if preserve_mode == "objects": 880 preserve_mask = _mask_matched_objects( 881 seg, prev_seg, preservation_threshold 882 ) 883 mask[preserve_mask] = 0 884 885 # Write the current object to committed objects. 886 seg[mask] += id_offset 887 viewer.layers["committed_objects"].data[bb][mask] = seg[mask] 888 viewer.layers["committed_objects"].refresh() 889 890 # If this is a SAM2 promptable segmentation workflow, reset the prompts after the user clicks commit. 891 if state.interactive_segmenter is not None: 892 state.interactive_segmenter.reset_predictor() 893 894 return id_offset, seg, mask, bb 895 896 897def _get_auto_segmentation_options(state, object_ids): 898 # The parameters of a run depend on the mode, so the widget reports them. 899 widget = state.widgets["autosegment"] 900 901 segmentation_options = { 902 "object_ids": [int(object_id) for object_id in object_ids] 903 } 904 segmentation_options.update(widget.commit_settings()) 905 906 return segmentation_options 907 908 909def _get_promptable_segmentation_options(state, object_ids): 910 segmentation_options = { 911 "object_ids": [int(object_id) for object_id in object_ids] 912 } 913 return segmentation_options, False 914 915 916def _commit_to_file(path, viewer, layer, seg, mask, bb, extra_attrs=None): 917 # NOTE: zarr-python is quite inefficient and writes empty blocks. 918 # So we have to use z5py here. 919 920 # Deal with issues z5py has with empty folders and require the json. 921 if os.path.exists(path): 922 required_json = os.path.join(path, ".zgroup") 923 if not os.path.exists(required_json): 924 with open(required_json, "w") as f: 925 json.dump({"zarr_format": 2}, f) 926 927 f = z5py.ZarrFile(path, "a") 928 state = AnnotatorState() 929 930 def _save_signature(f, data_signature): 931 embeds = state.widgets["embeddings"] 932 tile_shape, halo = _process_tiling_inputs( 933 embeds.tile_x, embeds.tile_y, embeds.halo_x, embeds.halo_y 934 ) 935 signature = util._get_embedding_signature( 936 input_=None, # We don't need this because we pass the data signature. 937 predictor=state.predictor, 938 tile_shape=tile_shape, 939 halo=halo, 940 data_signature=data_signature, 941 ) 942 for key, val in signature.items(): 943 f.attrs[key] = val 944 945 # If the data signature is saved in the file already, 946 # then we check if saved data signature and data signature of our image agree. 947 # If not, this file was used for committing objects from another file. 948 if "data_signature" in f.attrs: 949 saved_signature = f.attrs["data_signature"] 950 current_signature = state.data_signature 951 if saved_signature != current_signature: # Signatures disagree. 952 msg = f"The commit_path {path} was already used for saving annotations for different image data:\n" 953 msg += f"The data signatures are different: {saved_signature} != {current_signature}.\n" 954 msg += "Press 'Ok' to remove the data already stored in that file and continue annotation.\n" 955 msg += "Otherwise please select a different file path." 956 skip_clear = _generate_message("info", msg) 957 if skip_clear: 958 return 959 else: 960 f = z5py.ZarrFile(path, "w") 961 _save_signature(f, current_signature) 962 # Otherwise (data signature not saved yet), write the current signature. 963 else: 964 _save_signature(f, state.data_signature) 965 966 # Write the segmentation. 967 full_shape = viewer.layers["committed_objects"].data.shape 968 block_shape = util.get_block_shape(full_shape) 969 ds = f.require_dataset( 970 "committed_objects", 971 shape=full_shape, 972 chunks=block_shape, 973 compression="gzip", 974 dtype=seg.dtype, 975 ) 976 ds.n_threads = mp.cpu_count() 977 data = ds[bb] 978 data[mask] = seg[mask] 979 ds[bb] = data 980 981 # Write additional information to attrs. 982 if extra_attrs is not None: 983 f.attrs.update(extra_attrs) 984 985 # Get the commit history and the objects that are being commited. 986 commit_history = f.attrs.get("commit_history", []) 987 object_ids = np.unique(seg[mask]) 988 989 # We committed an automatic segmentation. 990 if layer == "auto_segmentation": 991 # Save the settings of the segmentation widget. 992 segmentation_options = _get_auto_segmentation_options( 993 state, object_ids 994 ) 995 commit_history.append({"auto_segmentation": segmentation_options}) 996 997 # Write the commit history. 998 f.attrs["commit_history"] = commit_history 999 1000 # If we run commit from the automatic segmentation we don't have 1001 # any prompts and so don't need to commit anything else. 1002 return 1003 1004 segmentation_options, is_tracking = _get_promptable_segmentation_options( 1005 state, object_ids 1006 ) 1007 commit_history.append({"current_object": segmentation_options}) 1008 1009 def write_prompts( 1010 object_id, prompts, point_prompts, point_labels, track_state=None 1011 ): 1012 g = f.create_group(f"prompts/{object_id}") 1013 if prompts is not None and len(prompts) > 0: 1014 data = np.array(prompts) 1015 g.create_dataset( 1016 "prompts", data=data, shape=data.shape, chunks=data.shape 1017 ) 1018 if point_prompts is not None and len(point_prompts) > 0: 1019 g.create_dataset( 1020 "point_prompts", 1021 data=point_prompts, 1022 shape=data.shape, 1023 chunks=point_prompts.shape, 1024 ) 1025 ds = g.create_dataset( 1026 "point_labels", 1027 data=point_labels, 1028 shape=data.shape, 1029 chunks=point_labels.shape, 1030 ) 1031 if track_state is not None: 1032 ds.attrs["track_state"] = track_state.tolist() 1033 1034 # Get the prompts from the layers. 1035 prompts = viewer.layers["prompts"].data 1036 point_layer = viewer.layers["point_prompts"] 1037 point_prompts = point_layer.data 1038 point_labels = point_layer.properties["label"] 1039 if len(point_prompts) > 0: 1040 point_labels = np.array( 1041 [1 if label == "positive" else 0 for label in point_labels] 1042 ) 1043 assert len(point_prompts) == len( 1044 point_labels 1045 ), f"Number of point prompts and labels disagree: {len(point_prompts)} != {len(point_labels)}" 1046 1047 # Commit the prompts for all the objects in the commit. 1048 if len(object_ids) == 1: # We only have a single object. 1049 write_prompts(object_ids[0], prompts, point_prompts, point_labels) 1050 1051 elif ( 1052 is_tracking 1053 ): # We have multiple objects from tracking a lineage with divisions. 1054 track_ids_points = np.array(point_layer.properties["track_id"]) 1055 track_ids_prompts = np.array( 1056 viewer.layers["prompts"].properties["track_id"] 1057 ) 1058 1059 unique_track_ids = np.unique(track_ids_points) 1060 assert len(unique_track_ids) == len(object_ids) 1061 track_state = np.array(point_layer.properties["state"]) 1062 for track_id, object_id in zip(unique_track_ids, object_ids): 1063 this_prompts = ( 1064 None 1065 if len(prompts) == 0 1066 else prompts[track_ids_prompts == track_id] 1067 ) 1068 point_mask = track_ids_points == track_id 1069 this_points, this_labels, this_track_state = ( 1070 point_prompts[point_mask], 1071 point_labels[point_mask], 1072 track_state[point_mask], 1073 ) 1074 write_prompts( 1075 object_id, 1076 this_prompts, 1077 this_points, 1078 this_labels, 1079 track_state=this_track_state, 1080 ) 1081 1082 else: # We have multiple objects, which are the result from batched interactive segmentation. 1083 # Note: we can't match exact object ids to their prompts, for batched segmentation. 1084 # We first write the objects from box prompts, then from point prompts. 1085 n_prompts, n_points = len(prompts), len(point_prompts) 1086 assert n_prompts + n_points == len( 1087 object_ids 1088 ), f"Number of prompts and objects disagree: {n_prompts} + {n_points} != {len(object_ids)}" 1089 for i, object_id in enumerate(object_ids): 1090 if i < n_prompts: 1091 this_prompts, this_points, this_labels = ( 1092 prompts[i : i + 1], # noqa 1093 None, 1094 None, 1095 ) 1096 else: 1097 j = i - n_prompts 1098 this_prompts, this_points, this_labels = ( 1099 None, 1100 point_prompts[j : j + 1], # noqa 1101 point_labels[j : j + 1], # noqa 1102 ) 1103 write_prompts(object_id, this_prompts, this_points, this_labels) 1104 1105 # Write the commit history. 1106 f.attrs["commit_history"] = commit_history 1107 1108 1109def _call_button_tooltip(widget_type, name): 1110 # Returns a magic_factory 'widget_init' that sets the call button's tooltip (magicgui call buttons 1111 # cannot be given a tooltip via the decorator directly). 1112 def _init(widget): 1113 widget.call_button.tooltip = get_tooltip(widget_type, name) 1114 return _init 1115 1116 1117@magic_factory( 1118 call_button="Commit [C]", 1119 widget_init=_call_button_tooltip("commit", "commit_button"), 1120 layer={ 1121 "choices": ["current_object", "auto_segmentation"], 1122 "tooltip": get_tooltip("commit", "layer"), 1123 }, 1124 preserve_mode={ 1125 "choices": ["objects", "pixels", "none"], 1126 "tooltip": get_tooltip("commit", "preserve_mode"), 1127 }, 1128 commit_path={"mode": "d", "tooltip": get_tooltip("commit", "commit_path")}, 1129) 1130def commit( 1131 viewer: "napari.viewer.Viewer", 1132 layer: str = "current_object", 1133 preserve_mode: str = "pixels", 1134 preservation_threshold: float = 0.75, 1135 commit_path: Optional[Path] = None, 1136) -> None: 1137 """Widget for committing the segmented objects from automatic or interactive segmentation. 1138 1139 Args: 1140 viewer: The napari viewer. 1141 layer: Select the layer to commit. Can be either 'current_object' to commit interacitve segmentation results. 1142 Or 'auto_segmentation' to commit automatic segmentation results. 1143 The annotator selects the layer of the last segmentation. The user can change it. 1144 preserve_mode: The mode for preserving already committed objects, in order to prevent over-writing 1145 them by a new commit. Supports the modes 'objects', which preserves on the object level, 1146 'pixels', which preserves on the pixel-level and is the default, or 'none', which does not 1147 preserve commited objects. 1148 preservation_threshold: The overlap threshold for preserving objects. This is only used if 1149 preservation_mode is set to 'objects'. 1150 commit_path: Select a file path where the committed results and prompts will be saved. 1151 This feature is not implemented yet and will be supported in a future release. 1152 """ 1153 # Saving committed results to file is not supported yet. 1154 if commit_path is not None: 1155 raise NotImplementedError( 1156 "Saving committed results to 'commit_path' is not supported yet and will be added in a future release." 1157 ) 1158 1159 # Commit the segmentation layer. 1160 _commit_impl(viewer, layer, preserve_mode, preservation_threshold) 1161 1162 if layer == "current_object": 1163 vutil.clear_annotations(viewer) 1164 else: 1165 viewer.layers["auto_segmentation"].data = np.zeros( 1166 viewer.layers["auto_segmentation"].data.shape, dtype="uint32" 1167 ) 1168 viewer.layers["auto_segmentation"].refresh() 1169 _select_layer(viewer, "committed_objects") 1170 1171 # Perform garbage collection 1172 gc.collect() 1173 1174 1175@magic_factory( 1176 call_button="Commit [C]", 1177 widget_init=_call_button_tooltip("commit", "commit_button"), 1178 layer={ 1179 "choices": ["current_object", "auto_segmentation"], 1180 "tooltip": get_tooltip("commit", "layer"), 1181 }, 1182 preserve_mode={ 1183 "choices": ["objects", "pixels", "none"], 1184 "tooltip": get_tooltip("commit", "preserve_mode"), 1185 }, 1186 commit_path={"mode": "d", "tooltip": get_tooltip("commit", "commit_path")}, 1187) 1188def commit_track( 1189 viewer: "napari.viewer.Viewer", 1190 layer: str = "current_object", 1191 preserve_mode: str = "pixels", 1192 preservation_threshold: float = 0.75, 1193 commit_path: Optional[Path] = None, 1194) -> None: 1195 """Widget for committing the objects from interactive tracking. 1196 1197 Args: 1198 viewer: The napari viewer. 1199 layer: Select the layer to commit. Can be either 'current_object' to commit interacitve segmentation results. 1200 Or 'auto_segmentation' to commit automatic segmentation results. 1201 The annotator selects the layer of the last segmentation. The user can change it. 1202 preserve_mode: The mode for preserving already committed objects, in order to prevent over-writing 1203 them by a new commit. Supports the modes 'objects', which preserves on the object level, 1204 'pixels', which preserves on the pixel-level and is the default, or 'none', which does not 1205 preserve commited objects. 1206 preservation_threshold: The overlap threshold for preserving objects. This is only used if 1207 preservation_mode is set to 'objects'. 1208 commit_path: Select a file path where the committed results and prompts will be saved. 1209 This feature is still experimental. 1210 """ 1211 # Commit the segmentation layer. 1212 id_offset, seg, mask, bb = _commit_impl( 1213 viewer, layer, preserve_mode, preservation_threshold 1214 ) 1215 1216 # Update the lineages: the ones of the automatic tracking, or the single one of the interactive tracking. 1217 state = AnnotatorState() 1218 if layer == "auto_segmentation": 1219 if state.auto_lineages is None: 1220 # A segmentation without tracking: every object is a track of its own, without divisions. 1221 lineage = {int(object_id): [] for object_id in np.unique(seg[mask]) if object_id != 0} 1222 if lineage: 1223 state.committed_lineages.append(lineage) 1224 else: 1225 state.committed_lineages.extend( 1226 {parent + id_offset: [child + id_offset for child in children] for parent, children in lineage.items()} 1227 for lineage in state.auto_lineages 1228 ) 1229 else: 1230 state.committed_lineages.append({ 1231 parent + id_offset: [child + id_offset for child in children] 1232 for parent, children in state.lineage.items() 1233 }) 1234 1235 if commit_path is not None: 1236 _commit_to_file( 1237 commit_path, 1238 viewer, 1239 layer, 1240 seg, 1241 mask, 1242 bb, 1243 extra_attrs={"committed_lineages": state.committed_lineages}, 1244 ) 1245 1246 if layer == "current_object": 1247 vutil.clear_annotations(viewer) 1248 else: 1249 # Clear the committed result, so that it is not committed a second time. 1250 state.auto_lineages = None 1251 viewer.layers["auto_segmentation"].data = np.zeros( 1252 viewer.layers["auto_segmentation"].data.shape, dtype="uint32" 1253 ) 1254 viewer.layers["auto_segmentation"].refresh() 1255 1256 # Create / update the tracking layer. 1257 layer_name = "tracks" 1258 segmentation = viewer.layers["committed_objects"].data 1259 track_data, parent_graph = get_napari_track_data( 1260 segmentation, state.committed_lineages 1261 ) 1262 if layer_name in viewer.layers: 1263 layer = viewer.layers[layer_name] 1264 layer.data = track_data 1265 layer.graph = parent_graph 1266 else: 1267 viewer.add_tracks(track_data, name=layer_name, graph=parent_graph) 1268 1269 # Reset the interactive tracking state, which an automatic result does not use. 1270 if layer == "current_object": 1271 _reset_tracking_state(viewer) 1272 1273 # Perform garbage collection. 1274 gc.collect() 1275 1276 1277@magic_factory( 1278 call_button="Export", 1279 widget_init=_call_button_tooltip("annotator_tracking", "export_button"), 1280 export_format={"choices": ["CTC", "GEFF", "TrackMate XML"]}, 1281 export_folder={"mode": "d"}, # choose a directory 1282) 1283def export_track( 1284 viewer: "napari.viewer.Viewer", 1285 export_format: str = "CTC", 1286 export_folder: Path = Path.cwd(), 1287) -> None: 1288 """Widget for exporting the committed tracking result. 1289 1290 Args: 1291 viewer: The napari viewer. 1292 export_format: The tracking export format. Supports 'CTC', 'GEFF' and 'TrackMate XML'. 1293 export_folder: The folder where the export is written. By default the current working directory is used. 1294 """ 1295 if "committed_objects" not in viewer.layers or viewer.layers["committed_objects"].data.max() == 0: 1296 _generate_message("error", "There are no committed tracking results to export yet.") 1297 return 1298 1299 segmentation = viewer.layers["committed_objects"].data 1300 lineages = AnnotatorState().committed_lineages 1301 if export_format == "CTC": 1302 export_tracking_result_to_ctc(segmentation, lineages, export_folder) 1303 show_info(f"Exported the tracking result to CTC format in '{export_folder}'.") 1304 elif export_format == "GEFF": 1305 export_path = export_tracking_result_to_geff(segmentation, lineages, export_folder) 1306 show_info(f"Exported the tracking result to GEFF format in '{export_path}'.") 1307 elif export_format == "TrackMate XML": 1308 export_path = export_tracking_result_to_trackmate_xml(segmentation, lineages, export_folder) 1309 show_info(f"Exported the tracking result to TrackMate XML format in '{export_path}'.") 1310 else: 1311 _generate_message("error", f"Unsupported tracking export format: {export_format}.") 1312 1313 1314def create_prompt_menu( 1315 points_layer, labels, menu_name="prompt", label_name="label", linked_layers=None, viewer=None, 1316): 1317 """Create a menu that keeps point and optional shape prompt labels synchronized.""" 1318 prompt_layers = [points_layer] + ([] if linked_layers is None else list(linked_layers)) 1319 label_menu = ComboBox( 1320 label=menu_name, 1321 choices=labels, 1322 tooltip=get_tooltip("prompt_menu", "labels"), 1323 ) 1324 label_widget = Container(widgets=[label_menu]) 1325 1326 def update_label_menu(event): 1327 new_label = str(event.source.current_properties[label_name][0]) 1328 if new_label != label_menu.value: 1329 label_menu.value = new_label 1330 1331 for layer in prompt_layers: 1332 layer.events.current_properties.connect(update_label_menu) 1333 1334 def label_changed(new_label): 1335 for layer in prompt_layers: 1336 if label_name == "label": 1337 # Only the layer in use relabels its selected scribbles, see 'relabels_selection'. 1338 vutil.set_prompt_label( 1339 layer, new_label, relabel_selected=vutil.relabels_selection(layer, viewer) 1340 ) 1341 else: 1342 current_properties = layer.current_properties 1343 current_properties[label_name] = np.array([new_label]) 1344 layer.current_properties = current_properties 1345 layer.refresh_colors() 1346 1347 label_menu.changed.connect(label_changed) 1348 1349 return label_widget 1350 1351 1352@magic_factory( 1353 call_button="Update settings", 1354 cache_directory={"mode": "d"}, # choose a directory 1355) 1356def settings_widget( 1357 cache_directory: Optional[Path] = util.get_cache_directory(), 1358) -> None: 1359 """Widget to update global micro_sam settings. 1360 1361 Args: 1362 cache_directory: Select the path for the micro_sam cache directory. `$HOME/.cache/micro_sam`. 1363 """ 1364 os.environ["MICROSAM_CACHEDIR"] = str(cache_directory) 1365 print(f"micro-sam cache directory set to: {cache_directory}") 1366 1367 1368def _generate_message(message_type: str, message: str) -> bool: 1369 """ 1370 Displays a message dialog based on the provided message type. 1371 1372 Args: 1373 message_type: The type of message to display. Valid options are: 1374 - "error": Displays a critical error message with an "Ok" button. 1375 - "info": Displays an informational message in a separate dialog box. 1376 The user can dismiss it by either clicking "Ok" or closing the dialog. 1377 message: The message content to be displayed in the dialog. 1378 1379 Returns: 1380 A flag indicating whether the user aborted the operation based on the 1381 message type. This flag is only set for "info" messages where the user 1382 can choose to cancel (rejected). 1383 1384 Raises: 1385 ValueError: If an invalid message type is provided. 1386 """ 1387 # Set button text and behavior based on message type 1388 if message_type == "error": 1389 QtWidgets.QMessageBox.critical( 1390 None, "Error", message, QtWidgets.QMessageBox.Ok 1391 ) 1392 abort = True 1393 return abort 1394 elif message_type == "info": 1395 info_dialog = InfoDialog(title="Validation Message", message=message) 1396 result = info_dialog.exec_() 1397 if result == QtWidgets.QDialog.Rejected: # Check for cancel 1398 abort = True # Set flag directly in calling function 1399 return abort 1400 else: 1401 raise ValueError(f"Invalid message type {message_type}") 1402 1403 1404def _ask_load_or_recompute(message: str) -> str: 1405 """Ask the user whether to load existing embeddings or recompute them. 1406 1407 Returns 'load', 'recompute' or 'cancel'. 1408 """ 1409 dialog = InfoDialog(title="Existing embeddings found", message=message, buttons=("Load", "Recompute", "Cancel")) 1410 dialog.exec_() 1411 return {"Load": "load", "Recompute": "recompute"}.get(dialog.clicked_label, "cancel") 1412 1413 1414def _validate_embeddings(viewer: "napari.viewer.Viewer"): 1415 state = AnnotatorState() 1416 if state.image_embeddings is None: 1417 msg = "Image embeddings are not yet computed. Press 'Compute Embeddings' to compute them for your image." 1418 return _generate_message("error", msg) 1419 else: 1420 return False 1421 1422 # This code is for checking the data signature of the current image layer and the data signature 1423 # of the embeddings. However, the code has some disadvantages, for example assuming the position of the 1424 # image layer and also having to compute the data signature every time. 1425 # That's why we are not using this for now, but may want to revisit this in the future. See: 1426 # https://github.com/computational-cell-analytics/micro-sam/issues/504 1427 1428 # embeddings_save_path = state.embedding_path 1429 # embedding_data_signature = None 1430 # image = None 1431 # if isinstance(viewer.layers[0], napari.layers.Image): # Assuming the image layer is at index 0 1432 # image = viewer.layers[0] 1433 # else: 1434 # # Handle the case where the first layer isn't an Image layer 1435 # raise ValueError("Expected an Image layer in viewer.layers") 1436 # img_signature = util._compute_data_signature(image.data) 1437 # if embeddings_save_path is not None: 1438 # # Check for existing embeddings 1439 # if os.listdir(embeddings_save_path): 1440 # try: 1441 # with zarr.open(embeddings_save_path, "a") as f: 1442 # # If data_signature exists, compare and return validation message 1443 # if "data_signature" in f.attrs: 1444 # embedding_data_signature = f.attrs["data_signature"] 1445 # except RuntimeError as e: 1446 # val_results = { 1447 # "message_type": "error", 1448 # "message": f"Failed to load image embeddings: {e}" 1449 # } 1450 # else: 1451 # val_results = {"message_type": "info", "message": "No existing embeddings found at the specified path."} 1452 # else: # load from state object 1453 # embedding_data_signature = state.data_signature 1454 # # compare image data signature with embedding data signature 1455 # if img_signature != embedding_data_signature: 1456 # val_results = { 1457 # "message_type": "error", 1458 # "message": f"The embeddings don't match with the image: {img_signature} {embedding_data_signature}" 1459 # } 1460 # else: 1461 # val_results = None 1462 # if val_results: 1463 # return _generate_message(val_results["message_type"], val_results["message"]) 1464 # else: 1465 # return False 1466 1467 1468def _validation_window_for_missing_layer(layer_choice): 1469 if layer_choice == "committed_objects": 1470 msg = "The 'committed_objects' layer to commit masks is missing. Please try to commit again." 1471 else: 1472 msg = f"The '{layer_choice}' layer to commit is missing. Please re-annotate and try again." 1473 1474 return _generate_message(message_type="error", message=msg) 1475 1476 1477def _validate_layers( 1478 viewer: "napari.viewer.Viewer", automatic_segmentation: bool = False 1479) -> bool: 1480 # Check whether all layers exist as expected or create new ones automatically. 1481 state = AnnotatorState() 1482 state.annotator._require_layers() 1483 1484 if not automatic_segmentation: 1485 # Check prompts layer. 1486 if ( 1487 len(viewer.layers["prompts"].data) == 0 1488 and len(viewer.layers["point_prompts"].data) == 0 1489 ): 1490 msg = "No prompts were given. Please provide prompts to run interactive segmentation." 1491 return _generate_message("error", msg) 1492 else: 1493 return False 1494 1495 1496def _embeddings_are_tiled(state): 1497 """Whether the current embeddings are tiled (tiled embeddings have a top-level 'input_size' of None).""" 1498 return state.image_embeddings is not None and state.image_embeddings.get("input_size") is None 1499 1500 1501def _batched_disabled_when_tiled(state, batched): 1502 """Batched (multi-object) prompting is not supported with tiling: each tile is segmented 1503 independently, so object ids would collide across tiles. Force single-object and warn.""" 1504 if batched and _embeddings_are_tiled(state): 1505 show_info( 1506 "Batched (multi-object) prompting is not supported with tiling. " 1507 "It runs single-object segmentation instead." 1508 ) 1509 return False 1510 return batched 1511 1512 1513def _bound_z_range_by_stops(prompted_slices, stop_slices, n_slices, z_range=None): 1514 """Bound the propagation range by the stop annotations (a lone negative point) of a volume. 1515 1516 A stop below all prompted slices ends the object below, a stop above all prompted slices ends it 1517 above. The stop slice itself stays empty. A stop between prompted slices is ignored. 1518 1519 Args: 1520 prompted_slices: The slices carrying a segmentation prompt. 1521 stop_slices: The slices carrying a stop annotation. 1522 n_slices: The number of slices in the volume. 1523 z_range: The inclusive (z_min, z_max) range selected by the user, or None for the full volume. 1524 1525 Returns: 1526 The inclusive (z_min, z_max) propagation range, or None for the full volume. 1527 The stop slices that were ignored. 1528 """ 1529 if not stop_slices or not prompted_slices: 1530 return z_range, [] 1531 1532 z_first, z_last = min(prompted_slices), max(prompted_slices) 1533 lower = [z for z in stop_slices if z < z_first] 1534 upper = [z for z in stop_slices if z > z_last] 1535 ignored = sorted(z for z in stop_slices if z_first <= z <= z_last) 1536 if not lower and not upper: 1537 return z_range, ignored 1538 1539 z_min, z_max = (0, n_slices - 1) if z_range is None else z_range 1540 if lower: 1541 z_min = max(z_min, max(lower) + 1) 1542 if upper: 1543 z_max = min(z_max, min(upper) - 1) 1544 return (z_min, z_max), ignored 1545 1546 1547def _plan_volume_prompts(merged_prompts, shape_prompts, is_batched): 1548 """Plan every prompt push of a volume segmentation round, in the order they must be pushed. 1549 1550 Shapes come first: SAM2 requires a box before any point on the same object and frame, so pushing 1551 the shapes ahead of the points lets a shape and its correction points combine regardless of the 1552 order they were drawn in. 1553 1554 In batched mode each box, mask and positive point is an object of its own, drawing ids from one 1555 shared counter, and a slice's negative points correct every object on that slice. In standard mode 1556 every prompt feeds the single object the segmenter defaults to. 1557 1558 Args: 1559 merged_prompts: Per-slice '(points, labels)', including the points a scribble expands into. 1560 shape_prompts: Per-slice '(boxes, masks)', with the rectangles separated from the filled shapes. 1561 is_batched: Whether each positive prompt defines an object of its own. 1562 1563 Returns: 1564 The pushes as '(kind, frame_id, object_ids, payload)' tuples. The payload is '(points, labels)' 1565 for a point push and the list of shapes otherwise; 'object_ids' is None in standard mode. 1566 """ 1567 plan = [] 1568 object_id = 0 1569 1570 def negatives_on(frame_id): 1571 # Only batched objects need the negatives shared explicitly; in standard mode they already 1572 # reach the one object through the point pushes below. 1573 if not is_batched: 1574 return np.zeros((0, 2)) 1575 points, labels = merged_prompts.get(frame_id, (np.zeros((0, 2)), np.zeros(0, dtype=int))) 1576 return points[labels != 1] 1577 1578 for frame_id, (boxes, masks) in shape_prompts.items(): 1579 negatives = negatives_on(frame_id) 1580 negative_labels = np.zeros(len(negatives), dtype=int) 1581 for kind, shapes in (("box", boxes), ("mask", masks)): 1582 if not shapes: 1583 continue 1584 ids = list(range(object_id + 1, object_id + 1 + len(shapes))) if is_batched else None 1585 object_id += len(shapes) 1586 plan.append((kind, frame_id, ids, shapes)) 1587 if ids is not None and len(negatives): 1588 for obj_id in ids: 1589 plan.append(("point", frame_id, [obj_id] * len(negatives), (negatives, negative_labels))) 1590 1591 for frame_id, (points, labels) in merged_prompts.items(): 1592 if not is_batched: 1593 plan.append(("point", frame_id, None, (points, labels))) 1594 continue 1595 negatives = points[labels != 1] 1596 negative_labels = np.zeros(len(negatives), dtype=int) 1597 for positive in points[labels == 1]: 1598 object_id += 1 1599 if len(negatives): 1600 pts = np.concatenate([positive[None], negatives]) 1601 lbs = np.concatenate([[1], negative_labels]) 1602 else: 1603 pts, lbs = positive[None], np.array([1]) 1604 plan.append(("point", frame_id, [object_id] * len(pts), (pts, lbs))) 1605 1606 return plan 1607 1608 1609def _volume_prompt_signatures(plan): 1610 """Hashable descriptors of every planned push, used to detect prompts changed since the last run. 1611 1612 The object id is part of the signature. 'sync_prompt_state' keeps the persistent SAM2 state when 1613 the new prompt set is a superset of the previous one, and the routing is what makes that safe: 1614 adding a box renumbers the objects of every prompt behind it, so without the id an unchanged point 1615 would be replayed into a different object and corrupt the state it is deduplicated against. 1616 """ 1617 signatures = set() 1618 for kind, frame_id, object_ids, payload in plan: 1619 if kind == "point": 1620 points, labels = payload 1621 ids = [1] * len(points) if object_ids is None else object_ids 1622 for (y, x), label, obj_id in zip(points, labels, ids): 1623 signatures.add(("point", obj_id, frame_id, round(float(y)), round(float(x)), int(label))) 1624 continue 1625 ids = [1] * len(payload) if object_ids is None else object_ids 1626 for shape, obj_id in zip(payload, ids): 1627 if kind == "box": 1628 signatures.add( 1629 ("box", obj_id, frame_id) + tuple(np.round(np.asarray(shape)).astype(int).tolist()) 1630 ) 1631 else: 1632 digest = hashlib.sha1(np.ascontiguousarray(shape).tobytes()).hexdigest() 1633 signatures.add(("mask", obj_id, frame_id, digest)) 1634 return signatures 1635 1636 1637def _push_volume_prompts(segmenter, plan): 1638 """Push a planned prompt round; the segmenter skips the prompts already in its persistent state.""" 1639 for kind, frame_id, object_ids, payload in plan: 1640 if kind == "point": 1641 points, labels = payload 1642 segmenter.add_point_prompts( 1643 frame_ids=frame_id, points=points, point_labels=labels, object_id=object_ids, 1644 ) 1645 elif kind == "box": 1646 segmenter.add_box_prompts(frame_ids=frame_id, boxes=payload, object_id=object_ids) 1647 else: 1648 segmenter.add_mask_prompts(frame_ids=frame_id, masks=payload, object_id=object_ids) 1649 1650 1651def _segment_object_2d(viewer, batched=False): 1652 """Segment object(s) in 2d for the current prompts. 1653 1654 This is the shared implementation used by the `segment` widget and the 1655 `InteractiveSegmentationWidget`. 1656 1657 Args: 1658 viewer: The napari viewer. 1659 batched: Choose if you want to segment multiple objects with point prompts. 1660 """ 1661 if _validate_embeddings(viewer): 1662 return None 1663 if _validate_layers(viewer): 1664 return None 1665 1666 shape = viewer.layers["current_object"].data.shape 1667 1668 # Get the current box, point and open-stroke prompts. Scribbles are encoded through SAM's 1669 # existing sparse point prompt embeddings, so the predictor interface remains unchanged. 1670 # 2d has no stop annotation, so a lone negative point stays a normal prompt. 1671 prompts = vutil.collect_frame_prompts( 1672 viewer.layers["point_prompts"], viewer.layers["prompts"], shape, with_stop_annotation=False, 1673 ) 1674 points, labels, boxes, masks = prompts.points, prompts.labels, prompts.boxes, prompts.masks 1675 1676 have_scribbles = prompts.have_scribbles 1677 if have_scribbles and not len(boxes) and not np.any(labels == 1): 1678 msg = "A negative scribble needs a positive point, positive scribble, box or mask prompt." 1679 return _generate_message("error", msg) 1680 1681 state = AnnotatorState() 1682 predictor = state.predictor 1683 image_embeddings = state.image_embeddings 1684 batched = _batched_disabled_when_tiled(state, batched) 1685 if have_scribbles and batched: 1686 show_info( 1687 "Batched segmentation is not supported with scribble prompts. " 1688 "It runs single-object segmentation instead." 1689 ) 1690 batched = False 1691 1692 # When the embeddings are tiled (top-level 'input_size' is None), route the prompts to the 1693 # matching tile and stitch. Otherwise the predictor already holds the single image embedding. 1694 if image_embeddings is not None and image_embeddings.get("input_size") is None: 1695 from micro_sam.v2.prompt_based_segmentation import tiled_promptable_segmentation_2d 1696 seg = tiled_promptable_segmentation_2d( 1697 predictor=predictor, image_embeddings=image_embeddings, 1698 points=points, labels=labels, boxes=boxes, masks=masks, batched=batched, 1699 devices=state.inference_devices, 1700 ) 1701 else: 1702 from micro_sam.v2.prompt_based_segmentation import promptable_segmentation_2d 1703 seg = promptable_segmentation_2d( 1704 predictor=predictor, 1705 points=points, 1706 labels=labels, 1707 boxes=boxes, 1708 masks=masks, 1709 batched=batched, 1710 ) 1711 1712 # no prompts were given or prompts were invalid, skip segmentation 1713 if seg is None: 1714 print( 1715 "You either haven't provided any prompts or invalid prompts. The segmentation will be skipped." 1716 ) 1717 return 1718 1719 viewer.layers["current_object"].data = seg 1720 viewer.layers["current_object"].refresh() 1721 1722 1723@magic_factory(call_button="Segment Object [S]") 1724def segment(viewer: "napari.viewer.Viewer", batched: bool = False) -> None: 1725 """Segment object(s) for the current prompts. 1726 1727 Args: 1728 viewer: The napari viewer. 1729 batched: Choose if you want to segment multiple objects with point prompts. 1730 """ 1731 _segment_object_2d(viewer, batched=batched) 1732 1733 1734# 1735# Functionality and widget to compute the image embeddings. 1736# 1737 1738 1739def _process_tiling_inputs(tile_shape_x, tile_shape_y, halo_x, halo_y): 1740 tile_shape = (tile_shape_x, tile_shape_y) 1741 halo = (halo_x, halo_y) 1742 # check if tile_shape/halo are not set: (0, 0) 1743 if all(item in (0, None) for item in tile_shape): 1744 tile_shape = None 1745 # check if at least 1 param is given 1746 elif tile_shape[0] == 0 or tile_shape[1] == 0: 1747 max_val = max(tile_shape[0], tile_shape[1]) 1748 if max_val < 256: # at least tile shape >256 1749 max_val = 256 1750 tile_shape = (max_val, max_val) 1751 # if both inputs given, check if smaller than 256 1752 elif tile_shape[0] != 0 and tile_shape[1] != 0: 1753 if tile_shape[0] < 256: 1754 tile_shape = (256, tile_shape[1]) # Create a new tuple 1755 if tile_shape[1] < 256: 1756 tile_shape = ( 1757 tile_shape[0], 1758 256, 1759 ) # Create a new tuple with modified value 1760 if all(item in (0, None) for item in halo): 1761 if tile_shape is not None: 1762 halo = (0, 0) 1763 else: 1764 halo = None 1765 # check if at least 1 param is given 1766 elif halo[0] != 0 or halo[1] != 0: 1767 max_val = max(halo[0], halo[1]) 1768 # don't apply halo if there is no tiling 1769 if tile_shape is None: 1770 halo = None 1771 else: 1772 halo = (max_val, max_val) 1773 return tile_shape, halo 1774 1775 1776class EmbeddingWidget(_WidgetBase): 1777 # Whether to show the CPU info popup for expensive (many-tile / 3D) computations. 1778 warn_on_cpu = True 1779 1780 # A tiled 2D image only gets slow on the CPU once it has many tiles. Warn from this many on. 1781 cpu_warn_tiles = 64 1782 1783 # Whether to offer the 'cache automatic segmentation state' option (segmentation / tracking only, 1784 # not the classification tools which have no automatic segmentation). 1785 supports_state_caching = True 1786 1787 def __init__(self, parent=None, ndim_choice=False, is_timeseries=False): 1788 super().__init__(parent=parent) 1789 # Whether to expose the 'image dimensions' (ndim) override dropdown. Only the segmentation 1790 # annotator wires it into image normalization, so it is off by default (hidden for tracking 1791 # and the classifiers, which do not use it). 1792 self.ndim_choice = ndim_choice 1793 # The tracking annotator operates on a (T, H, W) timeseries, not a 3D volume. Relabel the 1794 # embedding progress accordingly (the underlying compute path is the same as for 3D). 1795 self.is_timeseries = is_timeseries 1796 1797 # Create a nested layout for the sections. 1798 # Section 1: Image and Model. 1799 section1_layout = QtWidgets.QHBoxLayout() 1800 section1_layout.addLayout(self._create_image_section()) 1801 # Default to the single-source 'DEFAULT_MODEL' (the 'Microscopy' / 'hvit_t_cells' model); 1802 # '_create_model_section' derives the synthetic selector string from it when no value is given. 1803 section1_layout.addLayout( 1804 self._create_model_section() 1805 ) # Creates the model family widget section. 1806 self.layout().addLayout(section1_layout) 1807 1808 # Section 2: Settings (collapsible). 1809 self.layout().addWidget(self._create_settings_widget()) 1810 1811 # Enable sensible default tiling when a large image is selected. 1812 self.image_selection.changed.connect(self._set_default_tiling) 1813 self._set_default_tiling() 1814 1815 # Section 3: The button to trigger the embedding computation. 1816 self.run_button = QtWidgets.QPushButton("Compute Embeddings") 1817 self.run_button.clicked.connect(self.__call__) 1818 self.run_button.setToolTip(get_tooltip("embedding", "run_button")) 1819 self.layout().addWidget(self.run_button) 1820 1821 def _create_image_section(self): 1822 image_section = QtWidgets.QVBoxLayout() 1823 layer_label = "Timeseries Layer:" if self.is_timeseries else "Image Layer:" 1824 self.image_layer_label = QtWidgets.QLabel(layer_label) 1825 # self.image_layer_label.setToolTip(get_tooltip("embedding", "image")) # this adds tooltip to label 1826 image_section.addWidget(self.image_layer_label) 1827 1828 # Setting a napari layer in QT, see: 1829 # https://github.com/pyapp-kit/magicgui/blob/main/docs/examples/napari/napari_combine_qt.py 1830 self.image_selection = create_widget(annotation=napari.layers.Image) 1831 self.image_selection.native.setToolTip( 1832 get_tooltip("embedding", "image") 1833 ) 1834 image_section.addWidget(self.image_selection.native) 1835 1836 return image_section 1837 1838 def _update_model(self, state): 1839 _model_type = ( 1840 state.predictor.model_type 1841 if self.custom_weights 1842 else self.model_type 1843 ) 1844 1845 # Provide a detailed message for the model family and model size per chosen combination. 1846 msg = "Computed embeddings for " 1847 if ( 1848 self.custom_weights 1849 ): # Whether the user provided a filepath to custom finetuned model weights. 1850 msg += f"the model located at '{os.path.abspath(self.custom_weights)}' " 1851 # The size letter follows the backbone prefix: 'hvit_b...' for SAM2, 'vit_b...' for SAM1. 1852 size_key = _model_type[len("hvit_") if _model_type.startswith("hvit_") else len("vit_"):][:1] 1853 msg += f"of size '{self._model_size_map.get(size_key, self.model_size)}'." 1854 else: 1855 msg += ( 1856 f"the '{self.model_family}' model of size '{self.model_size}'." 1857 ) 1858 1859 show_info(msg) 1860 1861 state = AnnotatorState() 1862 # Update the widget itself. This is necessary because we may have loaded 1863 # some settings from the embedding file and have to reflect them in the widget. 1864 vutil._sync_embedding_widget( 1865 self, 1866 model_type=_model_type, 1867 save_path=self.embeddings_save_path, 1868 checkpoint_path=self.custom_weights, 1869 device=self.device, 1870 # Only forward tiling params when tiling is actually enabled. Otherwise '_sync_embedding_widget' 1871 # would force the tiling dropdown to "yes" using the (always-nonzero) default tile values. 1872 tile_shape=[self.tile_x, self.tile_y] if self.tiling == "yes" else None, 1873 halo=[self.halo_x, self.halo_y] if self.tiling == "yes" else None, 1874 ) 1875 1876 # Set the default settings for this model in the autosegment widget if it is part of 1877 # the currently used plugin. 1878 if "autosegment" in state.widgets: 1879 with_decoder = state.decoder is not None 1880 vutil._sync_autosegment_widget( 1881 state.widgets["autosegment"], 1882 _model_type, 1883 self.custom_weights, 1884 update_decoder=with_decoder, 1885 ) 1886 # Record the location of the cached decoder predictions. The widget reads and writes the cache. 1887 if with_decoder: 1888 state.autoseg_state = vutil._autoseg_state_descriptor(state.embedding_path, "ais") 1889 else: 1890 state.autoseg_state = None 1891 1892 # Now that the (possibly tiled) embeddings are known, refresh the 'Batched' control on the 1893 # segment/track widgets: batched prompting is unsupported with tiling, so it is hidden then. 1894 for widget in state.widgets.values(): 1895 update_batched = getattr(widget, "_update_batched_visibility", None) 1896 if callable(update_batched): 1897 update_batched() 1898 1899 def _create_settings_widget(self): 1900 setting_values = QtWidgets.QWidget() 1901 setting_values.setToolTip(get_tooltip("embedding", "settings")) 1902 setting_values.setLayout(QtWidgets.QVBoxLayout()) 1903 1904 # The dropdown rows of this panel, collected so that they get a uniform layout at the end. 1905 choice_rows = [] 1906 1907 # Optional image dimensionality override. 'auto' detects 2d or 3d (including channels) from the 1908 # selected image. '2d' and '3d' force the interpretation, e.g. to read a channels-first 1909 # (C, H, W) array as a 2d multi-channel image. 1910 if self.ndim_choice: 1911 self.image_ndim_mode = "auto" 1912 self.image_ndim_dropdown, ndim_layout = self._add_choice_param( 1913 "image_ndim_mode", self.image_ndim_mode, ["auto", "2d", "3d"], title="image dimensions:", 1914 tooltip=get_tooltip("embedding", "image_ndim"), 1915 ) 1916 # Forcing '2d' on a volume removes the slices the batch would span. 1917 self.image_ndim_dropdown.currentIndexChanged.connect(self._refresh_batch_size) 1918 setting_values.layout().addLayout(ndim_layout) 1919 choice_rows.append(ndim_layout) 1920 1921 # Create UI for tiling. A dropdown toggles whether the tool uses tiling. When you enable it, 1922 # the tile shape and halo fields appear with sensible defaults. 1923 self.tiling = "no" 1924 self.tiling_dropdown, tiling_layout = self._add_choice_param( 1925 "tiling", 1926 self.tiling, 1927 ["no", "yes"], 1928 title="tiling:", 1929 update=self._update_tiling_visibility, 1930 tooltip=get_tooltip("embedding", "tiling"), 1931 ) 1932 setting_values.layout().addLayout(tiling_layout) 1933 choice_rows.append(tiling_layout) 1934 1935 # Container holding the tile shape and halo fields (hidden unless tiling is 'yes'). 1936 self._tiling_widget = QtWidgets.QWidget() 1937 self._tiling_widget.setLayout(QtWidgets.QVBoxLayout()) 1938 self._tiling_widget.layout().setContentsMargins(0, 0, 0, 0) 1939 1940 # In-plane (xy) tile shape and halo, used when tiling is enabled. The defaults come from the 1941 # central v2 tiling values. The z block / halo are not set here: they only affect 3d automatic 1942 # segmentation (not the embeddings, which are tiled in-plane only), so they live in the 1943 # automatic segmentation settings instead. 1944 from micro_sam.v2.util import DEFAULT_TILE_SHAPE, DEFAULT_HALO 1945 self.tile_x, self.tile_y = DEFAULT_TILE_SHAPE 1946 self.tile_x_param, self.tile_y_param, tile_layout = self._add_shape_param( 1947 ("tile_x", "tile_y"), 1948 (self.tile_x, self.tile_y), 1949 min_val=0, 1950 max_val=2048, 1951 step=16, 1952 tooltip=get_tooltip("embedding", "tiling"), 1953 ) 1954 self._tiling_widget.layout().addLayout(tile_layout) 1955 1956 self.halo_x, self.halo_y = DEFAULT_HALO 1957 self.halo_x_param, self.halo_y_param, halo_layout = self._add_shape_param( 1958 ("halo_x", "halo_y"), 1959 (self.halo_x, self.halo_y), 1960 min_val=0, 1961 max_val=512, 1962 title=("overlap_x", "overlap_y"), 1963 tooltip=get_tooltip("embedding", "halo"), 1964 ) 1965 self._tiling_widget.layout().addLayout(halo_layout) 1966 1967 self._tiling_widget.setVisible(False) 1968 setting_values.layout().addWidget(self._tiling_widget) 1969 1970 # Add the model size widget section. 1971 model_size_layout = self._create_model_size_section() 1972 setting_values.layout().addLayout(model_size_layout) 1973 choice_rows.append(model_size_layout) 1974 1975 # Create UI for the device. 1976 self.device = "auto" 1977 device_options = ["auto"] + util._available_devices() 1978 1979 self.device_dropdown, device_layout = self._add_choice_param( 1980 "device", 1981 self.device, 1982 device_options, 1983 tooltip=get_tooltip("embedding", "device"), 1984 ) 1985 setting_values.layout().addLayout(device_layout) 1986 choice_rows.append(device_layout) 1987 1988 # The batch size follows the model and the device until the user edits it, after which their 1989 # value is kept. Until then it only previews what the backend will pick per device, see 1990 # '_effective_batch_size'. Batching only helps on a GPU, so the control is hidden whenever the 1991 # effective device is the CPU. Both visibility and value track the device dropdown, so they 1992 # also update when the user switches devices or when 'auto' resolves to the CPU. 1993 self.batch_size = 1 1994 self._batch_size_is_auto = True 1995 self.batch_size_param, batch_size_layout = self._add_int_param( 1996 "batch_size", self.batch_size, min_val=1, max_val=64, 1997 title="batch size", 1998 tooltip=get_tooltip("embedding", "batch_size"), 1999 ) 2000 self.batch_size_param.valueChanged.connect(self._on_batch_size_edited) 2001 self._batch_size_widget = QtWidgets.QWidget() 2002 self._batch_size_widget.setLayout(batch_size_layout) 2003 setting_values.layout().addWidget(self._batch_size_widget) 2004 self.device_dropdown.currentIndexChanged.connect(self._refresh_batch_size) 2005 self._refresh_batch_size() 2006 2007 # Create UI for the save path. 2008 self.embeddings_save_path = None 2009 self.embeddings_save_path_param, save_layout = self._add_path_param( 2010 "embeddings_save_path", 2011 self.embeddings_save_path, 2012 "directory", 2013 title="embeddings save path:", 2014 tooltip=get_tooltip("embedding", "embeddings_save_path"), 2015 ) 2016 setting_values.layout().addLayout(save_layout) 2017 2018 # Create UI for the custom weights. 2019 self.custom_weights = None 2020 self.custom_weights_param, weights_layout = self._add_path_param( 2021 "custom_weights", 2022 self.custom_weights, 2023 "file", 2024 title="custom weights path:", 2025 tooltip=get_tooltip("embedding", "custom_weights"), 2026 ) 2027 setting_values.layout().addLayout(weights_layout) 2028 2029 # Make the two path rows symmetric: equal label widths, so their text boxes match too. 2030 self._align_widths([save_layout.itemAt(0).widget(), weights_layout.itemAt(0).widget()]) 2031 # Move the horizontal space trimmed from the text boxes into the browse buttons (rather than 2032 # leaving a gap): widen them uniformly by that amount ('Select Directory' is wider than 2033 # 'Select File', which would otherwise offset the rows). 2034 path_button_extra = 20 2035 save_button = save_layout.itemAt(save_layout.count() - 1).widget() 2036 weights_button = weights_layout.itemAt(weights_layout.count() - 1).widget() 2037 button_width = max(save_button.sizeHint().width(), weights_button.sizeHint().width()) + path_button_extra 2038 for button in (save_button, weights_button): 2039 button.setFixedWidth(button_width) 2040 2041 # Give the dropdowns a slightly larger share of their row than the labels, so that they extend 2042 # a bit further to the left (their right edge stays at the panel margin). 2043 for row in choice_rows: 2044 row.setStretch(0, 4) 2045 row.setStretch(1, 5) 2046 2047 # Opt-in disk caching of the automatic-segmentation state (off by default). When on, the state 2048 # is precomputed to disk (next to the embeddings) while the embeddings are computed and reused 2049 # across runs / sessions. The automatic segmentation widget reads this flag from here. Not 2050 # offered by the classification tools (no automatic segmentation). 2051 self.cache_state = False 2052 if self.supports_state_caching: 2053 self.cache_state_checkbox = self._add_boolean_param( 2054 "cache_state", self.cache_state, title="cache automatic segmentation state", 2055 tooltip=get_tooltip("embedding", "cache_state"), 2056 ) 2057 setting_values.layout().addWidget(self.cache_state_checkbox) 2058 2059 # Hook for subclasses to add extra model controls at the end of the settings (no-op by default). 2060 self._add_extra_model_settings(setting_values.layout()) 2061 2062 settings = _make_collapsible( 2063 setting_values, title="Embedding Settings", tooltip=get_tooltip("embedding", "settings"), 2064 ) 2065 return settings 2066 2067 def _add_extra_model_settings(self, layout): 2068 """Hook to add extra model controls to the embedding settings. It does nothing by default. 2069 The classification embedding widget uses it to add the optional advanced-model selector.""" 2070 pass 2071 2072 def _apply_loaded_model_selection(self, model_name): 2073 """Reflect a loaded model in the model family and size dropdowns. It does nothing by default: 2074 the post-compute '_sync_embedding_widget' already syncs the SAM2-only widget, whose family 2075 names match. Subclasses with custom family handling (classification) override this.""" 2076 pass 2077 2078 def _selected_image_shape(self): 2079 # Spatial shape of the currently selected image layer (any channel axis removed), or None if 2080 # no image is selected. 2081 image = self.image_selection.get_value() 2082 if image is None: 2083 return None 2084 return image.data.shape[:-1] if image.rgb else image.data.shape 2085 2086 def _selected_image_ndim(self): 2087 # Spatial dimensionality of the currently selected image layer (2 or 3), or None if no image. 2088 shape = self._selected_image_shape() 2089 return None if shape is None else len(shape) 2090 2091 def _ndim_override(self): 2092 # The user-selected image dimensionality override: None for 'auto', else 2 or 3. Read the 2093 # dropdown directly so the value is correct regardless of signal ordering. 2094 dropdown = getattr(self, "image_ndim_dropdown", None) 2095 mode = dropdown.currentText() if dropdown is not None else "auto" 2096 return {"auto": None, "2d": 2, "3d": 3}.get(mode) 2097 2098 def _update_tiling_visibility(self, index=None): 2099 # Show the in-plane tile shape and halo fields only when tiling is enabled. 2100 self.tiling = self.tiling_dropdown.currentText() 2101 self._tiling_widget.setVisible(self.tiling == "yes") 2102 # Tiling decides whether a 2d image has anything to batch over. This also runs on image 2103 # selection, via '_set_default_tiling'. 2104 if getattr(self, "_batch_size_widget", None) is not None: 2105 self._refresh_batch_size() 2106 2107 def _batch_size_has_effect(self): 2108 # Batching does not help on the CPU (so 'auto' resolving to the CPU counts as no effect), and 2109 # the VFM encoders offered by the classifiers compute their embeddings unbatched. 2110 from micro_sam.models.vfm import is_vfm_model 2111 2112 device = self.device 2113 if device == "auto": 2114 device = util._get_default_device() 2115 if util.device_type(device) == "cpu" or is_vfm_model(getattr(self, "model_type", None)): 2116 return False 2117 2118 # A 2d image without tiling is a single encoder call, so there is nothing to batch. Tiles and 2119 # z slices are what the batch spans. An unknown dimensionality (no image yet) keeps the field. 2120 ndim = self._ndim_override() or self._selected_image_ndim() 2121 return not (ndim == 2 and self.tiling != "yes") 2122 2123 def _batch_size_is_tabulated(self): 2124 # Whether the VRAM table covers the selected model. It is calibrated for the SAM2 encoders; 2125 # SAM1 and the VFM encoders keep a batch of one. 2126 from micro_sam.v2.util import SUPPORTED_MODELS 2127 2128 model_type = getattr(self, "model_type", None) 2129 return bool(model_type) and str(model_type)[:6] in SUPPORTED_MODELS 2130 2131 def _effective_batch_size(self): 2132 """The batch size handed to the backend, or None for it to choose one per device. 2133 2134 The displayed value is only a preview (see `_recommended_batch_size`), so while the user has 2135 not edited it the SAM2 backend picks its own value per device, once the weights are placed 2136 there. A value the user typed, or one where batching has no effect, is forwarded verbatim. 2137 """ 2138 if not self._batch_size_has_effect(): 2139 return 1 2140 if self._batch_size_is_auto and self._batch_size_is_tabulated(): 2141 return None 2142 return self.batch_size 2143 2144 def _encoder_job_count(self): 2145 # The number of encoder calls the selected image needs (tiles, z slices, or both), or None 2146 # while no image is selected. Mirrors how the backend splits the input, so the preview is 2147 # never larger than the work. 2148 from bioimage_cpp.utils import Blocking 2149 2150 shape = self._selected_image_shape() 2151 if shape is None: 2152 return None 2153 2154 ndim = self._ndim_override() or len(shape) 2155 n_slices = shape[0] if ndim == 3 else 1 2156 if self.tiling != "yes": 2157 return n_slices 2158 2159 tile_shape, _ = _process_tiling_inputs(self.tile_x, self.tile_y, self.halo_x, self.halo_y) 2160 if tile_shape is None: 2161 return n_slices 2162 in_plane = shape[1:3] if ndim == 3 else shape[:2] 2163 return Blocking([0, 0], list(in_plane), list(tile_shape)).number_of_blocks * n_slices 2164 2165 def _recommended_batch_size(self): 2166 """The batch size the VRAM table suggests here, or one if the model is not tabulated. 2167 2168 This previews what the backend will pick rather than deciding it: it is read before the model 2169 is loaded, and for 'auto' from the default device only, whereas the backend reads every device 2170 it runs on after placing the weights there. It is capped by the total work; the backend also 2171 caps it by the share of that work each device receives. 2172 """ 2173 from micro_sam.v2.util import recommend_batch_size 2174 2175 if not self._batch_size_is_tabulated(): 2176 return 1 2177 2178 device = self.device 2179 if device == "auto": 2180 device = util._get_default_device() 2181 return recommend_batch_size(self.model_type, device, n_jobs=self._encoder_job_count()) 2182 2183 def _on_batch_size_edited(self, value): 2184 # A value the user typed is theirs to keep, so stop tracking the model and device. 2185 self._batch_size_is_auto = False 2186 2187 def _refresh_batch_size(self, index=None): 2188 # Show the field only where it has an effect, and keep its value in step with the model and 2189 # the device unless the user has set it themselves. 2190 self._batch_size_widget.setVisible(self._batch_size_has_effect()) 2191 if not self._batch_size_is_auto: 2192 return 2193 2194 recommended = self._recommended_batch_size() 2195 self.batch_size_param.blockSignals(True) 2196 self.batch_size_param.setValue(recommended) 2197 self.batch_size_param.blockSignals(False) 2198 self.batch_size = recommended 2199 2200 def _apply_default_tiling_for_shape(self, shape): 2201 # Enable tiling by default for large in-plane images, using the central v2 tiling defaults. 2202 # 'shape' is the spatial image shape (channel axis already removed). Shared by the layer-based 2203 # auto-tiling and the batch launcher (which judges from the first file in the folder). 2204 from micro_sam.v2.util import needs_default_tiling, DEFAULT_TILE_SHAPE, DEFAULT_HALO 2205 2206 if shape is not None and needs_default_tiling(shape): 2207 self.tile_x, self.tile_y = DEFAULT_TILE_SHAPE 2208 self.halo_x, self.halo_y = DEFAULT_HALO 2209 self.tile_x_param.setValue(self.tile_x) 2210 self.tile_y_param.setValue(self.tile_y) 2211 self.halo_x_param.setValue(self.halo_x) 2212 self.halo_y_param.setValue(self.halo_y) 2213 self.tiling_dropdown.setCurrentText("yes") 2214 2215 # Refresh which tiling fields are visible now that the image (and its dimensionality) changed. 2216 self._update_tiling_visibility() 2217 2218 def _set_default_tiling(self, *args): 2219 shape = self._selected_image_shape() 2220 if shape is not None: 2221 self._apply_default_tiling_for_shape(shape) 2222 2223 def _reset_inputs_to_defaults(self): 2224 """Reset the user inputs to their fresh-open defaults. 2225 2226 Called when the selected image changes, so a new image starts exactly as a freshly opened 2227 tool would: the default model family/size, no custom weights, default tiling parameters and 2228 no embeddings save path. The auto-tiling rule for the new image is re-applied at the end via 2229 '_set_default_tiling' (which also refreshes field visibility), matching a fresh open. 2230 """ 2231 # Clear custom weights first, then restore the default model family + size. (Setting custom 2232 # weights blanks the family dropdown, so clearing it before re-selecting keeps them in sync.) 2233 self.custom_weights_param.setText("") 2234 default_family = {v: k for k, v in self.supported_dropdown_maps.items()}[self._default_model_choice[5:]] 2235 default_size = self._model_size_map[self._default_model_choice[4]] 2236 self.model_family_dropdown.setCurrentText(default_family) 2237 self.model_size_dropdown.setCurrentText(default_size) 2238 2239 # Reset the in-plane tiling parameters to their creation defaults and the save path. Then 2240 # '_set_default_tiling' decides the on or off state (auto-enabled for large images, as on a fresh open). 2241 from micro_sam.v2.util import DEFAULT_TILE_SHAPE, DEFAULT_HALO 2242 self.tile_x_param.setValue(DEFAULT_TILE_SHAPE[0]) 2243 self.tile_y_param.setValue(DEFAULT_TILE_SHAPE[1]) 2244 self.halo_x_param.setValue(DEFAULT_HALO[0]) 2245 self.halo_y_param.setValue(DEFAULT_HALO[1]) 2246 self.tiling_dropdown.setCurrentText("no") 2247 self._batch_size_is_auto = True 2248 self._refresh_batch_size() 2249 self.embeddings_save_path_param.setText("") 2250 2251 # Reset the image-dimensionality override back to 'auto' so a new image is re-detected. 2252 # Block the signal so this does not re-trigger the annotator's normalization mid-reset. 2253 if getattr(self, "ndim_choice", False): 2254 self.image_ndim_dropdown.blockSignals(True) 2255 self.image_ndim_dropdown.setCurrentText("auto") 2256 self.image_ndim_mode = "auto" 2257 self.image_ndim_dropdown.blockSignals(False) 2258 2259 self._set_default_tiling() 2260 2261 def _validate_inputs(self): 2262 """Validates the inputs for the annotation process and returns a dictionary 2263 containing information for message generation, or False if no messages are needed. 2264 2265 This function performs the following checks: 2266 2267 - If an `embeddings_save_path` is provided: 2268 - Validates the image data signature by comparing it with the signature 2269 of the image data in the viewer's selection. 2270 - Checks for existing embeddings at the specified path. 2271 - If existing embeddings are found, it attempts to load parameters 2272 like tile shape, halo, and model type from the Zarr attributes. 2273 - An informational message is generated based on the loaded parameters. 2274 - If loading existing embeddings fails, an error message is generated. 2275 - If no existing embeddings are found, an informational message is generated. 2276 - If no `embeddings_save_path` is provided, the function returns None. 2277 2278 Returns: 2279 bool: True if the computation should be aborted, otherwise False. 2280 """ 2281 2282 # Check if we have an existing input image to compute the embeddings. 2283 image = self.image_selection.get_value() 2284 if image is None: 2285 return _generate_message("error", "No image has been selected.") 2286 2287 # Check if we have an existing embedding path. 2288 # If yes we check the data signature of these embeddings against the selected image 2289 # and we ask the user if they want to load these embeddings. 2290 if ( 2291 self.embeddings_save_path and os.path.isdir(self.embeddings_save_path) 2292 and os.listdir(self.embeddings_save_path) 2293 ): 2294 try: 2295 f = util._open_embeddings(self.embeddings_save_path, mode="a") 2296 2297 # Validate that the embeddings are complete. 2298 # Note: 'input_size' is the last value set in the attrs of f, 2299 # so we can use it as a proxy to check if the embeddings are fully computed 2300 if "input_size" not in f.attrs: 2301 msg = ( 2302 f"The embeddings at {self.embeddings_save_path} are incomplete. " 2303 "Specify a different path or remove them." 2304 ) 2305 return _generate_message("error", msg) 2306 2307 # Validate image data signature. 2308 if "data_signature" in f.attrs: 2309 image = self.image_selection.get_value() 2310 img_signature = util._compute_data_signature(image.data) 2311 if img_signature != f.attrs["data_signature"]: 2312 msg = f"The embeddings don't match with the image: {img_signature} {f.attrs['data_signature']}" 2313 return _generate_message("error", msg) 2314 2315 # The model the saved embeddings were computed with. 2316 saved_model = f.attrs.get("model_name") or f.attrs.get("model_type") 2317 if saved_model is None: 2318 return _generate_message( 2319 "error", f"The embeddings at '{self.embeddings_save_path}' do not record a model." 2320 ) 2321 2322 # Ask the user whether to load the saved embeddings or recompute them. The message 2323 # reflects what changed vs the saved embeddings: a model swap, custom weights (whose 2324 # identity we cannot verify here, so always flag them), or an exact match. 2325 if self.custom_weights: 2326 message = ( 2327 f"Saved embeddings use '{saved_model}'; custom weights are now selected. " 2328 "Load the saved embeddings or recompute?" 2329 ) 2330 elif saved_model != self.model_type: 2331 message = ( 2332 f"Saved embeddings use '{saved_model}', but '{self.model_type}' is selected. " 2333 "Load the saved embeddings or recompute?" 2334 ) 2335 else: 2336 message = f"Embeddings for '{saved_model}' already exist. Load or recompute?" 2337 choice = _ask_load_or_recompute(message) 2338 2339 if choice == "cancel": 2340 return True 2341 2342 if choice == "recompute": 2343 # Recompute with the user's current selection: clear the saved file so the backend 2344 # recomputes from scratch (works for any model and even when the model is unchanged). 2345 # Tiling and model stay as the user set them in the widget. 2346 util._open_embeddings(self.embeddings_save_path, mode="w") 2347 return False 2348 2349 # 'load': adopt the saved model and tiling, then load the existing embeddings. Clear any 2350 # custom weights so the predictor matches the loaded embeddings ('saved_model'), not a 2351 # mismatched custom checkpoint. 2352 self.custom_weights = None 2353 self.custom_weights_param.setText("") 2354 self.model_type = saved_model 2355 if self._validate_model_support(): 2356 return True 2357 # Reflect the loaded model in the model family / size dropdowns. 2358 self._apply_loaded_model_selection(saved_model) 2359 if "tile_shape" in f.attrs and f.attrs["tile_shape"] is not None: 2360 self.tile_x, self.tile_y = f.attrs["tile_shape"] 2361 self.halo_x, self.halo_y = f.attrs["halo"] 2362 # Reflect the loaded tiling parameters in the UI. 2363 self.tile_x_param.setValue(self.tile_x) 2364 self.tile_y_param.setValue(self.tile_y) 2365 self.halo_x_param.setValue(self.halo_x) 2366 self.halo_y_param.setValue(self.halo_y) 2367 self.tiling_dropdown.setCurrentText("yes") 2368 else: 2369 self.tiling_dropdown.setCurrentText("no") 2370 return False 2371 2372 except RuntimeError as e: 2373 val_results = { 2374 "message_type": "error", 2375 "message": f"Failed to load image embeddings: {e}", 2376 } 2377 return _generate_message( 2378 val_results["message_type"], val_results["message"] 2379 ) 2380 2381 # Otherwise we either don't have an embedding path or it is empty. We can proceed in both cases. 2382 return False 2383 2384 def _validate_existing_embeddings(self, state): 2385 # When an embeddings save path is set, '_validate_inputs' already offered load-vs-recompute, 2386 # so don't prompt again here. This only handles the in-memory case (no save path). 2387 if self.embeddings_save_path: 2388 return False 2389 if state.image_embeddings is None: 2390 return False 2391 return _generate_message( 2392 "info", "Embeddings have already been precomputed. Press OK to recompute the embeddings." 2393 ) 2394 2395 @staticmethod 2396 def _clear_autosegment_cache(state): 2397 """Discard predictions derived from the embeddings that were just replaced.""" 2398 widget = state.widgets.get("autosegment") 2399 if widget is not None: 2400 widget._release_segmenter() 2401 widget._drop_decoder_state() 2402 2403 def _n_tiles(self, tile_shape, shape): 2404 """The number of tiles the embedding computation is split into (1 without tiling).""" 2405 if tile_shape is None: 2406 return 1 2407 from bioimage_cpp.utils import Blocking 2408 return Blocking([0, 0], list(shape[:2]), list(tile_shape)).number_of_blocks 2409 2410 def _maybe_warn_cpu(self, ndim, tile_shape, shape): 2411 """Show a one-time-per-session info popup for CPU computations. 2412 2413 The popup appears for expensive CPU computations (many tiles or 3D), and always when the computer 2414 has an NVIDIA GPU that PyTorch cannot use. 2415 """ 2416 state = AnnotatorState() 2417 if state.cpu_info_shown or not self.warn_on_cpu: 2418 return 2419 if str(util.get_device(self.device)) != "cpu": 2420 return 2421 gpu_warning = util.get_gpu_setup_warning() 2422 if gpu_warning is not None: 2423 state.cpu_info_shown = True 2424 QtWidgets.QMessageBox.warning(self, "GPU not used", gpu_warning, QtWidgets.QMessageBox.Ok) 2425 return 2426 # 3D runs the encoder per slice. 2D is a single pass per tile, which only adds up for many tiles. 2427 if ndim < 3 and self._n_tiles(tile_shape, shape) < self.cpu_warn_tiles: 2428 return 2429 state.cpu_info_shown = True 2430 data_kind = "timeseries" if self.is_timeseries else "3D" # A timeseries uses the 3D compute path. 2431 QtWidgets.QMessageBox.information( 2432 self, "Running on CPU", 2433 f"micro_sam runs on the CPU, so computations can be slow for tiled or {data_kind} data. " 2434 "Using a GPU is recommended.", 2435 QtWidgets.QMessageBox.Ok, 2436 ) 2437 2438 def __call__(self, skip_validate=False): 2439 self._validate_model_type_and_custom_weights() 2440 if self._validate_model_support(): 2441 return 2442 2443 # For gated advanced (DINO / UNI) models, check the backend package + HuggingFace access. 2444 if self._validate_vfm_requirements(): 2445 return 2446 2447 # Validate user inputs. 2448 if not skip_validate and self._validate_inputs(): 2449 return 2450 2451 # Get the image. 2452 image = self.image_selection.get_value() 2453 2454 # Update the image embeddings: 2455 state = AnnotatorState() 2456 if self._validate_existing_embeddings(state): 2457 # Whether embeddings already exist to control existing objects in layers. 2458 state.skip_recomputing_embeddings = True 2459 return 2460 2461 state.skip_recomputing_embeddings = False 2462 # Reset the state. 2463 state.reset_state() 2464 2465 # Get image dimensions. 2466 state.image_shape = self._selected_image_shape() 2467 ndim = len(state.image_shape) 2468 state.ndim = ndim 2469 2470 # The image is set only now, after the validation, so a cancel keeps the state of the current image. 2471 state.image_scale = tuple(image.scale) 2472 state.image_name = image.name 2473 2474 # Process tile_shape and halo, set other data. Tiling is only applied when enabled. 2475 if self.tiling == "yes": 2476 tile_shape, halo = _process_tiling_inputs( 2477 self.tile_x, self.tile_y, self.halo_x, self.halo_y 2478 ) 2479 # Reflect the values actually used (after normalization) back in the UI so they are retained. 2480 if tile_shape is not None: 2481 self.tile_x, self.tile_y = tile_shape 2482 self.tile_x_param.setValue(self.tile_x) 2483 self.tile_y_param.setValue(self.tile_y) 2484 if halo is not None: 2485 self.halo_x, self.halo_y = halo 2486 self.halo_x_param.setValue(self.halo_x) 2487 self.halo_y_param.setValue(self.halo_y) 2488 else: 2489 tile_shape, halo = None, None 2490 save_path = ( 2491 None 2492 if self.embeddings_save_path == "" 2493 else self.embeddings_save_path 2494 ) 2495 image_data = image.data 2496 2497 # Warn CPU users once per session that processing can be slow. 2498 self._maybe_warn_cpu(ndim, tile_shape, state.image_shape) 2499 2500 # Eager caching of the automatic-segmentation state: if the 'cache automatic segmentation state' 2501 # option (in these embedding settings) is on, precompute the state to disk while computing the 2502 # embeddings. It persists wherever the embeddings live on disk - the given save path, or the 2503 # ephemeral zarr the eager setup creates for SAM2 volumes / tiled images (removed on reset). 2504 # Plain in-memory 2d has no disk location, so it needs a save path to persist. 2505 is_sam2 = self.model_type.startswith("hvit") 2506 embeddings_on_disk = save_path is not None or (is_sam2 and (ndim == 3 or tile_shape is not None)) 2507 precompute_autoseg_state = self.cache_state and embeddings_on_disk 2508 if self.cache_state and not embeddings_on_disk: 2509 show_info("Set an embeddings save path to cache the automatic segmentation state.") 2510 2511 # Set up progress bar and signals for using it within a threadworker. 2512 # Model and decoder preparation happens before the backend knows the tile / slice count, so 2513 # start with an indeterminate status instead of leaving napari's activity display empty. 2514 pbar, pbar_signals = _create_pbar_for_threadworker("Computing image embeddings") 2515 2516 # @thread_worker() 2517 def compute_image_embedding(): 2518 2519 # The computation runs synchronously on the main thread, so pump the Qt event loop on 2520 # every progress step. Otherwise the napari progress bar only repaints once at the end 2521 # (it just jumps to 100%). This matters most for tiled embeddings (many tiles or slices). 2522 def pbar_init(total, description): 2523 if self.is_timeseries: # A timeseries goes through the 3D compute path; relabel it. 2524 description = description.replace("3D", "Timeseries") 2525 # Reset the counter to 0 so each phase starts fresh: the embeddings, then (when caching 2526 # is on) the automatic-segmentation state precompute reuse the same bar, and without a 2527 # reset the second phase inherits the first's completed count and sits stuck at full. 2528 pbar_signals.pbar_reset.emit() 2529 pbar_signals.pbar_total.emit(total) 2530 pbar_signals.pbar_description.emit(description) 2531 QtWidgets.QApplication.processEvents() 2532 2533 def pbar_update(update): 2534 pbar_signals.pbar_update.emit(update) 2535 QtWidgets.QApplication.processEvents() 2536 2537 state.initialize_predictor( 2538 image_data, 2539 model_type=self.model_type, 2540 save_path=save_path, 2541 ndim=ndim, 2542 device=self.device, 2543 checkpoint_path=self.custom_weights, 2544 tile_shape=tile_shape, 2545 halo=halo, 2546 batch_size=self._effective_batch_size(), 2547 prefer_decoder=True, 2548 precompute_autoseg_state=precompute_autoseg_state, 2549 pbar_init=pbar_init, 2550 pbar_update=pbar_update, 2551 ) 2552 pbar_signals.pbar_stop.emit() 2553 2554 compute_image_embedding() 2555 self._clear_autosegment_cache(state) 2556 self._update_model(state) 2557 # worker = compute_image_embedding() 2558 # worker.returned.connect(self._update_model) 2559 # worker.start() 2560 # return worker 2561 2562 2563class ClassificationEmbeddingWidget(EmbeddingWidget): 2564 """Embedding widget for the classification tools (pixel and object classification). 2565 2566 The model selection mirrors the segmentation/tracking `EmbeddingWidget` exactly: the same single 2567 'Model:' dropdown with the SAM2 'Natural Images' and 'Microscopy' families (same names and config). 2568 Since classification operates directly on the image-encoder embeddings, it can additionally use 2569 models beyond SAM2. An opt-in 'Advanced Models' checkbox in the embedding settings swaps that one 2570 dropdown to the advanced families instead of adding a second dropdown. The advanced tier holds both 2571 the SAM1 families and the VFM (DINO / UNI) families (`_advanced_family_suffixes` and `_dino_families`). 2572 """ 2573 2574 # The classification tools have no automatic segmentation, so the state-caching option is hidden. 2575 supports_state_caching = False 2576 2577 size_order = ["tiny", "small", "base", "large", "huge", "giant"] 2578 2579 # The classifiers only run the image encoder and a lightweight classifier on top, so they stay 2580 # fast on the CPU and don't need the info popup. 2581 warn_on_cpu = False 2582 2583 # Advanced SAM1 families: UI label -> model-name suffix on the SAM1 'vit_' prefix, resolved in 2584 # '_get_model_size_options'. 2585 _advanced_family_suffixes = { 2586 "Natural Images (SAM1)": "", 2587 "Light Microscopy (µSAM)": "_lm", 2588 "Electron Microscopy (µSAM)": "_em_organelles", 2589 "Medical Imaging (MedicoSAM)": "_medical_imaging", 2590 "Histopathology (PathoSAM)": "_histopathology", 2591 } 2592 _advanced_size_map = {"t": "tiny", "b": "base", "l": "large", "h": "huge"} 2593 # Vision Foundation Model families beyond SAM: UI label -> the registry model_types in that family 2594 # (ordered by size). Sizes/names come from 'micro_sam.models.vfm.VFM_MODELS'/'VFM_SIZE_LABELS', not the 2595 # SAM1 naming scheme. DINOv2/v3 are natural-image (LVD-1689M) models. UNI/UNI2-h are histopathology. 2596 _dino_families = { 2597 "Natural Images (DINOv2)": ("vit_s_dinov2", "vit_b_dinov2", "vit_l_dinov2", "vit_g_dinov2"), 2598 "Natural Images (DINOv3)": ("vit_s_dinov3", "vit_b_dinov3", "vit_l_dinov3"), 2599 "Histopathology (UNI)": ("vit_uni", "vit_univ2"), 2600 "Natural Images (SAM3)": ("vit_sam3",), 2601 } 2602 # Older saved classifiers stored the primary SAM2 families under '(SAM2)' labels. Map them to the 2603 # current names so loading such a classifier still restores the right family. 2604 _primary_family_aliases = {"Natural Images (SAM2)": "Natural Images", "Microscopy (SAM2)": "Microscopy"} 2605 2606 def _all_advanced_families(self): 2607 # The advanced tier combines the SAM1 families and the VFM (DINO / UNI) families. 2608 return list(self._advanced_family_suffixes) + list(self._dino_families) 2609 2610 def _is_dino_active(self): 2611 return getattr(self, "model_family", None) in self._dino_families 2612 2613 def _advanced_active(self): 2614 # The single 'Model:' dropdown holds either the primary or the advanced families, so the 2615 # current family's membership is the source of truth (robust to the dropdown being blanked). 2616 return getattr(self, "model_family", None) in self._all_advanced_families() 2617 2618 def _add_extra_model_settings(self, layout): 2619 # 'Advanced Models' swaps the single 'Model:' dropdown above between the primary (SAM2) and the 2620 # advanced (SAM1) families - one dropdown only, to avoid confusion. Added last in the settings. 2621 self._primary_families = list(self.supported_dropdown_maps.keys()) 2622 # The default primary family ('Microscopy'), restored when advanced is switched back off. 2623 self._default_primary_family = self.model_family 2624 self.advanced = False 2625 self.advanced_checkbox = self._add_boolean_param( 2626 "advanced", self.advanced, title="Advanced Models", 2627 tooltip=get_tooltip("embedding", "advanced_model"), 2628 ) 2629 self.advanced_checkbox.stateChanged.connect(self._on_advanced_toggled) 2630 layout.addWidget(self.advanced_checkbox) 2631 2632 # The inherited dropdowns auto-bind their attribute by indexing the option list captured at 2633 # creation. We swap those lists (the families, and the per-family sizes), which makes the 2634 # captured index stale (wrong value, or out of range). Drop that auto-bind and let 2635 # '_update_model_type' (wired to 'currentTextChanged') sync the attribute from the text. 2636 for dropdown in (self.model_family_dropdown, self.model_size_dropdown): 2637 try: 2638 dropdown.currentIndexChanged.disconnect() 2639 except TypeError: 2640 pass 2641 2642 def _set_family_choices(self, families, select=None): 2643 # Replace the 'Model:' dropdown items, select 'select' (default first), then resolve the model. 2644 if select not in families: 2645 select = families[0] 2646 self.model_family_dropdown.blockSignals(True) 2647 self.model_family_dropdown.clear() 2648 self.model_family_dropdown.addItems(families) 2649 self.model_family_dropdown.setCurrentText(select) 2650 self.model_family_dropdown.blockSignals(False) 2651 self.model_family = select 2652 self._update_model_type() 2653 2654 def _on_advanced_toggled(self, state): 2655 advanced = self.advanced_checkbox.isChecked() 2656 if advanced: 2657 self._set_family_choices(self._all_advanced_families()) 2658 else: # Back to the SAM2 families, defaulting to 'Microscopy' rather than the first entry. 2659 self._set_family_choices(self._primary_families, select=self._default_primary_family) 2660 # Reflect the active tier in the 'Model:' dropdown tooltip. 2661 self.model_family_dropdown.setToolTip( 2662 get_tooltip("embedding", "model_family_advanced" if advanced else "model_family") 2663 ) 2664 2665 def _reset_inputs_to_defaults(self): 2666 # Turning off advanced mode restores the primary families. The base reset then selects the default. 2667 if getattr(self, "advanced_checkbox", None) is not None and self.advanced_checkbox.isChecked(): 2668 self.advanced_checkbox.setChecked(False) 2669 super()._reset_inputs_to_defaults() 2670 2671 def set_model_family_size(self, family, size): 2672 """Restore a saved (family, size): swap the dropdown to the matching tier, then select it.""" 2673 family = self._primary_family_aliases.get(family, family) 2674 self.advanced_checkbox.setChecked(family in self._all_advanced_families()) 2675 self.model_family_dropdown.setCurrentText(family) 2676 if size: 2677 self.model_size_dropdown.setCurrentText(size) 2678 2679 def _validate_model_support(self): 2680 # The vit-tiny backbone needs MobileSAM. Warn (instead of crashing later) if it is selected 2681 # without MobileSAM installed. The model stays selectable - we just block this compute. 2682 from ..util import VIT_T_SUPPORT 2683 if not VIT_T_SUPPORT and (self.model_type or "").startswith("vit_t"): 2684 return _generate_message( 2685 "error", 2686 f"'{self.model_type}' (vit-tiny) requires MobileSAM. Install MobileSAM or pick another size.", 2687 ) 2688 return False 2689 2690 def _family_and_size_for_model(self, model_name): 2691 """Map a stored model name to its (family label, size label) for this widget's dropdowns.""" 2692 full_size_map = {"t": "tiny", "s": "small", "b": "base", "l": "large", "h": "huge"} 2693 for family, models in self._dino_families.items(): # VFM families (DINO / UNI). 2694 if model_name in models: 2695 from ..models.vfm import VFM_SIZE_LABELS 2696 return family, VFM_SIZE_LABELS.get(model_name) 2697 if model_name.startswith("hvit_"): # SAM2 (primary families). 2698 size = full_size_map.get(model_name[5]) 2699 family = self._family_for_sam2_model(model_name) 2700 else: # SAM1 (advanced families): 'vit_<size><suffix>'. 2701 size = full_size_map.get(model_name[4]) 2702 suffix = model_name[5:] 2703 family = {v: k for k, v in self._advanced_family_suffixes.items()}.get(suffix, "Natural Images (SAM1)") 2704 return family, size 2705 2706 def _apply_loaded_model_selection(self, model_name): 2707 # Set the family (primary or advanced) and size dropdowns to match the loaded embeddings. 2708 family, size = self._family_and_size_for_model(model_name) 2709 self.set_model_family_size(family, size) 2710 2711 def _get_model_size_options(self): 2712 # Primary (SAM2) sizes come from the inherited logic. Advanced families resolve to SAM1/DINO names. 2713 if not self._advanced_active(): 2714 return super()._get_model_size_options() 2715 if self._is_dino_active(): 2716 from ..models.vfm import VFM_SIZE_LABELS 2717 models = self._dino_families[self.model_family] 2718 self.model_size_mapping = {VFM_SIZE_LABELS[m]: m for m in models} 2719 self.model_size_options = sorted(self.model_size_mapping.keys(), key=self.size_order.index) 2720 return 2721 from ..v1.util import get_model_names 2722 suffix = self._advanced_family_suffixes[self.model_family] 2723 available = {m for m in get_model_names() if not m.endswith("decoder")} 2724 self.model_size_mapping = {} 2725 for key, label in self._advanced_size_map.items(): 2726 name = f"vit_{key}{suffix}" 2727 if name in available: 2728 self.model_size_mapping[label] = name 2729 self.model_size_options = sorted(self.model_size_mapping.keys(), key=self.size_order.index) 2730 2731 def _update_model_type(self): 2732 # Sync the family from the dropdown first: the inherited auto-bind closure captures the original 2733 # (primary) option list, so after the dropdown is swapped to the advanced families it can set a 2734 # stale value. Re-reading the current text here is authoritative and decides the branch below. 2735 self.model_family = self.model_family_dropdown.currentText() or self.model_family 2736 # Primary mode defers to the inherited SAM2 logic. Advanced mode rebuilds the size dropdown for 2737 # the current SAM1 family and resolves its model name. 2738 if not self._advanced_active(): 2739 return super()._update_model_type() 2740 current_selection = self.model_size_dropdown.currentText() 2741 self._get_model_size_options() 2742 2743 self.model_size_dropdown.blockSignals(True) 2744 self.model_size_dropdown.clear() 2745 self.model_size_dropdown.addItems(self.model_size_options) 2746 if current_selection in self.model_size_options: 2747 self.model_size = current_selection 2748 elif self.model_size_options: 2749 self.model_size = self.model_size_options[0] 2750 self.model_type = self.model_size_mapping.get(self.model_size) 2751 self.model_size_dropdown.setCurrentText(self.model_size) 2752 self.model_size_dropdown.update() 2753 self.model_size_dropdown.blockSignals(False) 2754 # This branch does not go through the inherited update, so refresh the batch size here too: 2755 # the advanced families include the VFM encoders, which do not support batching. 2756 if getattr(self, "_batch_size_widget", None) is not None: 2757 self._refresh_batch_size() 2758 2759 def _validate_model_type_and_custom_weights(self): 2760 # DINO families always resolve from the registry. DINOv3 weights load from HuggingFace using the 2761 # user's own HF access (huggingface-cli login / HF_TOKEN), not the custom-weights field. 2762 if self._is_dino_active(): 2763 self._get_model_size_options() 2764 self.model_type = self.model_size_mapping.get(self.model_size, self.model_type) 2765 return 2766 # Advanced SAM1 mode (without custom weights): resolve the SAM1 model name from family + size. 2767 if self._advanced_active() and not self.custom_weights: 2768 self._get_model_size_options() 2769 self.model_type = self.model_size_mapping.get(self.model_size, self.model_type) 2770 return 2771 # Primary mode, or custom weights: the inherited logic resolves the type and blanks the dropdown. 2772 super()._validate_model_type_and_custom_weights() 2773 2774 2775# 2776# Functionality and widget for nd segmentation. 2777# 2778 2779 2780def _division_frame_for_track(point_layer, track_id): 2781 """Frame at which 'track_id' is annotated to divide, or None. 2782 2783 A division is a point tagged with the 'division' track-state for this track; the earliest such 2784 frame is the mother track's last frame (propagation is bounded above there). 2785 """ 2786 props = point_layer.properties 2787 if not len(point_layer.data) or "state" not in props or "track_id" not in props: 2788 return None 2789 states = np.asarray(props["state"]) 2790 track_ids_prop = np.asarray(props["track_id"]) 2791 z_all = np.round(point_layer.data[:, 0]).astype(int) 2792 div_mask = (states == "division") & (track_ids_prop == str(track_id)) 2793 return int(z_all[div_mask].min()) if np.any(div_mask) else None 2794 2795 2796def _mother_division_frame(point_layer, lineage, track_id): 2797 """Division frame of 'track_id's mother, or None if it is not a daughter of a dividing track. 2798 2799 A daughter does not exist before its mother divides, so its mask must start the frame after. 2800 """ 2801 for mother, daughters in lineage.items(): 2802 if track_id in daughters: 2803 return _division_frame_for_track(point_layer, mother) 2804 return None 2805 2806 2807def _update_lineage(viewer, mother=None): 2808 """Record a division for 'mother' by seeding two daughter track ids and refreshing the menus. 2809 2810 Args: 2811 viewer: The napari viewer. 2812 mother: The track id that divides. Defaults to the current track id. 2813 """ 2814 state = AnnotatorState() 2815 tracking_widget = state.annotator._tracking_widget 2816 2817 if mother is None: 2818 mother = state.current_track_id 2819 # Only seed daughters once per division: skip unknown tracks or tracks that already divided. 2820 if mother not in state.lineage or len(state.lineage[mother]) > 0: 2821 return 2822 2823 daughter1 = max(state.lineage.keys()) + 1 2824 daughter2 = daughter1 + 1 2825 state.lineage[mother] = [daughter1, daughter2] 2826 state.lineage[daughter1] = [] 2827 state.lineage[daughter2] = [] 2828 2829 # Update the choices in the track_id menu so that it contains the new track ids. 2830 # (index 2: prompt, track_state, track_id). 2831 track_ids = list(map(str, state.lineage.keys())) 2832 tracking_widget[2].choices = track_ids 2833 2834 viewer.layers["point_prompts"].property_choices["track_id"] = list(track_ids) 2835 viewer.layers["prompts"].property_choices["track_id"] = list(track_ids) 2836 2837 2838class UnifiedSegmentWidget(_WidgetBase): 2839 """Unified widget for 3D segmentation (per-slice and volumetric). 2840 """ 2841 2842 def __init__(self, viewer, tracking=False, parent=None): 2843 """Initialize the unified segmentation widget. 2844 2845 Args: 2846 viewer: The napari viewer. 2847 tracking: Whether this is used for tracking (vs volumetric). 2848 parent: Parent Qt widget. 2849 """ 2850 super().__init__(parent=parent) 2851 self._viewer = viewer 2852 self.tracking = tracking 2853 2854 # Initialize volume mode state 2855 self.apply_to_volume = False 2856 2857 # The progress bar pumps the Qt event loop, so a key press during a run would start a nested one. 2858 self.is_running = False 2859 # The key and result of the last volume propagation, so a re-press without changes reuses it. 2860 self._last_volume_run = None 2861 2862 # Create the widget UI 2863 self._create_widget() 2864 2865 def _create_widget(self): 2866 """Create the widget UI elements.""" 2867 # 1. Add volume mode checkbox 2868 volume_title = ( 2869 "Apply to All Frames" if self.tracking else "Apply to Volume" 2870 ) 2871 self.volume_checkbox = self._add_boolean_param( 2872 "apply_to_volume", 2873 self.apply_to_volume, 2874 title=volume_title, 2875 tooltip=get_tooltip("unified_segment", "apply_to_volume"), 2876 ) 2877 self.volume_checkbox.stateChanged.connect(self._on_volume_mode_changed) 2878 self.layout().addWidget(self.volume_checkbox) 2879 2880 # 2. Add the batched checkbox. It stays hidden until the embeddings exist and are not tiled. 2881 self.batched = False 2882 self.batched_checkbox = self._add_boolean_param( 2883 "batched", 2884 self.batched, 2885 title="Batched", 2886 tooltip=get_tooltip("unified_segment", "batched"), 2887 ) 2888 self.batched_checkbox.setVisible(False) # Initially hidden 2889 self.layout().addWidget(self.batched_checkbox) 2890 2891 # 3. Store the settings for volume propagation. The InteractiveSegmentationWidget shows the controls. 2892 # 'early_stop_patience': the number of empty slices after which propagation stops (0 disables it). 2893 # 'z_range': the inclusive (z_min, z_max) range for propagation, or None for the full volume. 2894 self.early_stop_patience = 2 2895 self.z_range = None 2896 2897 # 4. Add run button 2898 self.run_button = QtWidgets.QPushButton(self._get_button_text()) 2899 self.run_button.setToolTip(get_tooltip("unified_segment", "segment_button")) 2900 self.run_button.clicked.connect(self.__call__) 2901 self.layout().addWidget(self.run_button) 2902 2903 # 5. Set the visibility of the batched checkbox. 2904 self._update_batched_visibility() 2905 2906 def _on_volume_mode_changed(self, state): 2907 """Handle volume mode checkbox state change. 2908 2909 Args: 2910 state: Qt checkbox state (0=unchecked, 2=checked). 2911 """ 2912 # Update button text 2913 self.run_button.setText(self._get_button_text()) 2914 2915 # Update batched checkbox visibility 2916 self._update_batched_visibility() 2917 2918 def _update_batched_visibility(self): 2919 """Show the batched checkbox only for computed embeddings that are not tiled.""" 2920 state = AnnotatorState() 2921 2922 # Batched prompts do not work with tiled embeddings. They work in the slice and in the volume mode. 2923 should_show = state.image_embeddings is not None and not _embeddings_are_tiled(state) 2924 if not should_show and getattr(self, "batched", False): 2925 self.batched_checkbox.setChecked(False) 2926 self.batched_checkbox.setVisible(should_show) 2927 2928 def _get_button_text(self): 2929 """Get dynamic button text based on current mode.""" 2930 if self.tracking: 2931 return ( 2932 "Segment All Frames [S]" 2933 if self.apply_to_volume 2934 else "Segment Frame [S]" 2935 ) 2936 else: 2937 return ( 2938 "Segment Volume [S]" 2939 if self.apply_to_volume 2940 else "Segment Slice [S]" 2941 ) 2942 2943 def __call__(self, viewer=None): 2944 """Execute segmentation based on current mode. 2945 2946 Args: 2947 viewer: Optional napari viewer (for keybinding compatibility). 2948 """ 2949 if self.is_running: 2950 show_info("The segmentation is still running. Wait until it finishes.") 2951 return None 2952 2953 # Validation 2954 if _validate_embeddings(self._viewer): 2955 return None 2956 if _validate_layers(self._viewer): 2957 return None 2958 2959 self.is_running = True 2960 try: 2961 # Route to appropriate implementation 2962 if self.apply_to_volume: 2963 if self.tracking: 2964 return self._run_tracking() 2965 else: 2966 return self._run_volumetric_segmentation() 2967 else: 2968 if self.tracking: 2969 return self._run_frame_segmentation() 2970 else: 2971 return self._run_slice_segmentation() 2972 finally: 2973 self.is_running = False 2974 2975 def reset_last_volume_run(self): 2976 """Forget the last volume propagation, so the next run propagates again.""" 2977 self._last_volume_run = None 2978 2979 def _run_slice_segmentation(self): 2980 """Execute per-slice segmentation. 2981 """ 2982 shape = self._viewer.layers["current_object"].data.shape[1:] 2983 2984 z = vutil.current_slice(self._viewer, self._viewer.layers["point_prompts"]) 2985 2986 prompt_layer = self._viewer.layers["prompts"] 2987 prompts = vutil.collect_frame_prompts( 2988 self._viewer.layers["point_prompts"], prompt_layer, shape, i=z, 2989 ) 2990 # this is a stop prompt, we do nothing 2991 if prompts.is_stop: 2992 return 2993 2994 points, labels, boxes, masks = prompts.points, prompts.labels, prompts.boxes, prompts.masks 2995 have_scribbles = prompts.have_scribbles 2996 if have_scribbles and not boxes and not np.any(labels == 1): 2997 return _generate_message( 2998 "error", 2999 "A negative scribble needs a positive point, positive scribble, box or mask prompt.", 3000 ) 3001 3002 state = AnnotatorState() 3003 batched = _batched_disabled_when_tiled(state, bool(self.batched)) 3004 if have_scribbles and batched: 3005 show_info( 3006 "Batched segmentation is not supported with scribble prompts. " 3007 "It runs single-object segmentation instead." 3008 ) 3009 batched = False 3010 3011 boxes = [box[[1, 0, 3, 2]] for box in boxes] 3012 if batched: 3013 seg = self._segment_slice_batched(z, points, labels, boxes, masks, shape) 3014 else: 3015 seg = state.interactive_segmenter.segment_slice( 3016 frame_idx=z, 3017 points=points[:, ::-1].copy(), 3018 labels=labels, 3019 boxes=boxes, 3020 masks=masks, 3021 ) 3022 3023 # No prompts were given or prompts were invalid, skip segmentation. 3024 if seg is None: 3025 print( 3026 "You either haven't provided any prompts or invalid prompts. The segmentation will be skipped." 3027 ) 3028 return 3029 3030 self._viewer.layers["current_object"].data[z] = seg 3031 self._viewer.layers["current_object"].refresh() 3032 3033 def _segment_slice_batched(self, z, points, labels, boxes, masks, shape): 3034 """Batched multi-object segmentation for a single slice with SAM2. 3035 3036 Mirrors the 2d batched convention: one object per positive point (each combined with the 3037 shared negative points) and one object per box. A box from a polygon/ellipse (its entry in 3038 `masks` is not None) also carries its soft mask cue. The boxes are expected in the reordered 3039 layout used by `segment_slice`. 3040 """ 3041 state = AnnotatorState() 3042 points = np.zeros((0, 2)) if points is None else np.asarray(points) 3043 labels = np.zeros((0,), dtype=int) if labels is None else np.asarray(labels) 3044 positive_points = points[labels == 1] 3045 negative_points = points[labels != 1] 3046 n_neg = len(negative_points) 3047 3048 seg = np.zeros(tuple(shape), dtype="uint32") 3049 object_id = 0 3050 3051 # One object per positive point, each combined with the shared negative points. 3052 for pos in positive_points: 3053 pts = np.concatenate([pos[None], negative_points], axis=0) if n_neg else pos[None] 3054 lbs = np.concatenate([[1], np.zeros(n_neg, dtype=int)]) if n_neg else np.array([1]) 3055 object_id += 1 3056 mask = state.interactive_segmenter.segment_slice( 3057 frame_idx=z, points=pts[:, ::-1].copy(), labels=lbs, object_id=object_id, 3058 ) 3059 if mask is not None: 3060 seg[mask > 0] = object_id 3061 3062 # One object per box (with its mask cue if it is a polygon/ellipse), each combined with the 3063 # shared negative points. 3064 for bidx, box in enumerate(boxes): 3065 neg = negative_points[:, ::-1].copy() if n_neg else None 3066 neg_labels = np.zeros(n_neg, dtype=int) if n_neg else None 3067 object_id += 1 3068 mask = state.interactive_segmenter.segment_slice( 3069 frame_idx=z, points=neg, labels=neg_labels, boxes=[box], 3070 masks=[masks[bidx]] if masks is not None else None, object_id=object_id, 3071 ) 3072 if mask is not None: 3073 seg[mask > 0] = object_id 3074 3075 return seg 3076 3077 def _segment_track_on_frame(self, state, t, track_id, shape): 3078 """Segment a single track's object on frame 't'. Returns the binary mask or None.""" 3079 prompt_layer = self._viewer.layers["prompts"] 3080 prompts = vutil.collect_frame_prompts( 3081 self._viewer.layers["point_prompts"], prompt_layer, shape, i=t, track_id=track_id, 3082 ) 3083 # A single negative point is a stop prompt: nothing to segment for this track here. 3084 if prompts.is_stop: 3085 return None 3086 3087 points, labels, boxes, masks = prompts.points, prompts.labels, prompts.boxes, prompts.masks 3088 if prompts.have_scribbles and not boxes and not np.any(labels == 1): 3089 show_info( 3090 "A negative scribble alone cannot segment an object. " 3091 "Add a positive point, positive scribble, box or mask prompt." 3092 ) 3093 return None 3094 3095 # The tracking annotator is SAM2-only: segment the frame via the video predictor. 3096 # Points are reordered to (x, y) and boxes to (x0, y0, x1, y1), matching the per-slice path. 3097 sam2_boxes = [box[[1, 0, 3, 2]] for box in boxes] 3098 seg = state.interactive_segmenter.segment_slice( 3099 frame_idx=t, 3100 points=points[:, ::-1].copy() if len(points) else points, 3101 labels=labels, 3102 boxes=sam2_boxes, 3103 masks=masks, 3104 ) 3105 return None if seg is None else (seg.squeeze() == 1) 3106 3107 def _run_frame_segmentation(self): 3108 """Execute per-frame segmentation for the current track (tracking mode).""" 3109 state = AnnotatorState() 3110 shape = state.image_shape[1:] 3111 t = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3112 3113 track_id = state.current_track_id 3114 new_mask = self._segment_track_on_frame(state, t, track_id, shape) 3115 if new_mask is None: 3116 print( 3117 "You either haven't provided any prompts or invalid prompts. The segmentation will be skipped." 3118 ) 3119 return 3120 3121 # Clear the old segmentation for this track id, then set the new one. 3122 layer = self._viewer.layers["current_object"] 3123 layer.data[t][layer.data[t] == track_id] = 0 3124 layer.data[t][new_mask] = track_id 3125 layer.refresh() 3126 3127 def _run_volumetric_segmentation(self): 3128 """Execute volumetric segmentation. 3129 """ 3130 pbar, pbar_signals = _create_pbar_for_threadworker() 3131 3132 def emit_progress(update): 3133 # The run is synchronous, so pump the Qt event loop to repaint the bar live instead of 3134 # only updating the terminal tqdm. 3135 pbar_signals.pbar_update.emit(update) 3136 QtWidgets.QApplication.processEvents() 3137 3138 # @thread_worker 3139 def volumetric_segmentation_impl(): 3140 state = AnnotatorState() 3141 shape = state.image_shape 3142 3143 pbar_signals.pbar_total.emit(shape[0]) 3144 pbar_signals.pbar_description.emit("Segment object") 3145 3146 # Prepare the prompts 3147 point_prompts = self._viewer.layers["point_prompts"] 3148 box_prompts = self._viewer.layers["prompts"] 3149 z_values_points = np.round(point_prompts.data[:, 0]) 3150 z_values_scribbles = vutil.get_scribble_slices(box_prompts) 3151 have_scribbles = len(z_values_scribbles) > 0 3152 z_values_boxes = np.round( 3153 np.asarray([ 3154 shape[0, 0] 3155 for shape, shape_type in zip(box_prompts.data, box_prompts.shape_type) 3156 if shape_type not in vutil.SCRIBBLE_SHAPE_TYPES 3157 ]) 3158 ).astype("int") 3159 3160 # Whether the user decide to provide batched prompts for multi-object segmentation. 3161 is_batched = _batched_disabled_when_tiled(state, bool(self.batched)) 3162 if have_scribbles and is_batched: 3163 show_info( 3164 "Batched segmentation is not supported with scribble prompts. " 3165 "It runs single-object segmentation instead." 3166 ) 3167 is_batched = False 3168 3169 # Collect every prompt first: a slice's negative points must be known when the boxes 3170 # and masks on that slice are assigned their object ids, and the complete set is 3171 # needed to detect prompts that changed since the last run. 3172 shape_yx = state.image_shape[-2:] 3173 point_slices = np.unique(np.concatenate([z_values_points, z_values_scribbles])).astype("int") 3174 merged_prompts, shape_prompts, stop_slices = {}, {}, [] 3175 for curr_z in np.unique(np.concatenate([point_slices, z_values_boxes])).astype("int"): 3176 prompts = vutil.collect_frame_prompts(point_prompts, box_prompts, shape_yx, i=curr_z) 3177 # A slice whose only prompt is a single negative point is a 'stop' annotation. 3178 if prompts.is_stop: 3179 stop_slices.append(int(curr_z)) 3180 elif len(prompts.points): 3181 merged_prompts[int(curr_z)] = (prompts.points, prompts.labels) 3182 rect_boxes, poly_masks = prompts.split_shapes() 3183 if rect_boxes or poly_masks: 3184 shape_prompts[int(curr_z)] = (rect_boxes, poly_masks) 3185 3186 have_positive_points = any(np.any(labels == 1) for _, labels in merged_prompts.values()) 3187 have_shape_cue = len(shape_prompts) > 0 3188 if have_scribbles and not have_positive_points and not have_shape_cue: 3189 pbar_signals.pbar_stop.emit() 3190 _generate_message( 3191 "error", 3192 "A negative scribble needs a positive point, positive scribble, box or mask prompt.", 3193 ) 3194 return None 3195 if is_batched and not have_positive_points and not have_shape_cue: 3196 # A batched object needs a positive cue; a negative point only corrects one. 3197 pbar_signals.pbar_stop.emit() 3198 _generate_message( 3199 "error", 3200 "Batched segmentation needs a positive point, box or mask prompt.", 3201 ) 3202 return None 3203 3204 # Plan the whole round before touching the state: the object each prompt is routed to 3205 # depends on the prompt set as a whole, and the sync below needs that routing. 3206 plan = _plan_volume_prompts(merged_prompts, shape_prompts, is_batched) 3207 signatures = _volume_prompt_signatures(plan) 3208 3209 # A patience of 0 disables early stopping (propagate through the whole volume). 3210 early_stop_patience = self.early_stop_patience if self.early_stop_patience > 0 else None 3211 prompted_slices = set(merged_prompts) | set(shape_prompts) 3212 z_range, ignored_stops = _bound_z_range_by_stops( 3213 prompted_slices, stop_slices, shape[0], self.z_range 3214 ) 3215 if ignored_stops: 3216 show_info( 3217 f"Ignoring the stop annotation (single negative point) in slice(s) {ignored_stops}: " 3218 "a stop must lie below or above all prompted slices." 3219 ) 3220 3221 # Propagating the same prompts again costs a full pass and drifts from the first result. 3222 run_key = ( 3223 id(state.interactive_segmenter), is_batched, frozenset(signatures), z_range, early_stop_patience 3224 ) 3225 if self._last_volume_run is not None and self._last_volume_run[0] == run_key: 3226 pbar_signals.pbar_stop.emit() 3227 return self._last_volume_run[1].copy() 3228 3229 # Rebuild the persistent state when a prompt was deleted, moved, relabelled or routed 3230 # to a different object since the last run. A round that only adds prompts and leaves 3231 # the existing routing intact keeps the state, so only the new prompts are pushed. 3232 state.interactive_segmenter.sync_prompt_state(signatures) 3233 _push_volume_prompts(state.interactive_segmenter, plan) 3234 3235 # Propagate the prompts throughout the volume and combine the propagated segmentations. 3236 # Tiled segmenters count one step per slice in each tile activated above. 3237 n_propagation_steps = state.interactive_segmenter.get_progress_total(z_range) 3238 pbar_signals.pbar_total.emit(n_propagation_steps) 3239 pbar_signals.pbar_description.emit("Propagate in volume") 3240 seg = state.interactive_segmenter.predict( 3241 update_progress=emit_progress, 3242 early_stop_patience=early_stop_patience, z_range=z_range, 3243 ) 3244 self._last_volume_run = (run_key, seg.copy()) 3245 3246 pbar_signals.pbar_stop.emit() 3247 3248 return seg 3249 3250 def update_segmentation(seg): 3251 self._viewer.layers["current_object"].data = seg 3252 self._viewer.layers["current_object"].refresh() 3253 3254 seg = volumetric_segmentation_impl() 3255 if seg is None: 3256 return None 3257 self._viewer.layers["current_object"].data = seg 3258 self._viewer.layers["current_object"].refresh() 3259 # worker = volumetric_segmentation_impl() 3260 # worker.returned.connect(update_segmentation) 3261 # worker.start() 3262 # return worker 3263 3264 def _run_tracking(self): 3265 """Execute interactive tracking by propagating the current track's prompts across frames. 3266 3267 Design boundary: SAM2 only does per-object mask propagation across frames. It has no concept 3268 of a division / lineage event and never signals one. Everything division-related here is 3269 mechanistic orchestration on top of the model (reading the user's 'division' annotation, 3270 bounding propagation, seeding daughters, recording lineage edges) - none of it is a SAM2 3271 capability. Genuine automatic division detection lives in the automatic-tracking path via 3272 trackastra, which predicts lineages from per-frame segmentations; it is not SAM2. 3273 """ 3274 state = AnnotatorState() 3275 pbar, pbar_signals = _create_pbar_for_threadworker() 3276 3277 def emit_progress(update): 3278 # Synchronous run: pump the Qt event loop so the bar repaints live, not only in the terminal. 3279 pbar_signals.pbar_update.emit(update) 3280 QtWidgets.QApplication.processEvents() 3281 3282 def propagate_track(track_id, division_frame): 3283 # Propagate a single track's prompts forward in time with the SAM2 predictor. Tracking 3284 # is forward-only: it starts at the first prompted frame and never runs to earlier 3285 # frames. A frame whose only prompt for this track is a single negative point is a 3286 # 'stop' annotation. A stop on the highest annotated frame bounds propagation above. 3287 shape = state.image_shape 3288 point_layer = self._viewer.layers["point_prompts"] 3289 box_layer = self._viewer.layers["prompts"] 3290 3291 # Reset so a re-run does not accumulate prompts from a previous propagation. 3292 state.interactive_segmenter.reset_predictor() 3293 pbar_signals.pbar_description.emit(f"Track object {track_id}") 3294 3295 # Add the point and scribble prompts for this track, one frame at a time, recording the 3296 # prompted frames and the stop annotations. A scribble expands into several point prompts 3297 # on its frame, in the same (y, x) order as the point prompts. 3298 prompted_frames, stop_frames = [], [] 3299 z_points = ( 3300 np.unique(np.round(point_layer.data[:, 0]).astype(int)) 3301 if len(point_layer.data) else np.zeros(0, dtype=int) 3302 ) 3303 z_scribbles = vutil.get_scribble_slices(box_layer, track_id=track_id) 3304 have_positive_cue = False 3305 for t in sorted({int(t) for t in z_points} | {int(t) for t in z_scribbles}): 3306 # Exclude division markers: they signal a lineage event and bound propagation 3307 # (see below), but must not be fed to SAM2 as conditioning prompts - doing so 3308 # adds a second conditioning frame that corrupts the mother track's propagation. 3309 prompts = vutil.collect_frame_prompts( 3310 point_layer, box_layer, shape[1:], i=t, track_id=track_id, 3311 exclude_states=("division",), 3312 ) 3313 if prompts.is_stop: # Single negative point: a stop annotation for this track. 3314 stop_frames.append(t) 3315 continue 3316 if len(prompts.points) == 0: # This track has no point prompts on this frame. 3317 continue 3318 have_positive_cue = have_positive_cue or bool(np.any(prompts.labels == 1)) 3319 state.interactive_segmenter.add_point_prompts( 3320 frame_ids=t, points=prompts.points, point_labels=prompts.labels, 3321 ) 3322 prompted_frames.append(t) 3323 3324 # Add the box prompts for this track. 3325 z_boxes = ( 3326 np.unique(np.concatenate([box[:1, 0] for box in box_layer.data]).round().astype(int)) 3327 if box_layer.data else np.zeros(0, dtype=int) 3328 ) 3329 for t in z_boxes: 3330 boxes, _ = vutil.shape_layer_to_prompts(box_layer, shape=shape[1:], i=int(t), track_id=track_id) 3331 for box in boxes: 3332 state.interactive_segmenter.add_box_prompts(frame_ids=int(t), boxes=[box]) 3333 if boxes: 3334 have_positive_cue = True 3335 prompted_frames.append(int(t)) 3336 3337 if not prompted_frames: 3338 return None 3339 if not have_positive_cue: 3340 show_info( 3341 "Negative prompts alone cannot track an object. " 3342 "Add a positive point, positive scribble or box prompt." 3343 ) 3344 return None 3345 3346 # Forward-only propagation: start at the first prompted frame and never go to earlier 3347 # frames. A stop annotation on the highest annotated frame bounds propagation above 3348 # ('predict' enforces the z-range); a division bounds the mother at the division frame - 3349 # its last frame (only reached when the mother is not segmented yet, see 'tracking_impl'). 3350 annotated = sorted(set(prompted_frames) | set(stop_frames)) 3351 stop_upper = annotated[-1] in stop_frames 3352 z_lo = min(prompted_frames) 3353 z_hi = max(prompted_frames) if stop_upper else shape[0] - 1 3354 if division_frame is not None: # The division frame is the mother's last frame. 3355 z_hi = min(z_hi, division_frame) 3356 3357 if z_hi < z_lo: # The division precedes the track's first frame: nothing to segment. 3358 return None 3359 3360 pbar_signals.pbar_total.emit( 3361 state.interactive_segmenter.get_progress_total((z_lo, z_hi)) 3362 ) 3363 seg = state.interactive_segmenter.predict( 3364 update_progress=emit_progress, 3365 early_stop_patience=None, z_range=(z_lo, z_hi), 3366 ) 3367 return seg 3368 3369 def tracking_impl(): 3370 # Propagate the current track. Its propagated mask is labelled with its track id. 3371 track_ids = [state.current_track_id] 3372 point_layer = self._viewer.layers["point_prompts"] 3373 seg_layer = self._viewer.layers["current_object"] 3374 results = {} 3375 for track_id in track_ids: 3376 division_frame = _division_frame_for_track(point_layer, track_id) 3377 # A division is a cleanup, not a (re)segmentation: when the mother is already 3378 # segmented, its frames up to and including the division are correct (tracking is 3379 # forward-only), so we just erase it AFTER the division frame and seed the daughters 3380 # - no SAM2 re-run. Only when the mother is not segmented yet do we fall back to a 3381 # bounded propagation so it still gets created up to the division frame. 3382 segmented = division_frame is not None and bool( 3383 np.any(seg_layer.data[:division_frame + 1] == track_id) 3384 ) 3385 if segmented: 3386 results[track_id] = {"truncate_from": division_frame + 1} 3387 _update_lineage(self._viewer, mother=track_id) 3388 continue 3389 3390 seg = propagate_track(track_id, division_frame) 3391 if seg is not None: 3392 res = {"seg": seg} 3393 # A daughter must not occupy its mother's frames: clip its mask to start the 3394 # frame after the mother's division, no matter where the user prompted it. 3395 mother_division = _mother_division_frame(point_layer, state.lineage, track_id) 3396 if mother_division is not None: 3397 res["min_frame"] = mother_division + 1 3398 results[track_id] = res 3399 # A division seeds two daughter tracks, so the user can continue from the division. 3400 if division_frame is not None: 3401 _update_lineage(self._viewer, mother=track_id) 3402 pbar_signals.pbar_stop.emit() 3403 return results 3404 3405 def update_segmentation(results): 3406 if not results: 3407 print("No prompts were given for the track(s). The tracking will be skipped.") 3408 return 3409 3410 layer = self._viewer.layers["current_object"] 3411 for track_id, res in results.items(): 3412 if "truncate_from" in res: 3413 # Division cleanup: erase the mother after the division frame, leaving its 3414 # frames up to and including the division (already correct) untouched. 3415 f = res["truncate_from"] 3416 layer.data[f:][layer.data[f:] == track_id] = 0 3417 else: 3418 # Clear the old mask for this track, then set the propagated one. A daughter is 3419 # clipped to start the frame after its mother's division (it did not exist yet). 3420 seg = res["seg"] 3421 min_frame = res.get("min_frame") 3422 if min_frame is not None: 3423 seg = seg.copy() 3424 seg[:min_frame] = 0 3425 layer.data[layer.data == track_id] = 0 3426 layer.data[seg == 1] = track_id 3427 layer.refresh() 3428 3429 results = tracking_impl() 3430 update_segmentation(results) 3431 3432 3433# 3434# The widgets for interactive segmentation and tracking. 3435# 3436 3437 3438class InteractiveSegmentationWidget(_WidgetBase): 3439 """Interactive segmentation widget combining the prompt menu, segmentation and clearing. 3440 3441 This widget adapts to the data dimensionality and works with both SAM and SAM2 models. 3442 For 3d data it exposes a single 'Apply to Volume' checkbox that governs both segmentation and 3443 clearing (current slice vs. the whole volume / all slices), plus a batched toggle (SAM2 volume 3444 mode) for multi-object segmentation. 3445 3446 Args: 3447 viewer: The napari viewer. 3448 ndim: The number of spatial dimensions of the data (2 or 3). 3449 prompt_widget: The point prompt label menu created by `create_prompt_menu`. 3450 parent: The parent Qt widget. 3451 """ 3452 3453 segment_requested = Signal() 3454 3455 def __init__(self, viewer, ndim, prompt_widget, parent=None): 3456 super().__init__(parent=parent) 3457 self._viewer = viewer 3458 self._ndim = ndim 3459 self._prompt_widget = prompt_widget 3460 self.batched = False 3461 self.apply_to_volume = False 3462 self._segment_widget = None 3463 self._propagation_settings = None 3464 self._create_widget() 3465 3466 def _create_widget(self): 3467 # Prompt label menu. 3468 self.layout().addWidget(self._prompt_widget.native) 3469 3470 self.clear_button = QtWidgets.QPushButton("Clear Annotations [Shift + C]") 3471 self.clear_button.setToolTip(get_tooltip("unified_segment", "clear_button")) 3472 self.clear_button.clicked.connect(lambda: self.clear()) 3473 3474 self.segment_button = QtWidgets.QPushButton("Segment Object [S]") 3475 self.segment_button.setToolTip(get_tooltip("unified_segment", "segment_button")) 3476 self.segment_button.clicked.connect(lambda: self.segment()) 3477 3478 # Segmentation controls. 3479 if self._ndim == 2: 3480 # 2d: a 'batched' toggle above the side-by-side segment and clear buttons. 3481 self.batched_checkbox = self._add_boolean_param( 3482 "batched", 3483 self.batched, 3484 title="Batched", 3485 tooltip=get_tooltip("unified_segment", "batched"), 3486 ) 3487 self.layout().addWidget(self.batched_checkbox) 3488 else: 3489 # 3d: use the volumetric segmentation widget purely as the segmentation engine. 3490 # It does not show its own controls. The interactive widget owns the 'Apply to Volume' 3491 # and 'Batched' checkboxes and drives the engine's attributes. The 'Apply to Volume' 3492 # checkbox governs both segmentation (slice vs. volume) and clearing (current slice 3493 # vs. all slices). It is kept hidden but parented so it does not float as a window. 3494 self._segment_widget = UnifiedSegmentWidget(self._viewer, tracking=False) 3495 self._segment_widget.setVisible(False) 3496 self.layout().addWidget(self._segment_widget) 3497 3498 # Batched multi-object segmentation. Works for both a single slice and the whole 3499 # volume, so it is always available. 3500 self.batched_checkbox = self._add_boolean_param( 3501 "batched", 3502 self.batched, 3503 title="Batched", 3504 tooltip=get_tooltip("unified_segment", "batched"), 3505 ) 3506 self.batched_checkbox.stateChanged.connect(self._on_batched_changed) 3507 3508 self.apply_to_volume_checkbox = self._add_boolean_param( 3509 "apply_to_volume", 3510 self.apply_to_volume, 3511 title="Apply to Volume", 3512 tooltip=get_tooltip("unified_segment", "apply_to_volume"), 3513 ) 3514 self.apply_to_volume_checkbox.stateChanged.connect(self._on_apply_to_volume_changed) 3515 3516 # Place the two checkboxes side by side: 'Batched' on the left, 'Apply to Volume' 3517 # pushed to the right. 3518 checkbox_row = QtWidgets.QHBoxLayout() 3519 checkbox_row.addWidget(self.batched_checkbox) 3520 checkbox_row.addStretch() 3521 checkbox_row.addWidget(self.apply_to_volume_checkbox) 3522 self.layout().addLayout(checkbox_row) 3523 3524 # SAM2 volume-mode propagation controls (early stopping + z-range). Hidden until the 3525 # user enables 'Apply to Volume' with a SAM2 model. The controls drive the engine. 3526 self._propagation_settings = self._create_propagation_settings() 3527 self._propagation_settings.setVisible(False) 3528 self.layout().addWidget(self._propagation_settings) 3529 3530 # Place the segment and clear buttons side by side. 3531 button_row = QtWidgets.QHBoxLayout() 3532 button_row.addWidget(self.segment_button) 3533 button_row.addWidget(self.clear_button) 3534 self.layout().addLayout(button_row) 3535 3536 # Scribbles describe corrections for one object and cannot be assigned unambiguously to 3537 # separate objects in batched mode. Keep the control in sync as scribbles are added or 3538 # removed from the shared prompt layer. 3539 self._viewer.layers["prompts"].events.data.connect(self._update_batched_visibility) 3540 3541 # Hide the batched control if the (already loaded) embeddings are tiled. 3542 self._update_batched_visibility() 3543 3544 def _update_batched_visibility(self, event=None): 3545 """Disable batched segmentation while one or more scribble prompts are present.""" 3546 super()._update_batched_visibility() 3547 3548 prompt_layer = self._viewer.layers["prompts"] 3549 have_scribbles = any( 3550 shape_type in vutil.SCRIBBLE_SHAPE_TYPES for shape_type in prompt_layer.shape_type 3551 ) 3552 if have_scribbles and self.batched_checkbox.isChecked(): 3553 self.batched_checkbox.setChecked(False) 3554 3555 self.batched_checkbox.setEnabled(not have_scribbles) 3556 tooltip_key = "batched_scribble_disabled" if have_scribbles else "batched" 3557 self.batched_checkbox.setToolTip(get_tooltip("unified_segment", tooltip_key)) 3558 3559 def _create_propagation_settings(self): 3560 """Build the SAM2 volume-mode propagation controls (early stopping + z-range slider). 3561 3562 The controls live on the visible interactive widget and write their values into the hidden 3563 'UnifiedSegmentWidget' engine, which reads 'early_stop_patience' and 'z_range' at run time. 3564 """ 3565 container = QtWidgets.QWidget() 3566 container.setLayout(QtWidgets.QVBoxLayout()) 3567 3568 # Stop after this many consecutive empty slices (0 disables early stopping). 3569 self.early_stop_patience = 2 3570 self.early_stop_patience_param, layout = self._add_int_param( 3571 "early_stop_patience", self.early_stop_patience, min_val=0, max_val=100, 3572 title="Stop after empty slices", tooltip=get_tooltip("segmentnd", "early_stop_patience"), 3573 ) 3574 self.early_stop_patience_param.valueChanged.connect(self._sync_propagation_settings) 3575 container.layout().addLayout(layout) 3576 3577 # Full-volume propagation (default) vs. a restricted z-range. 3578 self.use_full_z_range = True 3579 self.full_z_range_checkbox = self._add_boolean_param( 3580 "use_full_z_range", self.use_full_z_range, 3581 title="Propagate through all slices", 3582 tooltip=get_tooltip("segmentnd", "use_full_z_range"), 3583 ) 3584 container.layout().addWidget(self.full_z_range_checkbox) 3585 3586 # The labeled range slider collapses to zero height when sharing a row with a text label, 3587 # so it gets its own full-width row with the caption above it and a minimum height. 3588 z_range_label = QtWidgets.QLabel("Propagation z-range") 3589 z_range_label.setToolTip(get_tooltip("segmentnd", "z_range")) 3590 container.layout().addWidget(z_range_label) 3591 self.z_range_slider = QLabeledRangeSlider(Qt.Orientation.Horizontal) 3592 self.z_range_slider.setRange(0, 1) 3593 self.z_range_slider.setValue((0, 1)) 3594 self.z_range_slider.setToolTip(get_tooltip("segmentnd", "z_range")) 3595 self.z_range_slider.setEnabled(not self.use_full_z_range) 3596 self.z_range_slider.setMinimumHeight(40) 3597 self.z_range_slider.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) 3598 container.layout().addWidget(self.z_range_slider) 3599 3600 self.full_z_range_checkbox.stateChanged.connect(self._on_full_z_range_changed) 3601 self.z_range_slider.valueChanged.connect(self._sync_propagation_settings) 3602 3603 return _make_collapsible( 3604 container, title="Volume Propagation Settings", tooltip=get_tooltip("segmentnd", "settings"), 3605 ) 3606 3607 def _on_full_z_range_changed(self, state): 3608 """Enable/disable the z-range slider and push the change to the engine.""" 3609 self.use_full_z_range = bool(state) 3610 self.z_range_slider.setEnabled(not self.use_full_z_range) 3611 self._sync_propagation_settings() 3612 3613 def _update_z_range_slider(self): 3614 """Match the z-range slider extent to the depth of the loaded volume.""" 3615 state = AnnotatorState() 3616 if state.image_shape is None: 3617 return 3618 z_max = int(state.image_shape[0]) - 1 3619 if z_max < 0: 3620 return 3621 lo, hi = self.z_range_slider.value() 3622 self.z_range_slider.setRange(0, z_max) 3623 if not self.use_full_z_range and hi <= z_max and lo < hi: 3624 self.z_range_slider.setValue((lo, hi)) 3625 else: 3626 self.z_range_slider.setValue((0, z_max)) 3627 3628 def _sync_propagation_settings(self, *args): 3629 """Write the propagation controls into the hidden segmentation engine.""" 3630 if self._segment_widget is None: 3631 return 3632 self._segment_widget.early_stop_patience = int(self.early_stop_patience_param.value()) 3633 if bool(self.use_full_z_range): 3634 self._segment_widget.z_range = None 3635 else: 3636 self._segment_widget.z_range = tuple(int(v) for v in self.z_range_slider.value()) 3637 3638 def _on_apply_to_volume_changed(self, state): 3639 """Sync the shared volume mode to the segmentation engine.""" 3640 self.apply_to_volume = bool(state) 3641 self._segment_widget.apply_to_volume = self.apply_to_volume 3642 3643 # Show the propagation controls only in volume mode with a loaded model. Then fit the slider to the volume. 3644 if self._propagation_settings is not None: 3645 show = self.apply_to_volume and AnnotatorState().predictor is not None 3646 self._propagation_settings.setVisible(show) 3647 if show: 3648 self._update_z_range_slider() 3649 self._sync_propagation_settings() 3650 3651 def _on_batched_changed(self, state): 3652 """Sync the batched mode to the segmentation engine.""" 3653 self.batched = bool(state) 3654 self._segment_widget.batched = self.batched 3655 3656 def segment(self, viewer=None): 3657 """Run interactive segmentation for the current prompts.""" 3658 self.segment_requested.emit() 3659 if self._ndim == 2: 3660 _segment_object_2d(self._viewer, batched=bool(self.batched)) 3661 else: 3662 self._sync_propagation_settings() 3663 self._segment_widget(self._viewer) 3664 3665 def clear(self, viewer=None): 3666 """Clear the current annotations.""" 3667 if self._segment_widget is not None: 3668 if self._segment_widget.is_running: 3669 show_info("The segmentation is still running. Wait until it finishes.") 3670 return 3671 self._segment_widget.reset_last_volume_run() 3672 3673 if self._ndim == 2 or self.apply_to_volume: 3674 vutil.clear_annotations(self._viewer) 3675 else: 3676 i = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3677 vutil.clear_annotations_slice(self._viewer, i=i) 3678 3679 # If this is a SAM2 promptable segmentation workflow, 3680 # reset the prompts after the user clears the annotations. 3681 state = AnnotatorState() 3682 if state.interactive_segmenter is not None: 3683 state.interactive_segmenter.reset_predictor() 3684 3685 gc.collect() 3686 3687 3688class InteractiveTrackingWidget(_WidgetBase): 3689 """Merged interactive widget for the tracking annotator. 3690 3691 Combines the prompt label menu, the track id / track state menus and the segment / clear 3692 controls into a single container, mirroring the segmentation annotator's 3693 'InteractiveSegmentationWidget'. The 'Apply to All Frames' checkbox governs both segmentation 3694 (current frame vs. propagating across the whole video) and clearing (current frame vs. all 3695 frames). A hidden 'UnifiedSegmentWidget' is used purely as the segmentation engine. 3696 3697 Args: 3698 viewer: The napari viewer. 3699 tracking_widget: The combined prompt label / track id / track state menu created by 3700 'create_tracking_menu'. 3701 parent: The parent Qt widget. 3702 """ 3703 3704 segment_requested = Signal() 3705 3706 def __init__(self, viewer, tracking_widget, parent=None): 3707 super().__init__(parent=parent) 3708 self._viewer = viewer 3709 self._tracking_widget = tracking_widget 3710 self.apply_to_volume = False 3711 self._segment_widget = None 3712 self._create_widget() 3713 3714 def _create_widget(self): 3715 # The combined prompt label / track id / track state menus (one container so the three 3716 # dropdowns share an aligned label column). Lay each row out as label-left, box-right. 3717 self.layout().addWidget(self._tracking_widget.native) 3718 self._align_menu_rows() 3719 3720 # Hidden segmentation engine: owns the per-frame and propagation logic, driven via its 3721 # 'apply_to_volume' attribute. Its own controls are not shown. 3722 self._segment_widget = UnifiedSegmentWidget(self._viewer, tracking=True) 3723 self._segment_widget.setVisible(False) 3724 self.layout().addWidget(self._segment_widget) 3725 3726 # 'Apply to All Frames' toggles between segmenting the current frame and propagating the track. 3727 self.apply_to_volume_checkbox = self._add_boolean_param( 3728 "apply_to_volume", self.apply_to_volume, title="Apply to All Frames", 3729 tooltip=get_tooltip("unified_segment", "apply_to_volume"), 3730 ) 3731 self.apply_to_volume_checkbox.stateChanged.connect(self._on_apply_to_volume_changed) 3732 self.layout().addWidget(self.apply_to_volume_checkbox) 3733 3734 # 'Segment Object' / 'Clear Annotations' side by side. 3735 self.segment_button = QtWidgets.QPushButton("Segment Object [S]") 3736 self.segment_button.setToolTip(get_tooltip("unified_segment", "segment_button")) 3737 self.segment_button.clicked.connect(lambda: self.segment()) 3738 self.clear_button = QtWidgets.QPushButton("Clear Annotations [Shift + C]") 3739 self.clear_button.setToolTip(get_tooltip("unified_segment", "clear_button")) 3740 self.clear_button.clicked.connect(lambda: self.clear()) 3741 button_row = QtWidgets.QHBoxLayout() 3742 button_row.addWidget(self.segment_button) 3743 button_row.addWidget(self.clear_button) 3744 self.layout().addLayout(button_row) 3745 3746 def _align_menu_rows(self): 3747 # Each menu row is a QHBoxLayout of [QLabel, QComboBox]. Insert a stretch between them so the 3748 # label stays left and the (fixed-width) combo box is right-aligned. Idempotent, since the 3749 # menu container persists across layout rebuilds. 3750 container_layout = self._tracking_widget.native.layout() 3751 for i in range(container_layout.count()): 3752 row = container_layout.itemAt(i).widget() 3753 row_layout = None if row is None else row.layout() 3754 if row_layout is None or row_layout.count() < 2: 3755 continue 3756 combo = row_layout.itemAt(row_layout.count() - 1).widget() 3757 if combo is not None: 3758 combo.setFixedWidth(300) 3759 if row_layout.count() < 3: # No stretch inserted yet. 3760 row_layout.insertStretch(1) 3761 3762 def _on_apply_to_volume_changed(self, state): 3763 self.apply_to_volume = bool(state) 3764 self._segment_widget.apply_to_volume = self.apply_to_volume 3765 3766 def segment(self, viewer=None): 3767 """Run interactive tracking segmentation for the current prompts.""" 3768 self.segment_requested.emit() 3769 self._segment_widget(self._viewer) 3770 3771 def clear(self, viewer=None): 3772 """Clear the annotations: the current frame, or all frames in 'Apply to All Frames' mode.""" 3773 if self._segment_widget.is_running: 3774 show_info("The segmentation is still running. Wait until it finishes.") 3775 return 3776 3777 if self.apply_to_volume: 3778 _reset_tracking_state(self._viewer) 3779 vutil.clear_annotations(self._viewer) 3780 else: 3781 i = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3782 vutil.clear_annotations_slice(self._viewer, i=i) 3783 3784 state = AnnotatorState() 3785 if state.interactive_segmenter is not None: 3786 state.interactive_segmenter.reset_predictor() 3787 gc.collect() 3788 3789 3790# 3791# The functionality and widgets for automatic segmentation. 3792# 3793 3794 3795# Every automatic segmentation mode runs off the UniSAM2 decoder predictions, so a model without a 3796# decoder has no automatic segmentation at all. 3797NO_DECODER_MESSAGE = ( 3798 "Automatic segmentation requires a UniSAM2 model with a decoder. Load one via the model dropdown " 3799 "or the 'custom weights' path in the embedding widget. A model trained for interactive segmentation " 3800 "only has no decoder." 3801) 3802 3803# APG prompts the SAM2 video predictor with every candidate, which needs an accelerator to finish in 3804# a reasonable time. This applies to a whole volume and to tracking (which prompts per frame); plain 3805# 2d APG on an image or a single slice has no such restriction and runs on the CPU like the other 3806# modes. This is an annotator-level restriction only - 'micro_sam.v2.automatic_prompt_generation' and 3807# the CLI still run wherever they are pointed. 3808APG_ACCELERATORS = ("cuda", "mps") 3809 3810 3811def _apg_runs_on_this_device(state): 3812 """Whether APG's video-predictor path can run on the device the model is loaded on. 3813 3814 Args: 3815 state: The annotator state, holding the loaded decoder. 3816 3817 Returns: 3818 Whether the device is one APG's volume / tracking path supports. 3819 """ 3820 return util.device_type(next(state.decoder.parameters()).device) in APG_ACCELERATORS 3821 3822 3823def _apg_error(state, volumetric, is_tracking=False): 3824 """Why APG cannot run in the annotator for this data, if it cannot. 3825 3826 The device rule is per data kind, not per run: volumetric data and a timeseries go through the 3827 video predictor, so APG is unavailable for the whole widget on the CPU - a single slice or frame 3828 of them included. A plain 2d image prompts the image predictor and runs anywhere. Tiled embeddings 3829 are no restriction, because `TiledAutomaticPromptGenerator` segments a tiled volume block by block. 3830 3831 Args: 3832 state: The annotator state, holding the loaded decoder. 3833 volumetric: Whether the widget's data is volumetric (a volume or a timeseries). 3834 is_tracking: Whether this is the automatic tracking widget. 3835 3836 Returns: 3837 The error message, or None if the APG run is supported. 3838 """ 3839 if (volumetric or is_tracking) and not _apg_runs_on_this_device(state): 3840 data_kind = "tracking" if is_tracking else "volumetric data" 3841 return ( 3842 f"APG is not available for {data_kind} on the CPU, since it prompts the video predictor " 3843 "for every candidate. Use the 'sparse' or 'dense' mode instead." 3844 ) 3845 return None 3846 3847 3848class AutoSegmentWidget(_WidgetBase): 3849 """Automatic segmentation widget for SAM2 with the APG, sparse and dense modes. 3850 3851 Subclasses set `_is_tracking = True` to hide the z-tiling controls (tracking segments per frame 3852 in 2d, so z-tiling does not apply). 3853 3854 All modes need a UniSAM2 decoder. Automatic prompt generation (APG) derives point prompts from 3855 the decoder predictions and applies them to the interactive branch; it is the default on CUDA 3856 and MPS. The sparse mode (AIS) is the CPU default. Sparse and dense modes post-process the 3857 decoder predictions directly. Without a decoder there is no automatic segmentation: the run 3858 button is disabled until a model that has one is loaded. 3859 3860 Disk-backed caching of the state is opted into via the 'cache automatic segmentation state' 3861 checkbox in the embedding settings (read here through the embedding widget); when off, the state 3862 is kept in memory only. 3863 3864 Args: 3865 viewer: The napari viewer. 3866 with_decoder: Whether the loaded model has a UniSAM2 decoder for automatic segmentation. 3867 volumetric: Whether the data is volumetric (3d). 3868 parent: The parent Qt widget. 3869 """ 3870 3871 segmentation_finished = Signal() 3872 3873 _is_tracking = False 3874 MODES = ("apg", "sparse", "dense") 3875 # The (section, name) of the run button's tooltip; the tracking subclass has its own. 3876 _RUN_TOOLTIP = ("autosegment", "run_button") 3877 3878 def __init__(self, viewer, with_decoder, volumetric, parent=None): 3879 super().__init__(parent) 3880 self._viewer = viewer 3881 self.with_decoder = with_decoder 3882 self.volumetric = volumetric 3883 # Every mode needs a decoder. APG additionally needs an accelerator for volumetric data and 3884 # for tracking, so it is dropped from the list there - see '_available_modes'. 3885 self.mode = self._default_mode() 3886 self.settings = None 3887 # z block / halo for 3d decoder inference: the volume is decoded in z chunks to bound memory. 3888 # These only matter for volumetric decoder modes. Set 'tile_z' >= the slice count for no z-tiling. 3889 from micro_sam.v2.util import DEFAULT_TILE_Z, DEFAULT_HALO_Z 3890 self.tile_z, self.halo_z = DEFAULT_TILE_Z, DEFAULT_HALO_Z 3891 # Cache of the (initialized) segmentation generator so changing post-processing parameters 3892 # only re-runs 'generate', not the expensive UniSAM2 inference. Keyed by the inputs. 3893 self._segmenter = None 3894 self._segmenter_key = None 3895 # The decoder prediction the generator is built from. It does not depend on the mode, so it 3896 # outlives the generator and is shared by 'sparse', 'dense' and 'apg'. 3897 self._decoder_state = None 3898 self._decoder_state_key = None 3899 self._decoder_state_save_path = None 3900 # The APG proposals, so that changing only the merge parameters skips the prompting. 3901 self._proposals = None 3902 self._proposals_key = None 3903 self._create_widget() 3904 3905 def _apg_is_available(self): 3906 # A plain 2d image prompts the image predictor and runs anywhere. Volumetric data and a 3907 # timeseries go through the video predictor, which needs an accelerator. Before the model is 3908 # loaded ('Compute Embeddings') the device is not known yet, so APG is offered and the sync 3909 # afterwards ('_reset_segmentation_mode') settles it. 3910 if not (self.volumetric or self._is_tracking): 3911 return True 3912 state = AnnotatorState() 3913 return state.decoder is None or _apg_runs_on_this_device(state) 3914 3915 def _available_modes(self): 3916 """The modes offered for this widget's data on the loaded device. 3917 3918 Returns: 3919 The mode names, in dropdown order. The first is the default. 3920 """ 3921 from micro_sam._model_settings import DEFAULT_POSTPROCESSING 3922 from micro_sam.v2.util import DEFAULT_MODEL, parameter_family 3923 3924 # Only a model with dense defaults segments neurites, e.g. not the EM organelle models. 3925 model_type = getattr(self, "model_type", None) or DEFAULT_MODEL 3926 has_dense = "dense" in DEFAULT_POSTPROCESSING.get(parameter_family(model_type), {}).get(model_type[:6], {}) 3927 modes = self.MODES if has_dense else tuple(mode for mode in self.MODES if mode != "dense") 3928 if not self._apg_is_available(): 3929 return tuple(mode for mode in modes if mode != "apg") 3930 3931 # Tiled APG can take hours on CPU. Prefer the direct decoder post-processing there, 3932 # while retaining APG as an explicit choice for 2d images. Before model loading, use 3933 # the available hardware; afterwards the decoder's device is authoritative, including 3934 # when the user explicitly chose CPU on a machine with an accelerator. 3935 state = AnnotatorState() 3936 device = util.get_device() if state.decoder is None else next(state.decoder.parameters()).device 3937 if util.device_type(device) not in APG_ACCELERATORS: 3938 return ("sparse", *(mode for mode in modes if mode != "sparse")) 3939 return modes 3940 3941 def _default_mode(self): 3942 return self._available_modes()[0] 3943 3944 def _mode_choices(self): 3945 return tuple(self.mode_dropdown.itemText(i) for i in range(self.mode_dropdown.count())) 3946 3947 def _create_widget(self): 3948 # Top row: the mode dropdown on the left, the 'Apply to Volume' switch (3d only) on the right. 3949 top_row = QtWidgets.QHBoxLayout() 3950 3951 self.mode_dropdown, mode_layout = self._add_choice_param( 3952 "mode", 3953 self.mode, 3954 list(self._available_modes()), 3955 title="mode:", 3956 update=self._on_mode_changed, 3957 tooltip=get_tooltip("autosegment", "mode"), 3958 ) 3959 # Keep the label at its text width so that the dropdown starts right after it and covers 3960 # the rest of the row. 3961 mode_layout.setStretch(0, 0) 3962 mode_layout.setStretch(1, 1) 3963 top_row.addLayout(mode_layout) 3964 3965 if self.volumetric: 3966 self.apply_to_volume = False 3967 self.apply_to_volume_checkbox = self._add_boolean_param( 3968 "apply_to_volume", 3969 self.apply_to_volume, 3970 title="Apply to Volume", 3971 tooltip=get_tooltip("autosegment", "apply_to_volume"), 3972 ) 3973 # The handler reads 'apply_to_volume', so it must run after the checkbox updates it. 3974 self.apply_to_volume_checkbox.stateChanged.connect(self._on_apply_to_volume_changed) 3975 top_row.addWidget(self.apply_to_volume_checkbox) 3976 3977 self.layout().addLayout(top_row) 3978 3979 # Advanced post-processing settings, shown inline and refreshed on mode change. 3980 self.settings = self._make_settings_widget() 3981 self.layout().addWidget(self.settings) 3982 3983 # Run button. It is only active with a decoder, since every mode needs one. 3984 self.run_button = QtWidgets.QPushButton("Automatic Segmentation") 3985 self.run_button.clicked.connect(self.__call__) 3986 self.layout().addWidget(self.run_button) 3987 self._update_run_button() 3988 3989 def _update_run_button(self): 3990 # Without a decoder none of the modes can run, so the button is disabled and says why. 3991 self.run_button.setEnabled(self.with_decoder) 3992 self.run_button.setToolTip( 3993 get_tooltip(*self._RUN_TOOLTIP) if self.with_decoder else NO_DECODER_MESSAGE 3994 ) 3995 3996 def _reset_segmentation_mode(self, with_decoder, model_type=None): 3997 # If neither the decoder availability, the offered modes nor the model changed there is nothing 3998 # to rebuild. The device can change the offered modes (volumes/tracking) or their order 3999 # (the CPU default is sparse, even for 2d), triggering a reset to the new default. The model 4000 # selects the default parameters, see 'default_postprocessing' and 'default_prompt_generation'. 4001 modes = self._available_modes() 4002 model_changed = model_type is not None and model_type != getattr(self, "model_type", None) 4003 if with_decoder == self.with_decoder and modes == self._mode_choices() and not model_changed: 4004 return 4005 if model_type is not None: 4006 self.model_type = model_type 4007 modes = self._available_modes() 4008 self.with_decoder = with_decoder 4009 self._update_run_button() 4010 4011 # Rebuild the list and go back to the default mode for the newly loaded model. 4012 self.mode_dropdown.blockSignals(True) 4013 self.mode_dropdown.clear() 4014 self.mode_dropdown.addItems(list(modes)) 4015 self.mode_dropdown.setCurrentText(self._default_mode()) 4016 self.mode_dropdown.blockSignals(False) 4017 4018 # Drop the cached segmenter and the decoder prediction, since the loaded model (and so its 4019 # predictions) changed, and refresh the settings panel to match the new default mode. 4020 self._release_segmenter() 4021 self._drop_decoder_state() 4022 self._on_mode_changed() 4023 4024 def _on_mode_changed(self, index=None): 4025 self.mode = self.mode_dropdown.currentText() 4026 new_settings = self._make_settings_widget() 4027 self.layout().replaceWidget(self.settings, new_settings) 4028 self.settings.deleteLater() 4029 self.settings = new_settings 4030 4031 def _make_settings_widget(self): 4032 # All hyperparameters (except mode and apply-to-volume) live in one collapsible 4033 # 'Advanced Settings' panel. The z block / halo (3d decoder modes) sit at the very top. 4034 advanced = QtWidgets.QWidget() 4035 advanced.setLayout(QtWidgets.QVBoxLayout()) 4036 advanced.layout().setContentsMargins(0, 0, 0, 0) 4037 self._add_z_tiling_params(advanced) 4038 if self.mode == "apg": 4039 self._apg_settings(advanced) 4040 elif self.mode == "dense": 4041 self._dense_settings(advanced) 4042 else: 4043 self._sparse_settings(advanced) 4044 4045 settings = QtWidgets.QWidget() 4046 settings.setLayout(QtWidgets.QVBoxLayout()) 4047 settings.layout().setContentsMargins(0, 0, 0, 0) 4048 advanced_tooltip = get_tooltip("autosegment", "advanced_settings") 4049 settings.layout().addWidget( 4050 _make_collapsible(advanced, title="Advanced Settings", tooltip=advanced_tooltip) 4051 ) 4052 return settings 4053 4054 def _add_density_threshold(self, settings): 4055 self.density_threshold_param, layout = self._add_float_param( 4056 "density_threshold", self.density_threshold, min_val=0.0, max_val=100.0, step=1.0, 4057 tooltip=get_tooltip("autosegment", "density_threshold"), 4058 ) 4059 settings.layout().addLayout(layout) 4060 4061 def _add_z_tiling_params(self, settings): 4062 # 3d decoder inference decodes the volume in z blocks (with a halo for context) to bound 4063 # memory. 'tile_z' and 'halo_z' sit side by side at the top of the settings. Only for 4064 # volumetric segmentation - not 2d and not tracking (which segments each frame in 2d). 4065 if not self.volumetric or self._is_tracking: 4066 return 4067 row = QtWidgets.QHBoxLayout() 4068 self.tile_z_param, _ = self._add_int_param( 4069 "tile_z", self.tile_z, min_val=1, max_val=512, title="tile_z:", 4070 tooltip=get_tooltip("autosegment", "tile_z"), layout=row, 4071 ) 4072 self.halo_z_param, _ = self._add_int_param( 4073 "halo_z", self.halo_z, min_val=0, max_val=128, title="overlap_z:", 4074 tooltip=get_tooltip("autosegment", "halo_z"), layout=row, 4075 ) 4076 settings.layout().addLayout(row) 4077 4078 def _add_flow_integration_params(self, settings, n_iter, dt=0.5, sigma=1.0): 4079 self.n_iter = n_iter 4080 self.n_iter_param, layout = self._add_int_param( 4081 "n_iter", self.n_iter, min_val=1, max_val=1000, tooltip=get_tooltip("autosegment", "n_iter"), 4082 ) 4083 settings.layout().addLayout(layout) 4084 4085 self.dt = dt 4086 self.dt_param, layout = self._add_float_param( 4087 "dt", self.dt, min_val=0.0, max_val=5.0, step=0.1, tooltip=get_tooltip("autosegment", "dt"), 4088 ) 4089 settings.layout().addLayout(layout) 4090 4091 self.sigma = sigma 4092 self.sigma_param, layout = self._add_float_param( 4093 "sigma", self.sigma, min_val=0.0, max_val=10.0, step=0.1, tooltip=get_tooltip("autosegment", "sigma"), 4094 ) 4095 settings.layout().addLayout(layout) 4096 4097 # Default to 8 threads for the post-processing flow/multicut backends (a sensible default that 4098 # does not oversubscribe. The user can raise it up to the spinbox maximum). 4099 self.n_threads = min(8, mp.cpu_count()) 4100 self.n_threads_param, layout = self._add_int_param( 4101 "n_threads", self.n_threads, min_val=1, max_val=64, tooltip=get_tooltip("autosegment", "n_threads"), 4102 ) 4103 settings.layout().addLayout(layout) 4104 4105 def _sparse_settings(self, settings): 4106 # Flow-based instance segmentation parameters (LM data). 4107 from micro_sam.v2.postprocessing import default_postprocessing 4108 from micro_sam.v2.util import DEFAULT_MODEL 4109 defaults = default_postprocessing( 4110 getattr(self, "model_type", None) or DEFAULT_MODEL, "sparse", is_volume=self._run_ndim() == 3, 4111 ) 4112 4113 self.foreground_threshold = defaults["foreground_threshold"] 4114 self.foreground_threshold_param, layout = self._add_float_param( 4115 "foreground_threshold", self.foreground_threshold, min_val=0.0, max_val=1.0, step=0.05, 4116 tooltip=get_tooltip("autosegment", "foreground_threshold"), 4117 ) 4118 settings.layout().addLayout(layout) 4119 4120 self.density_threshold = defaults["density_threshold"] 4121 self._add_density_threshold(settings) 4122 4123 self.min_object_size = defaults["min_size"] 4124 self.min_object_size_param, layout = self._add_int_param( 4125 "min_object_size", self.min_object_size, min_val=0, max_val=int(1e4), 4126 tooltip=get_tooltip("autosegment", "min_object_size"), 4127 ) 4128 settings.layout().addLayout(layout) 4129 4130 self._add_flow_integration_params( 4131 settings, 4132 n_iter=defaults["n_iter"], 4133 dt=defaults["dt"], 4134 sigma=defaults["sigma"], 4135 ) 4136 4137 def _dense_settings(self, settings): 4138 # Multicut-based instance segmentation parameters (EM data, 2d and 3d). 4139 from micro_sam.v2.postprocessing import default_postprocessing 4140 from micro_sam.v2.util import DEFAULT_MODEL 4141 defaults = default_postprocessing(getattr(self, "model_type", None) or DEFAULT_MODEL, "dense") 4142 4143 self.beta = defaults["beta"] 4144 self.beta_param, layout = self._add_float_param( 4145 "beta", self.beta, min_val=0.0, max_val=1.0, step=0.05, 4146 tooltip=get_tooltip("autosegment", "beta"), 4147 ) 4148 settings.layout().addLayout(layout) 4149 4150 self.density_threshold = defaults["density_threshold"] 4151 self._add_density_threshold(settings) 4152 4153 self._add_flow_integration_params( 4154 settings, 4155 n_iter=defaults["n_iter"], 4156 dt=defaults["dt"], 4157 sigma=defaults["sigma"], 4158 ) 4159 4160 # The APG parameters with other defaults for a volume, as (widget attribute, key of the defaults). 4161 _APG_DIMENSION_PARAMS = ( 4162 ("candidate_threshold", "candidate_threshold"), ("min_candidate_size", "min_candidate_size"), 4163 ("score_threshold", "score_threshold"), ("max_overlap", "max_overlap"), 4164 ("min_object_size", "min_size"), ("sigma", "sigma"), ("foreground_threshold", "foreground_threshold"), 4165 ) 4166 4167 def _apg_default_values(self, is_volume): 4168 """The defaults of the APG parameters that depend on the dimensionality of the run. 4169 4170 Args: 4171 is_volume: Whether the run segments a whole volume rather than an image or a slice. 4172 4173 Returns: 4174 The default values, keyed by the widget attribute. 4175 """ 4176 from micro_sam.v2.util import DEFAULT_MODEL 4177 from micro_sam.v2.automatic_prompt_generation import default_prompt_generation 4178 model_type = getattr(self, "model_type", None) or DEFAULT_MODEL 4179 defaults = default_prompt_generation(model_type, is_volume=is_volume) 4180 values = {attribute: defaults[key] for attribute, key in self._APG_DIMENSION_PARAMS} 4181 if is_volume: # A volume has a (low, high) pair of candidate thresholds. 4182 values["candidate_threshold"], values["candidate_threshold_high"] = defaults["candidate_threshold"] 4183 values["refine_with_box_prompts"] = defaults["refinement"] == "boxes" 4184 return values 4185 4186 def _on_apply_to_volume_changed(self, state=None): 4187 # Show the parameters of the next run. A slice run and a volume run keep their own values. 4188 if self.mode != "apg" or len(self._apg_values) < 2: 4189 return 4190 is_volume = self._run_ndim() == 3 4191 previous = self._apg_values[not is_volume] 4192 for attribute in previous: 4193 previous[attribute] = getattr(self, attribute) 4194 for attribute, value in self._apg_values[is_volume].items(): 4195 if attribute == "refine_with_box_prompts": 4196 self.refine_with_box_prompts_checkbox.setChecked(bool(value)) # also updates the attribute 4197 else: 4198 getattr(self, f"{attribute}_param").setValue(value) # also updates the attribute 4199 self.candidate_threshold_high_row.setVisible(is_volume) 4200 4201 def _apg_settings(self, settings): 4202 from micro_sam.v2.automatic_prompt_generation import ( 4203 DEFAULT_PROMPT_GENERATION, DEFAULT_REFINEMENT, default_prompt_generation, 4204 ) 4205 from micro_sam.v2.util import DEFAULT_MODEL 4206 model_type = getattr(self, "model_type", None) or DEFAULT_MODEL 4207 defaults = default_prompt_generation(model_type, is_volume=False) 4208 4209 # The parameters of a slice run (False) and of a volume run (True). 4210 self._apg_values = {False: self._apg_default_values(is_volume=False)} 4211 if self.volumetric and not self._is_tracking: 4212 self._apg_values[True] = self._apg_default_values(is_volume=True) 4213 is_volume = self._run_ndim() == 3 4214 values = self._apg_values[is_volume] 4215 4216 self.candidate_threshold = values["candidate_threshold"] 4217 self.candidate_threshold_param, layout = self._add_float_param( 4218 "candidate_threshold", self.candidate_threshold, min_val=0.0, max_val=100.0, step=0.1, 4219 tooltip=get_tooltip("autosegment", "candidate_threshold"), 4220 ) 4221 settings.layout().addLayout(layout) 4222 4223 if self.volumetric and not self._is_tracking: 4224 # Only a volume run uses the second threshold. 4225 self.candidate_threshold_high = self._apg_values[True]["candidate_threshold_high"] 4226 self.candidate_threshold_high_param, layout = self._add_float_param( 4227 "candidate_threshold_high", self.candidate_threshold_high, min_val=0.0, max_val=100.0, step=0.1, 4228 tooltip=get_tooltip("autosegment", "candidate_threshold_high"), 4229 ) 4230 layout.setContentsMargins(0, 0, 0, 0) 4231 self.candidate_threshold_high_row = QtWidgets.QWidget() 4232 self.candidate_threshold_high_row.setLayout(layout) 4233 self.candidate_threshold_high_row.setVisible(is_volume) 4234 settings.layout().addWidget(self.candidate_threshold_high_row) 4235 4236 self.foreground_threshold = values["foreground_threshold"] 4237 self.foreground_threshold_param, layout = self._add_float_param( 4238 "foreground_threshold", self.foreground_threshold, min_val=0.0, max_val=1.0, step=0.05, 4239 tooltip=get_tooltip("autosegment", "foreground_threshold"), 4240 ) 4241 settings.layout().addLayout(layout) 4242 4243 self.min_candidate_size = values["min_candidate_size"] 4244 self.min_candidate_size_param, layout = self._add_int_param( 4245 "min_candidate_size", self.min_candidate_size, min_val=0, max_val=int(1e4), 4246 tooltip=get_tooltip("autosegment", "min_candidate_size"), 4247 ) 4248 settings.layout().addLayout(layout) 4249 4250 self.score_threshold = values["score_threshold"] 4251 self.score_threshold_param, layout = self._add_float_param( 4252 "score_threshold", self.score_threshold, min_val=0.0, max_val=1.0, step=0.05, 4253 tooltip=get_tooltip("autosegment", "score_threshold"), 4254 ) 4255 settings.layout().addLayout(layout) 4256 4257 self.max_overlap = values["max_overlap"] 4258 self.max_overlap_param, layout = self._add_float_param( 4259 "max_overlap", self.max_overlap, min_val=0.0, max_val=1.0, step=0.05, 4260 tooltip=get_tooltip("autosegment", "max_overlap"), 4261 ) 4262 settings.layout().addLayout(layout) 4263 4264 self.min_object_size = values["min_object_size"] 4265 self.min_object_size_param, layout = self._add_int_param( 4266 "min_object_size", self.min_object_size, min_val=0, max_val=int(1e4), 4267 tooltip=get_tooltip("autosegment", "min_object_size"), 4268 ) 4269 settings.layout().addLayout(layout) 4270 4271 self.multimasking = DEFAULT_PROMPT_GENERATION["multimasking"] 4272 self.multimasking_checkbox = self._add_boolean_param( 4273 "multimasking", self.multimasking, tooltip=get_tooltip("autosegment", "multimasking"), 4274 ) 4275 settings.layout().addWidget(self.multimasking_checkbox) 4276 4277 self.refine_with_box_prompts = values["refine_with_box_prompts"] 4278 self.refine_with_box_prompts_checkbox = self._add_boolean_param( 4279 "refine_with_box_prompts", self.refine_with_box_prompts, 4280 tooltip=get_tooltip("autosegment", "refine_with_box_prompts"), 4281 ) 4282 settings.layout().addWidget(self.refine_with_box_prompts_checkbox) 4283 4284 self.box_extension = DEFAULT_REFINEMENT["box_extension"] 4285 self.box_extension_param, layout = self._add_int_param( 4286 "box_extension", self.box_extension, min_val=0, max_val=100, 4287 tooltip=get_tooltip("autosegment", "box_extension"), 4288 ) 4289 settings.layout().addLayout(layout) 4290 4291 self.prompt_batch_size = DEFAULT_PROMPT_GENERATION["batch_size"] 4292 self.prompt_batch_size_param, layout = self._add_int_param( 4293 "prompt_batch_size", self.prompt_batch_size, min_val=1, max_val=1024, 4294 tooltip=get_tooltip("autosegment", "prompt_batch_size"), 4295 ) 4296 settings.layout().addLayout(layout) 4297 4298 if self.volumetric and not self._is_tracking: 4299 self.n_objects_per_pass = DEFAULT_PROMPT_GENERATION["n_objects_per_pass"] 4300 self.n_objects_per_pass_param, layout = self._add_int_param( 4301 "n_objects_per_pass", self.n_objects_per_pass, min_val=1, max_val=1024, 4302 tooltip=get_tooltip("autosegment", "n_objects_per_pass"), 4303 ) 4304 settings.layout().addLayout(layout) 4305 4306 self.early_stop_patience = DEFAULT_PROMPT_GENERATION["early_stop_patience"] 4307 self.early_stop_patience_param, layout = self._add_int_param( 4308 "early_stop_patience", self.early_stop_patience, min_val=0, max_val=1024, 4309 tooltip=get_tooltip("autosegment", "early_stop_patience"), 4310 ) 4311 settings.layout().addLayout(layout) 4312 4313 self._add_flow_integration_params( 4314 settings, n_iter=defaults["n_iter"], dt=DEFAULT_PROMPT_GENERATION["dt"], sigma=values["sigma"], 4315 ) 4316 4317 def _postproc_kwargs(self): 4318 if self.mode == "dense": 4319 return dict( 4320 beta=self.beta, density_threshold=self.density_threshold, n_iter=self.n_iter, 4321 dt=self.dt, sigma=self.sigma, n_threads=self.n_threads, 4322 ) 4323 return dict( 4324 foreground_threshold=self.foreground_threshold, density_threshold=self.density_threshold, 4325 min_size=self.min_object_size, n_iter=self.n_iter, dt=self.dt, sigma=self.sigma, 4326 n_threads=self.n_threads, 4327 ) 4328 4329 def _apg_kwargs(self, ndim): 4330 candidate_threshold = self.candidate_threshold 4331 if ndim == 3: 4332 candidate_threshold = (candidate_threshold, self.candidate_threshold_high) 4333 refinement = "boxes" if self.refine_with_box_prompts else None 4334 refinement_kwargs = {"box_extension": self.box_extension} if refinement is not None else None 4335 4336 kwargs = dict( 4337 candidate_threshold=candidate_threshold, foreground_threshold=self.foreground_threshold, 4338 min_candidate_size=self.min_candidate_size, score_threshold=self.score_threshold, 4339 max_overlap=self.max_overlap, min_size=self.min_object_size, 4340 refinement=refinement, refinement_kwargs=refinement_kwargs, 4341 multimasking=bool(self.multimasking), batch_size=self.prompt_batch_size, 4342 n_iter=self.n_iter, dt=self.dt, sigma=self.sigma, n_threads=self.n_threads, 4343 ) 4344 if ndim == 3: 4345 kwargs["n_objects_per_pass"] = self.n_objects_per_pass 4346 kwargs["early_stop_patience"] = self.early_stop_patience or None 4347 return kwargs 4348 4349 def _apg_propose_kwargs(self): 4350 # The prompting stage: everything that decides which candidates are prompted, and how. 4351 return dict( 4352 candidate_threshold=self.candidate_threshold, foreground_threshold=self.foreground_threshold, 4353 n_iter=self.n_iter, dt=self.dt, sigma=self.sigma, min_candidate_size=self.min_candidate_size, 4354 multimasking=bool(self.multimasking), batch_size=self.prompt_batch_size, n_threads=self.n_threads, 4355 ) 4356 4357 def _apg_select_kwargs(self): 4358 # The merge stage: post-processing of the proposals, cheap next to the prompting. 4359 refinement = "boxes" if self.refine_with_box_prompts else None 4360 refinement_kwargs = {"box_extension": self.box_extension} if refinement is not None else None 4361 return dict( 4362 score_threshold=self.score_threshold, max_overlap=self.max_overlap, min_size=self.min_object_size, 4363 refinement=refinement, refinement_kwargs=refinement_kwargs, 4364 batch_size=self.prompt_batch_size, 4365 ) 4366 4367 def _run_ndim(self): 4368 # The dimensionality of the next run: 3 only for a volume segmented as a whole. Tracking 4369 # segments each frame in 2d, so it stays 2 there even with 'Track Timeseries' on. 4370 if self.volumetric and not self._is_tracking and getattr(self, "apply_to_volume", False): 4371 return 3 4372 return 2 4373 4374 def commit_settings(self): 4375 """The parameters of the current automatic segmentation, for the commit history. 4376 4377 Returns: 4378 A json-serializable dict with the mode and the parameters that mode runs with. 4379 """ 4380 settings = {"mode": self.mode} 4381 if self.mode == "apg": 4382 settings.update(self._apg_kwargs(self._run_ndim())) 4383 else: 4384 settings.update(self._postproc_kwargs()) 4385 4386 if self.volumetric: 4387 settings["apply_to_volume"] = bool(getattr(self, "apply_to_volume", False)) 4388 # The z block / halo exist only while the z-tiling controls are shown, see '_add_z_tiling_params'. 4389 if hasattr(self, "tile_z_param"): 4390 settings["tile_z"], settings["halo_z"] = self.tile_z, self.halo_z 4391 4392 return settings 4393 4394 def _z_tiling(self, n_slices): 4395 # The z block / halo for 3d decoder inference. 'tile_z' >= the slice count means no z-tiling 4396 # (the whole volume is decoded in one z block). 4397 z_block = self.tile_z if 0 < self.tile_z < n_slices else n_slices 4398 z_halo = self.halo_z if z_block < n_slices else 0 4399 return z_block, z_halo 4400 4401 def _state_save_path(self, state): 4402 # The state cache is opted into via the embedding settings' 'cache automatic segmentation state' 4403 # checkbox. When on, it persists next to the embeddings, else in-memory only ('_segmenter' cache). 4404 embed_widget = state.widgets.get("embeddings") 4405 return state.embedding_path if getattr(embed_widget, "cache_state", False) else None 4406 4407 def _release_segmenter(self): 4408 # Dropping the reference is not enough: the volumetric prompt generator holds a SAM2 video 4409 # inference state and an ephemeral embedding store, which only 'clear_state' releases. 4410 if self._segmenter is not None: 4411 self._segmenter.clear_state() 4412 self._segmenter = None 4413 self._segmenter_key = None 4414 self._proposals = None 4415 self._proposals_key = None 4416 4417 def _decoder_key(self, state, ndim, z, is_tiled, z_block, z_halo): 4418 # What the decoder prediction depends on. The mode is deliberately absent: the same 4419 # prediction feeds the 'sparse' and 'dense' post-processing and the 'apg' prompt generation. 4420 return (state.data_signature, ndim, z, is_tiled, z_block, z_halo) 4421 4422 def _cached_decoder_state(self, key): 4423 return self._decoder_state if self._decoder_state_key == key else None 4424 4425 def _store_decoder_state(self, key, decoder_state, save_path=None): 4426 self._decoder_state = dict(decoder_state) 4427 self._decoder_state_key = key 4428 self._decoder_state_save_path = save_path 4429 4430 def _persist_decoder_state(self, decoder_state, save_path, state_index, model_type): 4431 if save_path is None or getattr(self, "_decoder_state_save_path", None) == save_path: 4432 return 4433 from micro_sam.precompute_state import save_ais_state 4434 save_ais_state(decoder_state, save_path, state_index=state_index, model_type=model_type) 4435 self._decoder_state_save_path = save_path 4436 4437 def _drop_decoder_state(self): 4438 # Only for a new input or a new model: the prediction is derived from both. 4439 self._decoder_state = None 4440 self._decoder_state_key = None 4441 self._decoder_state_save_path = None 4442 4443 def _run_unisam2(self, state, run_raw, ndim, z, pbar_init=None, pbar_update=None): 4444 from micro_sam.precompute_state import cache_autoseg_state 4445 4446 device = next(state.decoder.parameters()).device 4447 model_type = getattr(state.predictor, "model_type", None) 4448 save_path = self._state_save_path(state) 4449 4450 # All decoder auto-seg cases reuse the precomputed embeddings and run the decoder on them (no 4451 # encoder re-run). The in-plane tiling is taken from the embeddings (tiled embeddings have a 4452 # top-level 'input_size' of None), so only the z entry of 'tile_shape'/'halo' below matters - 4453 # the y, x entries are filler, ignored by the decoder-from-embeddings path. This covers 2d 4454 # and 3d, tiled and untiled. 4455 tile_shape, halo = None, None 4456 z_block, z_halo = None, None 4457 if not self.volumetric or ndim == 3: 4458 # Plain 2d image, or the whole 3d volume: the precomputed embeddings match directly. 4459 image_embeddings = state.image_embeddings 4460 is_tiled = image_embeddings["input_size"] is None 4461 if ndim == 3: # the decoder pass is z-chunked using the auto-seg z block / halo controls. 4462 z_block, z_halo = self._z_tiling(int(run_raw.shape[0])) 4463 tile_shape = (z_block, run_raw.shape[1], run_raw.shape[2]) 4464 halo = (z_halo, 0, 0) 4465 else: 4466 # A single slice of a 3d volume: reuse that slice's features (no re-encode). For untiled 4467 # embeddings, build the slice's 2d embedding. For tiled embeddings, pass the tiled 3d 4468 # embeddings + slice index 'z' and let the segmenter reconstruct each tile's slice. 4469 emb3d = state.image_embeddings 4470 if emb3d is not None and emb3d.get("input_size") is not None: 4471 image_embeddings = { 4472 "features": np.asarray(emb3d["features"][z:z + 1]), 4473 "input_size": emb3d["input_size"], "original_size": emb3d["original_size"], 4474 } 4475 is_tiled = False 4476 else: 4477 image_embeddings, is_tiled = emb3d, True 4478 4479 # The in-memory cache avoids re-running the model when only the post-processing parameters 4480 # change. 'cache_autoseg_state' additionally persists the decoder predictions in the 4481 # embedding Zarr so a later run or session reuses them. The whole volume is 4482 # cached under one key ('state'); a single segmented slice under 'state-{z}'. 4483 cache_key = ( 4484 state.data_signature, "unisam2", ndim, z, tile_shape, halo, z_block, z_halo, 4485 image_embeddings is not None, save_path, 4486 ) 4487 decoder_key = self._decoder_key(state, ndim, z, is_tiled, z_block, z_halo) 4488 if self._segmenter is None or self._segmenter_key != cache_key: 4489 self._release_segmenter() 4490 decoder_state = self._cached_decoder_state(decoder_key) 4491 if decoder_state is None: 4492 self._segmenter = cache_autoseg_state( 4493 "ais", state.decoder, run_raw, image_embeddings, save_path, ndim=ndim, 4494 model_type=model_type, 4495 i=z, state_index=(None if ndim == 3 else z), is_tiled=is_tiled, 4496 tile_shape=tile_shape, halo=halo, device=device, devices=state.inference_devices, 4497 pbar_init=pbar_init, pbar_update=pbar_update, verbose=False, 4498 ) 4499 decoder_state = self._segmenter.get_state() 4500 self._store_decoder_state(decoder_key, decoder_state, save_path=save_path) 4501 else: 4502 from micro_sam.v2.instance_segmentation import get_unisam2_segmentation_generator 4503 self._segmenter = get_unisam2_segmentation_generator( 4504 state.decoder, is_tiled=is_tiled, device=device, inference_device=state.inference_devices, 4505 ) 4506 self._segmenter.set_state(decoder_state) 4507 self._persist_decoder_state( 4508 decoder_state, save_path, state_index=(None if ndim == 3 else z), model_type=model_type, 4509 ) 4510 self._segmenter_key = cache_key 4511 4512 return self._segmenter.generate(mode=self.mode, **self._postproc_kwargs()) 4513 4514 def _run_apg(self, state, run_raw, ndim, z, pbar_init=None, pbar_update=None): 4515 from micro_sam.precompute_state import cache_autoseg_state 4516 from micro_sam.v2.instance_segmentation import get_instance_segmentation_generator 4517 4518 model = getattr(state.predictor, "model", state.predictor) 4519 model_type = getattr(state.predictor, "model_type", None) 4520 device = next(state.decoder.parameters()).device 4521 save_path = self._state_save_path(state) 4522 image_embeddings = state.image_embeddings 4523 is_tiled = image_embeddings is not None and image_embeddings.get("input_size") is None 4524 decoder_embeddings = image_embeddings 4525 if z is not None and not is_tiled: 4526 decoder_embeddings = { 4527 "features": np.asarray(image_embeddings["features"][z:z + 1]), 4528 "input_size": image_embeddings["input_size"], 4529 "original_size": image_embeddings["original_size"], 4530 } 4531 4532 tile_shape, halo = None, None 4533 if is_tiled: 4534 attrs = image_embeddings["features"].attrs 4535 tile_shape = tuple(int(value) for value in attrs["tile_shape"]) 4536 halo = tuple(int(value) for value in attrs["halo"]) 4537 4538 z_block, z_halo = None, None 4539 decoder_tile_shape, decoder_halo = tile_shape, halo 4540 if ndim == 3: 4541 z_block, z_halo = self._z_tiling(int(run_raw.shape[0])) 4542 # The decoder's z chunk goes in front; y, x are the in-plane tiling above, or filler 4543 # (ignored by the decoder-from-embeddings path) when there is none. 4544 decoder_tile_shape = (z_block, *(tile_shape or run_raw.shape[1:3])) 4545 decoder_halo = (z_halo, *(halo or (0, 0))) 4546 4547 cache_key = ( 4548 state.data_signature, "apg", ndim, z, tile_shape, halo, z_block, z_halo, 4549 image_embeddings is not None, save_path, 4550 ) 4551 if self._segmenter is None or self._segmenter_key != cache_key: 4552 self._release_segmenter() 4553 self._segmenter = get_instance_segmentation_generator( 4554 model=model, decoder=state.decoder, is_tiled=is_tiled, segmentation_mode="apg", 4555 device=device, inference_device=state.inference_devices, ndim=ndim, 4556 ) 4557 if is_tiled: 4558 # The blocks use the tiling of the embeddings, so each block reads its tile. 4559 self._segmenter.initialize( 4560 run_raw, ndim=ndim, tile_shape=decoder_tile_shape, halo=decoder_halo, verbose=False, 4561 image_embeddings=image_embeddings, i=z, 4562 ) 4563 else: 4564 decoder_key = self._decoder_key(state, ndim, z, is_tiled, z_block, z_halo) 4565 decoder_state = self._cached_decoder_state(decoder_key) 4566 if decoder_state is None: 4567 decoder_segmenter = cache_autoseg_state( 4568 "ais", state.decoder, run_raw, decoder_embeddings, save_path, ndim=ndim, 4569 model_type=model_type, i=z, state_index=(None if ndim == 3 else z), 4570 is_tiled=False, tile_shape=decoder_tile_shape, halo=decoder_halo, device=device, 4571 devices=state.inference_devices, 4572 pbar_init=pbar_init, pbar_update=pbar_update, verbose=False, 4573 ) 4574 decoder_state = decoder_segmenter.get_state() 4575 self._store_decoder_state(decoder_key, decoder_state, save_path=save_path) 4576 self._persist_decoder_state( 4577 decoder_state, save_path, state_index=(None if ndim == 3 else z), model_type=model_type, 4578 ) 4579 apg_state = dict(decoder_state) 4580 apg_state["image_embeddings"] = image_embeddings 4581 if z is not None: 4582 apg_state["i"] = z 4583 if ndim == 3: 4584 apg_state["volume"] = run_raw 4585 self._segmenter.set_state(apg_state) 4586 self._segmenter_key = cache_key 4587 4588 if is_tiled: 4589 return self._segmenter.generate( 4590 **self._apg_kwargs(ndim), pbar_init=pbar_init, pbar_update=pbar_update, 4591 ) 4592 4593 if ndim == 3: # One pass: the volumetric stages are not separable the way the 2d ones are. 4594 return self._segmenter.generate( 4595 **self._apg_kwargs(ndim), pbar_init=pbar_init, pbar_update=pbar_update, 4596 ) 4597 4598 # 'propose' does the prompting and 'select' only merges, so re-running with a different 4599 # score / overlap / size replays the merge instead of prompting the model again. 4600 propose_kwargs = self._apg_propose_kwargs() 4601 proposals_key = (cache_key, tuple(sorted(propose_kwargs.items()))) 4602 if self._proposals is None or self._proposals_key != proposals_key: 4603 self._proposals = self._segmenter.propose( 4604 **propose_kwargs, pbar_init=pbar_init, pbar_update=pbar_update, 4605 ) 4606 self._proposals_key = proposals_key 4607 if pbar_init is not None: 4608 pbar_init(1, "APG: merging masks") 4609 segmentation = self._segmenter.select(self._proposals, **self._apg_select_kwargs()) 4610 if pbar_update is not None: 4611 pbar_update(1) 4612 return segmentation 4613 4614 def __call__(self): 4615 state = AnnotatorState() 4616 if not self.with_decoder or state.decoder is None: 4617 return _generate_message("error", NO_DECODER_MESSAGE) 4618 if _validate_layers(self._viewer, automatic_segmentation=True): 4619 return 4620 # Every mode reuses the precomputed image embeddings, so they must exist and match 4621 # the current image. If embeddings were reset (e.g. after an image change) this prompts the 4622 # user to recompute them instead of segmenting with stale embeddings. 4623 if _validate_embeddings(self._viewer): 4624 return 4625 4626 # Get the raw image and determine the run dimensionality. 4627 image_name = state.get_image_name(self._viewer) 4628 raw = np.asarray(self._viewer.layers[image_name].data) 4629 4630 apply_to_volume = self.volumetric and getattr(self, "apply_to_volume", False) 4631 z = None 4632 if apply_to_volume: 4633 run_raw, ndim = raw, 3 4634 elif self.volumetric: # segment only the current slice 4635 z = vutil.current_slice(self._viewer, self._viewer.layers[image_name]) 4636 run_raw, ndim = raw[z], 2 4637 else: 4638 run_raw, ndim = raw, 2 4639 4640 if self.mode == "apg": 4641 apg_error = _apg_error(state, self.volumetric, is_tracking=self._is_tracking) 4642 if apg_error is not None: 4643 return _generate_message("error", apg_error) 4644 4645 # Show progress in the napari activity dock: decoder tiles/slices, then APG prompt batches, 4646 # scoring slices or propagation passes. Each stage resets the count and total. 4647 # This tool disables thread workers (see top of module), so the run is 4648 # synchronous. We drive the bar via callbacks the backends call between units and pump the Qt 4649 # event loop with 'processEvents' on each update so it repaints live. It is always closed in 4650 # the 'finally' block. Batched 3d inference forwards completed tile-slice increments from its 4651 # worker threads to this calling thread so napari can repaint them safely. 4652 pbar, pbar_signals = _create_pbar_for_threadworker() 4653 4654 def pbar_init(total, description): 4655 pbar_signals.pbar_reset.emit() 4656 pbar_signals.pbar_total.emit(total) 4657 pbar_signals.pbar_description.emit(description) 4658 QtWidgets.QApplication.processEvents() 4659 4660 def pbar_update(update=1): 4661 pbar_signals.pbar_update.emit(update) 4662 QtWidgets.QApplication.processEvents() 4663 4664 pbar_signals.pbar_description.emit(f"Running automatic segmentation ({self.mode})") 4665 QtWidgets.QApplication.processEvents() 4666 try: 4667 if self.mode == "apg": 4668 seg = self._run_apg(state, run_raw, ndim, z, pbar_init=pbar_init, pbar_update=pbar_update) 4669 else: 4670 seg = self._run_unisam2(state, run_raw, ndim, z, pbar_init=pbar_init, pbar_update=pbar_update) 4671 finally: 4672 pbar_signals.pbar_stop.emit() 4673 4674 if z is None: 4675 self._viewer.layers["auto_segmentation"].data = seg 4676 else: 4677 self._viewer.layers["auto_segmentation"].data[z] = seg 4678 self._viewer.layers["auto_segmentation"].refresh() 4679 _select_layer(self._viewer, "auto_segmentation") 4680 self.segmentation_finished.emit() 4681 4682 4683class AutoTrackWidget(AutoSegmentWidget): 4684 _is_tracking = True 4685 _RUN_TOOLTIP = ("autotrack", "run_button") 4686 4687 def _create_widget(self): 4688 # Top row: the 'Track Timeseries' switch on the left, the mode dropdown on the right. 4689 top_row = QtWidgets.QHBoxLayout() 4690 4691 self.apply_to_volume = False 4692 self.apply_to_volume_checkbox = self._add_boolean_param( 4693 "apply_to_volume", 4694 self.apply_to_volume, 4695 title="Track Timeseries", 4696 tooltip=get_tooltip("autotrack", "run_tracking"), 4697 ) 4698 top_row.addWidget(self.apply_to_volume_checkbox) 4699 4700 self.mode_dropdown, mode_layout = self._add_choice_param( 4701 "mode", 4702 self.mode, 4703 list(self._available_modes()), 4704 title="mode:", 4705 update=self._on_mode_changed, 4706 tooltip=get_tooltip("autosegment", "mode"), 4707 ) 4708 # Keep the label at its text width so that the dropdown starts right after it and covers 4709 # the rest of the row. 4710 mode_layout.setStretch(0, 0) 4711 mode_layout.setStretch(1, 1) 4712 top_row.addLayout(mode_layout) 4713 4714 self.layout().addLayout(top_row) 4715 4716 self.settings = self._make_settings_widget() 4717 self.layout().addWidget(self.settings) 4718 4719 # The run button is only active with a decoder, since every mode needs one. 4720 self.run_button = QtWidgets.QPushButton("Automatic Tracking") 4721 self.run_button.clicked.connect(self.__call__) 4722 self.layout().addWidget(self.run_button) 4723 self._update_run_button() 4724 4725 def _empty_tracking_warning(self): 4726 return _generate_message( 4727 "error", 4728 "The automatic tracking result does not contain any objects. " 4729 "Try adjusting the automatic tracking settings.", 4730 ) 4731 4732 def _run_frame_segmentation(self, state, frame, frame_id, pbar_init=None, pbar_update=None): 4733 # Forward the progress callbacks so a frame advances the overall bar per tile (tiled) or by 4734 # one step (untiled). The caller passes a no-op 'pbar_init' so a frame cannot reset the total. 4735 if self.mode == "apg": 4736 return self._run_apg(state, frame, 2, frame_id, pbar_init=pbar_init, pbar_update=pbar_update) 4737 return self._run_unisam2(state, frame, 2, frame_id, pbar_init=pbar_init, pbar_update=pbar_update) 4738 4739 def _n_inplane_tiles(self, state, raw): 4740 # In-plane tiles per frame for the current run (1 if not tiled). The auto-tracking bar 4741 # advances per tile, so its total is this times the number of frames. 4742 from bioimage_cpp.utils import Blocking 4743 4744 # The modes reuse the precomputed embeddings; tiled ones have no top-level input_size. 4745 emb = state.image_embeddings 4746 tile_shape = None 4747 if emb is not None and emb.get("input_size") is None: 4748 tile_shape = tuple(int(s) for s in emb["features"].attrs["tile_shape"]) 4749 if tile_shape is None: 4750 return 1 4751 return Blocking([0, 0], list(raw.shape[1:3]), list(tile_shape)).number_of_blocks 4752 4753 def _track_timeseries(self, state, raw): 4754 segmentation = np.zeros_like(self._viewer.layers["auto_segmentation"].data) 4755 pbar, pbar_signals = _create_pbar_for_threadworker() 4756 offset = 0 4757 4758 def tracking_pbar_init(total, description): 4759 pbar_signals.pbar_total.emit(total) 4760 pbar_signals.pbar_description.emit(description) 4761 QtWidgets.QApplication.processEvents() 4762 4763 def tracking_pbar_update(update=1): 4764 pbar_signals.pbar_update.emit(update) 4765 QtWidgets.QApplication.processEvents() 4766 4767 # Decoder modes share a total over all frames. APG has candidate-dependent stages, 4768 # so reset for each stage and keep the frame number in its description. 4769 def frame_pbar_init(total, description): 4770 # APG reports several stages per frame, whose totals depend on its candidates. 4771 if self.mode == "apg": 4772 pbar_signals.pbar_reset.emit() 4773 tracking_pbar_init(total, f"Frame {frame_id + 1}/{len(raw)} - {description}") 4774 4775 n_tiles = self._n_inplane_tiles(state, raw) 4776 try: 4777 # Decoder modes advance per tile (or once per untiled frame). APG replaces this 4778 # initial total as soon as its first stage starts. 4779 pbar_signals.pbar_total.emit(n_tiles * len(raw)) 4780 QtWidgets.QApplication.processEvents() 4781 for frame_id, frame in enumerate(raw): 4782 pbar_signals.pbar_description.emit( 4783 f"Automatic segmentation ({self.mode}): frame {frame_id + 1}/{len(raw)}" 4784 ) 4785 QtWidgets.QApplication.processEvents() 4786 seg = self._run_frame_segmentation( 4787 state, frame, frame_id, pbar_init=frame_pbar_init, pbar_update=tracking_pbar_update, 4788 ) 4789 seg_max = int(seg.max()) 4790 if seg_max != 0: 4791 seg[seg != 0] += offset 4792 offset += seg_max 4793 segmentation[frame_id] = seg 4794 4795 if offset == 0: 4796 self._viewer.layers["auto_segmentation"].data = segmentation 4797 self._viewer.layers["auto_segmentation"].refresh() 4798 return self._empty_tracking_warning() 4799 4800 pbar_signals.pbar_reset.emit() 4801 segmentation, lineages = track_across_frames( 4802 raw, 4803 segmentation, 4804 verbose=True, 4805 pbar_init=tracking_pbar_init, 4806 pbar_update=tracking_pbar_update, 4807 ) 4808 finally: 4809 pbar_signals.pbar_stop.emit() 4810 4811 state.auto_lineages = lineages 4812 self._viewer.layers["auto_segmentation"].data = segmentation 4813 self._viewer.layers["auto_segmentation"].refresh() 4814 _select_layer(self._viewer, "auto_segmentation") 4815 self.segmentation_finished.emit() 4816 4817 def __call__(self): 4818 state = AnnotatorState() 4819 if not self.with_decoder or state.decoder is None: 4820 return _generate_message("error", NO_DECODER_MESSAGE) 4821 # Tracking prompts the video predictor per frame, so APG needs an accelerator here for a 4822 # single frame just as much as for the whole timeseries. Checked before the single-frame 4823 # delegation below so both paths are covered. 4824 if self.mode == "apg": 4825 apg_error = _apg_error(state, self.volumetric, is_tracking=True) 4826 if apg_error is not None: 4827 return _generate_message("error", apg_error) 4828 4829 if not (self.volumetric and getattr(self, "apply_to_volume", False)): 4830 return super().__call__() 4831 if _validate_layers(self._viewer, automatic_segmentation=True): 4832 return None 4833 if state.committed_lineages: 4834 return _generate_message( 4835 "error", 4836 "Automatic tracking can only be called if you have not committed interactive tracking results yet.", 4837 ) 4838 4839 image_name = state.get_image_name(self._viewer) 4840 raw = np.asarray(self._viewer.layers[image_name].data) 4841 if raw.ndim != 3: 4842 return _generate_message("error", "Automatic tracking expects a 2d timeseries.") 4843 return self._track_timeseries(state, raw)
74class CheckableComboBox(QtWidgets.QComboBox): 75 """A dropdown with a checkbox per item, to select several items at once. 76 77 Args: 78 items: The item names. 79 labels: Optional display text per item. By default the item names are shown. 80 parent: The parent widget. 81 """ 82 selection_changed = Signal() 83 84 def __init__(self, items, labels=None, parent=None): 85 super().__init__(parent) 86 self._items = list(items) 87 labels = self._items if labels is None else list(labels) 88 self._model = QStandardItemModel(self) 89 for label in labels: 90 item = QStandardItem(label) 91 # The click handler toggles the state, so the item itself is not user-checkable. 92 item.setFlags(Qt.ItemIsEnabled) 93 item.setData(Qt.Checked, Qt.CheckStateRole) 94 self._model.appendRow(item) 95 self.setModel(self._model) 96 self.view().pressed.connect(self._toggle) 97 self._keep_open = False 98 # The closed box only shows a short summary, so the long item names must not widen the panel. 99 self.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) 100 self.setMinimumContentsLength(12) 101 self.view().setMinimumWidth(self.view().sizeHintForColumn(0) + 40) 102 103 def _toggle(self, index): 104 item = self._model.itemFromIndex(index) 105 checked = item.data(Qt.CheckStateRole) == Qt.Checked 106 item.setData(Qt.Unchecked if checked else Qt.Checked, Qt.CheckStateRole) 107 self._keep_open = True 108 self.update() 109 self.selection_changed.emit() 110 111 def hidePopup(self): 112 # Keep the popup open while the user toggles items. 113 if self._keep_open: 114 self._keep_open = False 115 return 116 super().hidePopup() 117 118 def selected(self): 119 """Return the names of the checked items.""" 120 return [ 121 name for row, name in enumerate(self._items) 122 if self._model.item(row).data(Qt.CheckStateRole) == Qt.Checked 123 ] 124 125 def set_selected(self, names): 126 """Check exactly the items in `names`.""" 127 for row, name in enumerate(self._items): 128 self._model.item(row).setData(Qt.Checked if name in names else Qt.Unchecked, Qt.CheckStateRole) 129 self.update() 130 self.selection_changed.emit() 131 132 def paintEvent(self, event): 133 # Show a summary of the selection instead of the current item. 134 n_selected = len(self.selected()) 135 if n_selected == len(self._items): 136 text = "all features" 137 elif n_selected == 0: 138 text = "no features" 139 else: 140 text = f"{n_selected} of {len(self._items)} features" 141 painter = QtWidgets.QStylePainter(self) 142 option = QtWidgets.QStyleOptionComboBox() 143 self.initStyleOption(option) 144 option.currentText = text 145 painter.drawComplexControl(QtWidgets.QStyle.CC_ComboBox, option) 146 painter.drawControl(QtWidgets.QStyle.CE_ComboBoxLabel, option)
A dropdown with a checkbox per item, to select several items at once.
Arguments:
- items: The item names.
- labels: Optional display text per item. By default the item names are shown.
- parent: The parent widget.
84 def __init__(self, items, labels=None, parent=None): 85 super().__init__(parent) 86 self._items = list(items) 87 labels = self._items if labels is None else list(labels) 88 self._model = QStandardItemModel(self) 89 for label in labels: 90 item = QStandardItem(label) 91 # The click handler toggles the state, so the item itself is not user-checkable. 92 item.setFlags(Qt.ItemIsEnabled) 93 item.setData(Qt.Checked, Qt.CheckStateRole) 94 self._model.appendRow(item) 95 self.setModel(self._model) 96 self.view().pressed.connect(self._toggle) 97 self._keep_open = False 98 # The closed box only shows a short summary, so the long item names must not widen the panel. 99 self.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) 100 self.setMinimumContentsLength(12) 101 self.view().setMinimumWidth(self.view().sizeHintForColumn(0) + 40)
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
111 def hidePopup(self): 112 # Keep the popup open while the user toggles items. 113 if self._keep_open: 114 self._keep_open = False 115 return 116 super().hidePopup()
hidePopup(self, /)
118 def selected(self): 119 """Return the names of the checked items.""" 120 return [ 121 name for row, name in enumerate(self._items) 122 if self._model.item(row).data(Qt.CheckStateRole) == Qt.Checked 123 ]
Return the names of the checked items.
125 def set_selected(self, names): 126 """Check exactly the items in `names`.""" 127 for row, name in enumerate(self._items): 128 self._model.item(row).setData(Qt.Checked if name in names else Qt.Unchecked, Qt.CheckStateRole) 129 self.update() 130 self.selection_changed.emit()
Check exactly the items in names.
132 def paintEvent(self, event): 133 # Show a summary of the selection instead of the current item. 134 n_selected = len(self.selected()) 135 if n_selected == len(self._items): 136 text = "all features" 137 elif n_selected == 0: 138 text = "no features" 139 else: 140 text = f"{n_selected} of {len(self._items)} features" 141 painter = QtWidgets.QStylePainter(self) 142 option = QtWidgets.QStyleOptionComboBox() 143 self.initStyleOption(option) 144 option.currentText = text 145 painter.drawComplexControl(QtWidgets.QStyle.CC_ComboBox, option) 146 painter.drawControl(QtWidgets.QStyle.CE_ComboBoxLabel, option)
paintEvent(self, e: QPaintEvent | None, /)
664class PBarSignals(QObject): 665 pbar_total = Signal(int) 666 pbar_update = Signal(int) 667 pbar_description = Signal(str) 668 pbar_stop = Signal() 669 pbar_reset = Signal()
QObject(parent: Self = None)
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
672class InfoDialog(QtWidgets.QDialog): 673 def __init__(self, title, message, buttons=("OK", "Cancel")): 674 super().__init__() 675 self.setWindowTitle(title) 676 # Label of the button the user clicked (None if the dialog was closed without a button). 677 self.clicked_label = None 678 # The first button accepts the dialog. The rest reject it. 679 self._accept_label = buttons[0] 680 681 layout = QtWidgets.QVBoxLayout() 682 layout.addWidget(QtWidgets.QLabel(message)) 683 684 # The buttons sit side by side. The first is the default, so Enter triggers it. 685 button_box = QtWidgets.QHBoxLayout() 686 for i, label in enumerate(buttons): 687 button = QtWidgets.QPushButton(label) 688 button.clicked.connect(lambda checked=False, lbl=label: self.button_clicked(lbl)) 689 if i == 0: 690 button.setDefault(True) 691 button.setFocus() 692 button_box.addWidget(button) 693 694 layout.addLayout(button_box) 695 self.setLayout(layout) 696 697 def button_clicked(self, label): 698 self.clicked_label = label 699 if label == self._accept_label: 700 self.accept() 701 else: 702 self.reject()
QDialog(parent: QWidget | None = None, flags: Qt.WindowType = Qt.WindowFlags())
673 def __init__(self, title, message, buttons=("OK", "Cancel")): 674 super().__init__() 675 self.setWindowTitle(title) 676 # Label of the button the user clicked (None if the dialog was closed without a button). 677 self.clicked_label = None 678 # The first button accepts the dialog. The rest reject it. 679 self._accept_label = buttons[0] 680 681 layout = QtWidgets.QVBoxLayout() 682 layout.addWidget(QtWidgets.QLabel(message)) 683 684 # The buttons sit side by side. The first is the default, so Enter triggers it. 685 button_box = QtWidgets.QHBoxLayout() 686 for i, label in enumerate(buttons): 687 button = QtWidgets.QPushButton(label) 688 button.clicked.connect(lambda checked=False, lbl=label: self.button_clicked(lbl)) 689 if i == 0: 690 button.setDefault(True) 691 button.setFocus() 692 button_box.addWidget(button) 693 694 layout.addLayout(button_box) 695 self.setLayout(layout)
Widget for clearing the current annotations.
Arguments:
- viewer: The napari viewer.
Widget for clearing the current annotations in 3D.
Arguments:
- viewer: The napari viewer.
- all_slices: Choose whether to clear the annotations for all or only the current slice.
Widget for clearing all tracking annotations and state.
Arguments:
- viewer: The napari viewer.
- all_frames: Choose whether to clear the annotations for all or only the current frame.
Widget for committing the segmented objects from automatic or interactive segmentation.
Arguments:
- viewer: The napari viewer.
- layer: Select the layer to commit. Can be either 'current_object' to commit interacitve segmentation results. Or 'auto_segmentation' to commit automatic segmentation results. The annotator selects the layer of the last segmentation. The user can change it.
- preserve_mode: The mode for preserving already committed objects, in order to prevent over-writing them by a new commit. Supports the modes 'objects', which preserves on the object level, 'pixels', which preserves on the pixel-level and is the default, or 'none', which does not preserve commited objects.
- preservation_threshold: The overlap threshold for preserving objects. This is only used if preservation_mode is set to 'objects'.
- commit_path: Select a file path where the committed results and prompts will be saved. This feature is not implemented yet and will be supported in a future release.
Widget for committing the objects from interactive tracking.
Arguments:
- viewer: The napari viewer.
- layer: Select the layer to commit. Can be either 'current_object' to commit interacitve segmentation results. Or 'auto_segmentation' to commit automatic segmentation results. The annotator selects the layer of the last segmentation. The user can change it.
- preserve_mode: The mode for preserving already committed objects, in order to prevent over-writing them by a new commit. Supports the modes 'objects', which preserves on the object level, 'pixels', which preserves on the pixel-level and is the default, or 'none', which does not preserve commited objects.
- preservation_threshold: The overlap threshold for preserving objects. This is only used if preservation_mode is set to 'objects'.
- commit_path: Select a file path where the committed results and prompts will be saved. This feature is still experimental.
Widget for exporting the committed tracking result.
Arguments:
- viewer: The napari viewer.
- export_format: The tracking export format. Supports 'CTC', 'GEFF' and 'TrackMate XML'.
- export_folder: The folder where the export is written. By default the current working directory is used.
Widget to update global micro_sam settings.
Arguments:
- cache_directory: Select the path for the micro_sam cache directory.
$HOME/.cache/micro_sam.
Segment object(s) for the current prompts.
Arguments:
- viewer: The napari viewer.
- batched: Choose if you want to segment multiple objects with point prompts.
1777class EmbeddingWidget(_WidgetBase): 1778 # Whether to show the CPU info popup for expensive (many-tile / 3D) computations. 1779 warn_on_cpu = True 1780 1781 # A tiled 2D image only gets slow on the CPU once it has many tiles. Warn from this many on. 1782 cpu_warn_tiles = 64 1783 1784 # Whether to offer the 'cache automatic segmentation state' option (segmentation / tracking only, 1785 # not the classification tools which have no automatic segmentation). 1786 supports_state_caching = True 1787 1788 def __init__(self, parent=None, ndim_choice=False, is_timeseries=False): 1789 super().__init__(parent=parent) 1790 # Whether to expose the 'image dimensions' (ndim) override dropdown. Only the segmentation 1791 # annotator wires it into image normalization, so it is off by default (hidden for tracking 1792 # and the classifiers, which do not use it). 1793 self.ndim_choice = ndim_choice 1794 # The tracking annotator operates on a (T, H, W) timeseries, not a 3D volume. Relabel the 1795 # embedding progress accordingly (the underlying compute path is the same as for 3D). 1796 self.is_timeseries = is_timeseries 1797 1798 # Create a nested layout for the sections. 1799 # Section 1: Image and Model. 1800 section1_layout = QtWidgets.QHBoxLayout() 1801 section1_layout.addLayout(self._create_image_section()) 1802 # Default to the single-source 'DEFAULT_MODEL' (the 'Microscopy' / 'hvit_t_cells' model); 1803 # '_create_model_section' derives the synthetic selector string from it when no value is given. 1804 section1_layout.addLayout( 1805 self._create_model_section() 1806 ) # Creates the model family widget section. 1807 self.layout().addLayout(section1_layout) 1808 1809 # Section 2: Settings (collapsible). 1810 self.layout().addWidget(self._create_settings_widget()) 1811 1812 # Enable sensible default tiling when a large image is selected. 1813 self.image_selection.changed.connect(self._set_default_tiling) 1814 self._set_default_tiling() 1815 1816 # Section 3: The button to trigger the embedding computation. 1817 self.run_button = QtWidgets.QPushButton("Compute Embeddings") 1818 self.run_button.clicked.connect(self.__call__) 1819 self.run_button.setToolTip(get_tooltip("embedding", "run_button")) 1820 self.layout().addWidget(self.run_button) 1821 1822 def _create_image_section(self): 1823 image_section = QtWidgets.QVBoxLayout() 1824 layer_label = "Timeseries Layer:" if self.is_timeseries else "Image Layer:" 1825 self.image_layer_label = QtWidgets.QLabel(layer_label) 1826 # self.image_layer_label.setToolTip(get_tooltip("embedding", "image")) # this adds tooltip to label 1827 image_section.addWidget(self.image_layer_label) 1828 1829 # Setting a napari layer in QT, see: 1830 # https://github.com/pyapp-kit/magicgui/blob/main/docs/examples/napari/napari_combine_qt.py 1831 self.image_selection = create_widget(annotation=napari.layers.Image) 1832 self.image_selection.native.setToolTip( 1833 get_tooltip("embedding", "image") 1834 ) 1835 image_section.addWidget(self.image_selection.native) 1836 1837 return image_section 1838 1839 def _update_model(self, state): 1840 _model_type = ( 1841 state.predictor.model_type 1842 if self.custom_weights 1843 else self.model_type 1844 ) 1845 1846 # Provide a detailed message for the model family and model size per chosen combination. 1847 msg = "Computed embeddings for " 1848 if ( 1849 self.custom_weights 1850 ): # Whether the user provided a filepath to custom finetuned model weights. 1851 msg += f"the model located at '{os.path.abspath(self.custom_weights)}' " 1852 # The size letter follows the backbone prefix: 'hvit_b...' for SAM2, 'vit_b...' for SAM1. 1853 size_key = _model_type[len("hvit_") if _model_type.startswith("hvit_") else len("vit_"):][:1] 1854 msg += f"of size '{self._model_size_map.get(size_key, self.model_size)}'." 1855 else: 1856 msg += ( 1857 f"the '{self.model_family}' model of size '{self.model_size}'." 1858 ) 1859 1860 show_info(msg) 1861 1862 state = AnnotatorState() 1863 # Update the widget itself. This is necessary because we may have loaded 1864 # some settings from the embedding file and have to reflect them in the widget. 1865 vutil._sync_embedding_widget( 1866 self, 1867 model_type=_model_type, 1868 save_path=self.embeddings_save_path, 1869 checkpoint_path=self.custom_weights, 1870 device=self.device, 1871 # Only forward tiling params when tiling is actually enabled. Otherwise '_sync_embedding_widget' 1872 # would force the tiling dropdown to "yes" using the (always-nonzero) default tile values. 1873 tile_shape=[self.tile_x, self.tile_y] if self.tiling == "yes" else None, 1874 halo=[self.halo_x, self.halo_y] if self.tiling == "yes" else None, 1875 ) 1876 1877 # Set the default settings for this model in the autosegment widget if it is part of 1878 # the currently used plugin. 1879 if "autosegment" in state.widgets: 1880 with_decoder = state.decoder is not None 1881 vutil._sync_autosegment_widget( 1882 state.widgets["autosegment"], 1883 _model_type, 1884 self.custom_weights, 1885 update_decoder=with_decoder, 1886 ) 1887 # Record the location of the cached decoder predictions. The widget reads and writes the cache. 1888 if with_decoder: 1889 state.autoseg_state = vutil._autoseg_state_descriptor(state.embedding_path, "ais") 1890 else: 1891 state.autoseg_state = None 1892 1893 # Now that the (possibly tiled) embeddings are known, refresh the 'Batched' control on the 1894 # segment/track widgets: batched prompting is unsupported with tiling, so it is hidden then. 1895 for widget in state.widgets.values(): 1896 update_batched = getattr(widget, "_update_batched_visibility", None) 1897 if callable(update_batched): 1898 update_batched() 1899 1900 def _create_settings_widget(self): 1901 setting_values = QtWidgets.QWidget() 1902 setting_values.setToolTip(get_tooltip("embedding", "settings")) 1903 setting_values.setLayout(QtWidgets.QVBoxLayout()) 1904 1905 # The dropdown rows of this panel, collected so that they get a uniform layout at the end. 1906 choice_rows = [] 1907 1908 # Optional image dimensionality override. 'auto' detects 2d or 3d (including channels) from the 1909 # selected image. '2d' and '3d' force the interpretation, e.g. to read a channels-first 1910 # (C, H, W) array as a 2d multi-channel image. 1911 if self.ndim_choice: 1912 self.image_ndim_mode = "auto" 1913 self.image_ndim_dropdown, ndim_layout = self._add_choice_param( 1914 "image_ndim_mode", self.image_ndim_mode, ["auto", "2d", "3d"], title="image dimensions:", 1915 tooltip=get_tooltip("embedding", "image_ndim"), 1916 ) 1917 # Forcing '2d' on a volume removes the slices the batch would span. 1918 self.image_ndim_dropdown.currentIndexChanged.connect(self._refresh_batch_size) 1919 setting_values.layout().addLayout(ndim_layout) 1920 choice_rows.append(ndim_layout) 1921 1922 # Create UI for tiling. A dropdown toggles whether the tool uses tiling. When you enable it, 1923 # the tile shape and halo fields appear with sensible defaults. 1924 self.tiling = "no" 1925 self.tiling_dropdown, tiling_layout = self._add_choice_param( 1926 "tiling", 1927 self.tiling, 1928 ["no", "yes"], 1929 title="tiling:", 1930 update=self._update_tiling_visibility, 1931 tooltip=get_tooltip("embedding", "tiling"), 1932 ) 1933 setting_values.layout().addLayout(tiling_layout) 1934 choice_rows.append(tiling_layout) 1935 1936 # Container holding the tile shape and halo fields (hidden unless tiling is 'yes'). 1937 self._tiling_widget = QtWidgets.QWidget() 1938 self._tiling_widget.setLayout(QtWidgets.QVBoxLayout()) 1939 self._tiling_widget.layout().setContentsMargins(0, 0, 0, 0) 1940 1941 # In-plane (xy) tile shape and halo, used when tiling is enabled. The defaults come from the 1942 # central v2 tiling values. The z block / halo are not set here: they only affect 3d automatic 1943 # segmentation (not the embeddings, which are tiled in-plane only), so they live in the 1944 # automatic segmentation settings instead. 1945 from micro_sam.v2.util import DEFAULT_TILE_SHAPE, DEFAULT_HALO 1946 self.tile_x, self.tile_y = DEFAULT_TILE_SHAPE 1947 self.tile_x_param, self.tile_y_param, tile_layout = self._add_shape_param( 1948 ("tile_x", "tile_y"), 1949 (self.tile_x, self.tile_y), 1950 min_val=0, 1951 max_val=2048, 1952 step=16, 1953 tooltip=get_tooltip("embedding", "tiling"), 1954 ) 1955 self._tiling_widget.layout().addLayout(tile_layout) 1956 1957 self.halo_x, self.halo_y = DEFAULT_HALO 1958 self.halo_x_param, self.halo_y_param, halo_layout = self._add_shape_param( 1959 ("halo_x", "halo_y"), 1960 (self.halo_x, self.halo_y), 1961 min_val=0, 1962 max_val=512, 1963 title=("overlap_x", "overlap_y"), 1964 tooltip=get_tooltip("embedding", "halo"), 1965 ) 1966 self._tiling_widget.layout().addLayout(halo_layout) 1967 1968 self._tiling_widget.setVisible(False) 1969 setting_values.layout().addWidget(self._tiling_widget) 1970 1971 # Add the model size widget section. 1972 model_size_layout = self._create_model_size_section() 1973 setting_values.layout().addLayout(model_size_layout) 1974 choice_rows.append(model_size_layout) 1975 1976 # Create UI for the device. 1977 self.device = "auto" 1978 device_options = ["auto"] + util._available_devices() 1979 1980 self.device_dropdown, device_layout = self._add_choice_param( 1981 "device", 1982 self.device, 1983 device_options, 1984 tooltip=get_tooltip("embedding", "device"), 1985 ) 1986 setting_values.layout().addLayout(device_layout) 1987 choice_rows.append(device_layout) 1988 1989 # The batch size follows the model and the device until the user edits it, after which their 1990 # value is kept. Until then it only previews what the backend will pick per device, see 1991 # '_effective_batch_size'. Batching only helps on a GPU, so the control is hidden whenever the 1992 # effective device is the CPU. Both visibility and value track the device dropdown, so they 1993 # also update when the user switches devices or when 'auto' resolves to the CPU. 1994 self.batch_size = 1 1995 self._batch_size_is_auto = True 1996 self.batch_size_param, batch_size_layout = self._add_int_param( 1997 "batch_size", self.batch_size, min_val=1, max_val=64, 1998 title="batch size", 1999 tooltip=get_tooltip("embedding", "batch_size"), 2000 ) 2001 self.batch_size_param.valueChanged.connect(self._on_batch_size_edited) 2002 self._batch_size_widget = QtWidgets.QWidget() 2003 self._batch_size_widget.setLayout(batch_size_layout) 2004 setting_values.layout().addWidget(self._batch_size_widget) 2005 self.device_dropdown.currentIndexChanged.connect(self._refresh_batch_size) 2006 self._refresh_batch_size() 2007 2008 # Create UI for the save path. 2009 self.embeddings_save_path = None 2010 self.embeddings_save_path_param, save_layout = self._add_path_param( 2011 "embeddings_save_path", 2012 self.embeddings_save_path, 2013 "directory", 2014 title="embeddings save path:", 2015 tooltip=get_tooltip("embedding", "embeddings_save_path"), 2016 ) 2017 setting_values.layout().addLayout(save_layout) 2018 2019 # Create UI for the custom weights. 2020 self.custom_weights = None 2021 self.custom_weights_param, weights_layout = self._add_path_param( 2022 "custom_weights", 2023 self.custom_weights, 2024 "file", 2025 title="custom weights path:", 2026 tooltip=get_tooltip("embedding", "custom_weights"), 2027 ) 2028 setting_values.layout().addLayout(weights_layout) 2029 2030 # Make the two path rows symmetric: equal label widths, so their text boxes match too. 2031 self._align_widths([save_layout.itemAt(0).widget(), weights_layout.itemAt(0).widget()]) 2032 # Move the horizontal space trimmed from the text boxes into the browse buttons (rather than 2033 # leaving a gap): widen them uniformly by that amount ('Select Directory' is wider than 2034 # 'Select File', which would otherwise offset the rows). 2035 path_button_extra = 20 2036 save_button = save_layout.itemAt(save_layout.count() - 1).widget() 2037 weights_button = weights_layout.itemAt(weights_layout.count() - 1).widget() 2038 button_width = max(save_button.sizeHint().width(), weights_button.sizeHint().width()) + path_button_extra 2039 for button in (save_button, weights_button): 2040 button.setFixedWidth(button_width) 2041 2042 # Give the dropdowns a slightly larger share of their row than the labels, so that they extend 2043 # a bit further to the left (their right edge stays at the panel margin). 2044 for row in choice_rows: 2045 row.setStretch(0, 4) 2046 row.setStretch(1, 5) 2047 2048 # Opt-in disk caching of the automatic-segmentation state (off by default). When on, the state 2049 # is precomputed to disk (next to the embeddings) while the embeddings are computed and reused 2050 # across runs / sessions. The automatic segmentation widget reads this flag from here. Not 2051 # offered by the classification tools (no automatic segmentation). 2052 self.cache_state = False 2053 if self.supports_state_caching: 2054 self.cache_state_checkbox = self._add_boolean_param( 2055 "cache_state", self.cache_state, title="cache automatic segmentation state", 2056 tooltip=get_tooltip("embedding", "cache_state"), 2057 ) 2058 setting_values.layout().addWidget(self.cache_state_checkbox) 2059 2060 # Hook for subclasses to add extra model controls at the end of the settings (no-op by default). 2061 self._add_extra_model_settings(setting_values.layout()) 2062 2063 settings = _make_collapsible( 2064 setting_values, title="Embedding Settings", tooltip=get_tooltip("embedding", "settings"), 2065 ) 2066 return settings 2067 2068 def _add_extra_model_settings(self, layout): 2069 """Hook to add extra model controls to the embedding settings. It does nothing by default. 2070 The classification embedding widget uses it to add the optional advanced-model selector.""" 2071 pass 2072 2073 def _apply_loaded_model_selection(self, model_name): 2074 """Reflect a loaded model in the model family and size dropdowns. It does nothing by default: 2075 the post-compute '_sync_embedding_widget' already syncs the SAM2-only widget, whose family 2076 names match. Subclasses with custom family handling (classification) override this.""" 2077 pass 2078 2079 def _selected_image_shape(self): 2080 # Spatial shape of the currently selected image layer (any channel axis removed), or None if 2081 # no image is selected. 2082 image = self.image_selection.get_value() 2083 if image is None: 2084 return None 2085 return image.data.shape[:-1] if image.rgb else image.data.shape 2086 2087 def _selected_image_ndim(self): 2088 # Spatial dimensionality of the currently selected image layer (2 or 3), or None if no image. 2089 shape = self._selected_image_shape() 2090 return None if shape is None else len(shape) 2091 2092 def _ndim_override(self): 2093 # The user-selected image dimensionality override: None for 'auto', else 2 or 3. Read the 2094 # dropdown directly so the value is correct regardless of signal ordering. 2095 dropdown = getattr(self, "image_ndim_dropdown", None) 2096 mode = dropdown.currentText() if dropdown is not None else "auto" 2097 return {"auto": None, "2d": 2, "3d": 3}.get(mode) 2098 2099 def _update_tiling_visibility(self, index=None): 2100 # Show the in-plane tile shape and halo fields only when tiling is enabled. 2101 self.tiling = self.tiling_dropdown.currentText() 2102 self._tiling_widget.setVisible(self.tiling == "yes") 2103 # Tiling decides whether a 2d image has anything to batch over. This also runs on image 2104 # selection, via '_set_default_tiling'. 2105 if getattr(self, "_batch_size_widget", None) is not None: 2106 self._refresh_batch_size() 2107 2108 def _batch_size_has_effect(self): 2109 # Batching does not help on the CPU (so 'auto' resolving to the CPU counts as no effect), and 2110 # the VFM encoders offered by the classifiers compute their embeddings unbatched. 2111 from micro_sam.models.vfm import is_vfm_model 2112 2113 device = self.device 2114 if device == "auto": 2115 device = util._get_default_device() 2116 if util.device_type(device) == "cpu" or is_vfm_model(getattr(self, "model_type", None)): 2117 return False 2118 2119 # A 2d image without tiling is a single encoder call, so there is nothing to batch. Tiles and 2120 # z slices are what the batch spans. An unknown dimensionality (no image yet) keeps the field. 2121 ndim = self._ndim_override() or self._selected_image_ndim() 2122 return not (ndim == 2 and self.tiling != "yes") 2123 2124 def _batch_size_is_tabulated(self): 2125 # Whether the VRAM table covers the selected model. It is calibrated for the SAM2 encoders; 2126 # SAM1 and the VFM encoders keep a batch of one. 2127 from micro_sam.v2.util import SUPPORTED_MODELS 2128 2129 model_type = getattr(self, "model_type", None) 2130 return bool(model_type) and str(model_type)[:6] in SUPPORTED_MODELS 2131 2132 def _effective_batch_size(self): 2133 """The batch size handed to the backend, or None for it to choose one per device. 2134 2135 The displayed value is only a preview (see `_recommended_batch_size`), so while the user has 2136 not edited it the SAM2 backend picks its own value per device, once the weights are placed 2137 there. A value the user typed, or one where batching has no effect, is forwarded verbatim. 2138 """ 2139 if not self._batch_size_has_effect(): 2140 return 1 2141 if self._batch_size_is_auto and self._batch_size_is_tabulated(): 2142 return None 2143 return self.batch_size 2144 2145 def _encoder_job_count(self): 2146 # The number of encoder calls the selected image needs (tiles, z slices, or both), or None 2147 # while no image is selected. Mirrors how the backend splits the input, so the preview is 2148 # never larger than the work. 2149 from bioimage_cpp.utils import Blocking 2150 2151 shape = self._selected_image_shape() 2152 if shape is None: 2153 return None 2154 2155 ndim = self._ndim_override() or len(shape) 2156 n_slices = shape[0] if ndim == 3 else 1 2157 if self.tiling != "yes": 2158 return n_slices 2159 2160 tile_shape, _ = _process_tiling_inputs(self.tile_x, self.tile_y, self.halo_x, self.halo_y) 2161 if tile_shape is None: 2162 return n_slices 2163 in_plane = shape[1:3] if ndim == 3 else shape[:2] 2164 return Blocking([0, 0], list(in_plane), list(tile_shape)).number_of_blocks * n_slices 2165 2166 def _recommended_batch_size(self): 2167 """The batch size the VRAM table suggests here, or one if the model is not tabulated. 2168 2169 This previews what the backend will pick rather than deciding it: it is read before the model 2170 is loaded, and for 'auto' from the default device only, whereas the backend reads every device 2171 it runs on after placing the weights there. It is capped by the total work; the backend also 2172 caps it by the share of that work each device receives. 2173 """ 2174 from micro_sam.v2.util import recommend_batch_size 2175 2176 if not self._batch_size_is_tabulated(): 2177 return 1 2178 2179 device = self.device 2180 if device == "auto": 2181 device = util._get_default_device() 2182 return recommend_batch_size(self.model_type, device, n_jobs=self._encoder_job_count()) 2183 2184 def _on_batch_size_edited(self, value): 2185 # A value the user typed is theirs to keep, so stop tracking the model and device. 2186 self._batch_size_is_auto = False 2187 2188 def _refresh_batch_size(self, index=None): 2189 # Show the field only where it has an effect, and keep its value in step with the model and 2190 # the device unless the user has set it themselves. 2191 self._batch_size_widget.setVisible(self._batch_size_has_effect()) 2192 if not self._batch_size_is_auto: 2193 return 2194 2195 recommended = self._recommended_batch_size() 2196 self.batch_size_param.blockSignals(True) 2197 self.batch_size_param.setValue(recommended) 2198 self.batch_size_param.blockSignals(False) 2199 self.batch_size = recommended 2200 2201 def _apply_default_tiling_for_shape(self, shape): 2202 # Enable tiling by default for large in-plane images, using the central v2 tiling defaults. 2203 # 'shape' is the spatial image shape (channel axis already removed). Shared by the layer-based 2204 # auto-tiling and the batch launcher (which judges from the first file in the folder). 2205 from micro_sam.v2.util import needs_default_tiling, DEFAULT_TILE_SHAPE, DEFAULT_HALO 2206 2207 if shape is not None and needs_default_tiling(shape): 2208 self.tile_x, self.tile_y = DEFAULT_TILE_SHAPE 2209 self.halo_x, self.halo_y = DEFAULT_HALO 2210 self.tile_x_param.setValue(self.tile_x) 2211 self.tile_y_param.setValue(self.tile_y) 2212 self.halo_x_param.setValue(self.halo_x) 2213 self.halo_y_param.setValue(self.halo_y) 2214 self.tiling_dropdown.setCurrentText("yes") 2215 2216 # Refresh which tiling fields are visible now that the image (and its dimensionality) changed. 2217 self._update_tiling_visibility() 2218 2219 def _set_default_tiling(self, *args): 2220 shape = self._selected_image_shape() 2221 if shape is not None: 2222 self._apply_default_tiling_for_shape(shape) 2223 2224 def _reset_inputs_to_defaults(self): 2225 """Reset the user inputs to their fresh-open defaults. 2226 2227 Called when the selected image changes, so a new image starts exactly as a freshly opened 2228 tool would: the default model family/size, no custom weights, default tiling parameters and 2229 no embeddings save path. The auto-tiling rule for the new image is re-applied at the end via 2230 '_set_default_tiling' (which also refreshes field visibility), matching a fresh open. 2231 """ 2232 # Clear custom weights first, then restore the default model family + size. (Setting custom 2233 # weights blanks the family dropdown, so clearing it before re-selecting keeps them in sync.) 2234 self.custom_weights_param.setText("") 2235 default_family = {v: k for k, v in self.supported_dropdown_maps.items()}[self._default_model_choice[5:]] 2236 default_size = self._model_size_map[self._default_model_choice[4]] 2237 self.model_family_dropdown.setCurrentText(default_family) 2238 self.model_size_dropdown.setCurrentText(default_size) 2239 2240 # Reset the in-plane tiling parameters to their creation defaults and the save path. Then 2241 # '_set_default_tiling' decides the on or off state (auto-enabled for large images, as on a fresh open). 2242 from micro_sam.v2.util import DEFAULT_TILE_SHAPE, DEFAULT_HALO 2243 self.tile_x_param.setValue(DEFAULT_TILE_SHAPE[0]) 2244 self.tile_y_param.setValue(DEFAULT_TILE_SHAPE[1]) 2245 self.halo_x_param.setValue(DEFAULT_HALO[0]) 2246 self.halo_y_param.setValue(DEFAULT_HALO[1]) 2247 self.tiling_dropdown.setCurrentText("no") 2248 self._batch_size_is_auto = True 2249 self._refresh_batch_size() 2250 self.embeddings_save_path_param.setText("") 2251 2252 # Reset the image-dimensionality override back to 'auto' so a new image is re-detected. 2253 # Block the signal so this does not re-trigger the annotator's normalization mid-reset. 2254 if getattr(self, "ndim_choice", False): 2255 self.image_ndim_dropdown.blockSignals(True) 2256 self.image_ndim_dropdown.setCurrentText("auto") 2257 self.image_ndim_mode = "auto" 2258 self.image_ndim_dropdown.blockSignals(False) 2259 2260 self._set_default_tiling() 2261 2262 def _validate_inputs(self): 2263 """Validates the inputs for the annotation process and returns a dictionary 2264 containing information for message generation, or False if no messages are needed. 2265 2266 This function performs the following checks: 2267 2268 - If an `embeddings_save_path` is provided: 2269 - Validates the image data signature by comparing it with the signature 2270 of the image data in the viewer's selection. 2271 - Checks for existing embeddings at the specified path. 2272 - If existing embeddings are found, it attempts to load parameters 2273 like tile shape, halo, and model type from the Zarr attributes. 2274 - An informational message is generated based on the loaded parameters. 2275 - If loading existing embeddings fails, an error message is generated. 2276 - If no existing embeddings are found, an informational message is generated. 2277 - If no `embeddings_save_path` is provided, the function returns None. 2278 2279 Returns: 2280 bool: True if the computation should be aborted, otherwise False. 2281 """ 2282 2283 # Check if we have an existing input image to compute the embeddings. 2284 image = self.image_selection.get_value() 2285 if image is None: 2286 return _generate_message("error", "No image has been selected.") 2287 2288 # Check if we have an existing embedding path. 2289 # If yes we check the data signature of these embeddings against the selected image 2290 # and we ask the user if they want to load these embeddings. 2291 if ( 2292 self.embeddings_save_path and os.path.isdir(self.embeddings_save_path) 2293 and os.listdir(self.embeddings_save_path) 2294 ): 2295 try: 2296 f = util._open_embeddings(self.embeddings_save_path, mode="a") 2297 2298 # Validate that the embeddings are complete. 2299 # Note: 'input_size' is the last value set in the attrs of f, 2300 # so we can use it as a proxy to check if the embeddings are fully computed 2301 if "input_size" not in f.attrs: 2302 msg = ( 2303 f"The embeddings at {self.embeddings_save_path} are incomplete. " 2304 "Specify a different path or remove them." 2305 ) 2306 return _generate_message("error", msg) 2307 2308 # Validate image data signature. 2309 if "data_signature" in f.attrs: 2310 image = self.image_selection.get_value() 2311 img_signature = util._compute_data_signature(image.data) 2312 if img_signature != f.attrs["data_signature"]: 2313 msg = f"The embeddings don't match with the image: {img_signature} {f.attrs['data_signature']}" 2314 return _generate_message("error", msg) 2315 2316 # The model the saved embeddings were computed with. 2317 saved_model = f.attrs.get("model_name") or f.attrs.get("model_type") 2318 if saved_model is None: 2319 return _generate_message( 2320 "error", f"The embeddings at '{self.embeddings_save_path}' do not record a model." 2321 ) 2322 2323 # Ask the user whether to load the saved embeddings or recompute them. The message 2324 # reflects what changed vs the saved embeddings: a model swap, custom weights (whose 2325 # identity we cannot verify here, so always flag them), or an exact match. 2326 if self.custom_weights: 2327 message = ( 2328 f"Saved embeddings use '{saved_model}'; custom weights are now selected. " 2329 "Load the saved embeddings or recompute?" 2330 ) 2331 elif saved_model != self.model_type: 2332 message = ( 2333 f"Saved embeddings use '{saved_model}', but '{self.model_type}' is selected. " 2334 "Load the saved embeddings or recompute?" 2335 ) 2336 else: 2337 message = f"Embeddings for '{saved_model}' already exist. Load or recompute?" 2338 choice = _ask_load_or_recompute(message) 2339 2340 if choice == "cancel": 2341 return True 2342 2343 if choice == "recompute": 2344 # Recompute with the user's current selection: clear the saved file so the backend 2345 # recomputes from scratch (works for any model and even when the model is unchanged). 2346 # Tiling and model stay as the user set them in the widget. 2347 util._open_embeddings(self.embeddings_save_path, mode="w") 2348 return False 2349 2350 # 'load': adopt the saved model and tiling, then load the existing embeddings. Clear any 2351 # custom weights so the predictor matches the loaded embeddings ('saved_model'), not a 2352 # mismatched custom checkpoint. 2353 self.custom_weights = None 2354 self.custom_weights_param.setText("") 2355 self.model_type = saved_model 2356 if self._validate_model_support(): 2357 return True 2358 # Reflect the loaded model in the model family / size dropdowns. 2359 self._apply_loaded_model_selection(saved_model) 2360 if "tile_shape" in f.attrs and f.attrs["tile_shape"] is not None: 2361 self.tile_x, self.tile_y = f.attrs["tile_shape"] 2362 self.halo_x, self.halo_y = f.attrs["halo"] 2363 # Reflect the loaded tiling parameters in the UI. 2364 self.tile_x_param.setValue(self.tile_x) 2365 self.tile_y_param.setValue(self.tile_y) 2366 self.halo_x_param.setValue(self.halo_x) 2367 self.halo_y_param.setValue(self.halo_y) 2368 self.tiling_dropdown.setCurrentText("yes") 2369 else: 2370 self.tiling_dropdown.setCurrentText("no") 2371 return False 2372 2373 except RuntimeError as e: 2374 val_results = { 2375 "message_type": "error", 2376 "message": f"Failed to load image embeddings: {e}", 2377 } 2378 return _generate_message( 2379 val_results["message_type"], val_results["message"] 2380 ) 2381 2382 # Otherwise we either don't have an embedding path or it is empty. We can proceed in both cases. 2383 return False 2384 2385 def _validate_existing_embeddings(self, state): 2386 # When an embeddings save path is set, '_validate_inputs' already offered load-vs-recompute, 2387 # so don't prompt again here. This only handles the in-memory case (no save path). 2388 if self.embeddings_save_path: 2389 return False 2390 if state.image_embeddings is None: 2391 return False 2392 return _generate_message( 2393 "info", "Embeddings have already been precomputed. Press OK to recompute the embeddings." 2394 ) 2395 2396 @staticmethod 2397 def _clear_autosegment_cache(state): 2398 """Discard predictions derived from the embeddings that were just replaced.""" 2399 widget = state.widgets.get("autosegment") 2400 if widget is not None: 2401 widget._release_segmenter() 2402 widget._drop_decoder_state() 2403 2404 def _n_tiles(self, tile_shape, shape): 2405 """The number of tiles the embedding computation is split into (1 without tiling).""" 2406 if tile_shape is None: 2407 return 1 2408 from bioimage_cpp.utils import Blocking 2409 return Blocking([0, 0], list(shape[:2]), list(tile_shape)).number_of_blocks 2410 2411 def _maybe_warn_cpu(self, ndim, tile_shape, shape): 2412 """Show a one-time-per-session info popup for CPU computations. 2413 2414 The popup appears for expensive CPU computations (many tiles or 3D), and always when the computer 2415 has an NVIDIA GPU that PyTorch cannot use. 2416 """ 2417 state = AnnotatorState() 2418 if state.cpu_info_shown or not self.warn_on_cpu: 2419 return 2420 if str(util.get_device(self.device)) != "cpu": 2421 return 2422 gpu_warning = util.get_gpu_setup_warning() 2423 if gpu_warning is not None: 2424 state.cpu_info_shown = True 2425 QtWidgets.QMessageBox.warning(self, "GPU not used", gpu_warning, QtWidgets.QMessageBox.Ok) 2426 return 2427 # 3D runs the encoder per slice. 2D is a single pass per tile, which only adds up for many tiles. 2428 if ndim < 3 and self._n_tiles(tile_shape, shape) < self.cpu_warn_tiles: 2429 return 2430 state.cpu_info_shown = True 2431 data_kind = "timeseries" if self.is_timeseries else "3D" # A timeseries uses the 3D compute path. 2432 QtWidgets.QMessageBox.information( 2433 self, "Running on CPU", 2434 f"micro_sam runs on the CPU, so computations can be slow for tiled or {data_kind} data. " 2435 "Using a GPU is recommended.", 2436 QtWidgets.QMessageBox.Ok, 2437 ) 2438 2439 def __call__(self, skip_validate=False): 2440 self._validate_model_type_and_custom_weights() 2441 if self._validate_model_support(): 2442 return 2443 2444 # For gated advanced (DINO / UNI) models, check the backend package + HuggingFace access. 2445 if self._validate_vfm_requirements(): 2446 return 2447 2448 # Validate user inputs. 2449 if not skip_validate and self._validate_inputs(): 2450 return 2451 2452 # Get the image. 2453 image = self.image_selection.get_value() 2454 2455 # Update the image embeddings: 2456 state = AnnotatorState() 2457 if self._validate_existing_embeddings(state): 2458 # Whether embeddings already exist to control existing objects in layers. 2459 state.skip_recomputing_embeddings = True 2460 return 2461 2462 state.skip_recomputing_embeddings = False 2463 # Reset the state. 2464 state.reset_state() 2465 2466 # Get image dimensions. 2467 state.image_shape = self._selected_image_shape() 2468 ndim = len(state.image_shape) 2469 state.ndim = ndim 2470 2471 # The image is set only now, after the validation, so a cancel keeps the state of the current image. 2472 state.image_scale = tuple(image.scale) 2473 state.image_name = image.name 2474 2475 # Process tile_shape and halo, set other data. Tiling is only applied when enabled. 2476 if self.tiling == "yes": 2477 tile_shape, halo = _process_tiling_inputs( 2478 self.tile_x, self.tile_y, self.halo_x, self.halo_y 2479 ) 2480 # Reflect the values actually used (after normalization) back in the UI so they are retained. 2481 if tile_shape is not None: 2482 self.tile_x, self.tile_y = tile_shape 2483 self.tile_x_param.setValue(self.tile_x) 2484 self.tile_y_param.setValue(self.tile_y) 2485 if halo is not None: 2486 self.halo_x, self.halo_y = halo 2487 self.halo_x_param.setValue(self.halo_x) 2488 self.halo_y_param.setValue(self.halo_y) 2489 else: 2490 tile_shape, halo = None, None 2491 save_path = ( 2492 None 2493 if self.embeddings_save_path == "" 2494 else self.embeddings_save_path 2495 ) 2496 image_data = image.data 2497 2498 # Warn CPU users once per session that processing can be slow. 2499 self._maybe_warn_cpu(ndim, tile_shape, state.image_shape) 2500 2501 # Eager caching of the automatic-segmentation state: if the 'cache automatic segmentation state' 2502 # option (in these embedding settings) is on, precompute the state to disk while computing the 2503 # embeddings. It persists wherever the embeddings live on disk - the given save path, or the 2504 # ephemeral zarr the eager setup creates for SAM2 volumes / tiled images (removed on reset). 2505 # Plain in-memory 2d has no disk location, so it needs a save path to persist. 2506 is_sam2 = self.model_type.startswith("hvit") 2507 embeddings_on_disk = save_path is not None or (is_sam2 and (ndim == 3 or tile_shape is not None)) 2508 precompute_autoseg_state = self.cache_state and embeddings_on_disk 2509 if self.cache_state and not embeddings_on_disk: 2510 show_info("Set an embeddings save path to cache the automatic segmentation state.") 2511 2512 # Set up progress bar and signals for using it within a threadworker. 2513 # Model and decoder preparation happens before the backend knows the tile / slice count, so 2514 # start with an indeterminate status instead of leaving napari's activity display empty. 2515 pbar, pbar_signals = _create_pbar_for_threadworker("Computing image embeddings") 2516 2517 # @thread_worker() 2518 def compute_image_embedding(): 2519 2520 # The computation runs synchronously on the main thread, so pump the Qt event loop on 2521 # every progress step. Otherwise the napari progress bar only repaints once at the end 2522 # (it just jumps to 100%). This matters most for tiled embeddings (many tiles or slices). 2523 def pbar_init(total, description): 2524 if self.is_timeseries: # A timeseries goes through the 3D compute path; relabel it. 2525 description = description.replace("3D", "Timeseries") 2526 # Reset the counter to 0 so each phase starts fresh: the embeddings, then (when caching 2527 # is on) the automatic-segmentation state precompute reuse the same bar, and without a 2528 # reset the second phase inherits the first's completed count and sits stuck at full. 2529 pbar_signals.pbar_reset.emit() 2530 pbar_signals.pbar_total.emit(total) 2531 pbar_signals.pbar_description.emit(description) 2532 QtWidgets.QApplication.processEvents() 2533 2534 def pbar_update(update): 2535 pbar_signals.pbar_update.emit(update) 2536 QtWidgets.QApplication.processEvents() 2537 2538 state.initialize_predictor( 2539 image_data, 2540 model_type=self.model_type, 2541 save_path=save_path, 2542 ndim=ndim, 2543 device=self.device, 2544 checkpoint_path=self.custom_weights, 2545 tile_shape=tile_shape, 2546 halo=halo, 2547 batch_size=self._effective_batch_size(), 2548 prefer_decoder=True, 2549 precompute_autoseg_state=precompute_autoseg_state, 2550 pbar_init=pbar_init, 2551 pbar_update=pbar_update, 2552 ) 2553 pbar_signals.pbar_stop.emit() 2554 2555 compute_image_embedding() 2556 self._clear_autosegment_cache(state) 2557 self._update_model(state) 2558 # worker = compute_image_embedding() 2559 # worker.returned.connect(self._update_model) 2560 # worker.start() 2561 # return worker
QWidget(parent: Self = None, flags: Qt.WindowType = Qt.WindowFlags())
1788 def __init__(self, parent=None, ndim_choice=False, is_timeseries=False): 1789 super().__init__(parent=parent) 1790 # Whether to expose the 'image dimensions' (ndim) override dropdown. Only the segmentation 1791 # annotator wires it into image normalization, so it is off by default (hidden for tracking 1792 # and the classifiers, which do not use it). 1793 self.ndim_choice = ndim_choice 1794 # The tracking annotator operates on a (T, H, W) timeseries, not a 3D volume. Relabel the 1795 # embedding progress accordingly (the underlying compute path is the same as for 3D). 1796 self.is_timeseries = is_timeseries 1797 1798 # Create a nested layout for the sections. 1799 # Section 1: Image and Model. 1800 section1_layout = QtWidgets.QHBoxLayout() 1801 section1_layout.addLayout(self._create_image_section()) 1802 # Default to the single-source 'DEFAULT_MODEL' (the 'Microscopy' / 'hvit_t_cells' model); 1803 # '_create_model_section' derives the synthetic selector string from it when no value is given. 1804 section1_layout.addLayout( 1805 self._create_model_section() 1806 ) # Creates the model family widget section. 1807 self.layout().addLayout(section1_layout) 1808 1809 # Section 2: Settings (collapsible). 1810 self.layout().addWidget(self._create_settings_widget()) 1811 1812 # Enable sensible default tiling when a large image is selected. 1813 self.image_selection.changed.connect(self._set_default_tiling) 1814 self._set_default_tiling() 1815 1816 # Section 3: The button to trigger the embedding computation. 1817 self.run_button = QtWidgets.QPushButton("Compute Embeddings") 1818 self.run_button.clicked.connect(self.__call__) 1819 self.run_button.setToolTip(get_tooltip("embedding", "run_button")) 1820 self.layout().addWidget(self.run_button)
2564class ClassificationEmbeddingWidget(EmbeddingWidget): 2565 """Embedding widget for the classification tools (pixel and object classification). 2566 2567 The model selection mirrors the segmentation/tracking `EmbeddingWidget` exactly: the same single 2568 'Model:' dropdown with the SAM2 'Natural Images' and 'Microscopy' families (same names and config). 2569 Since classification operates directly on the image-encoder embeddings, it can additionally use 2570 models beyond SAM2. An opt-in 'Advanced Models' checkbox in the embedding settings swaps that one 2571 dropdown to the advanced families instead of adding a second dropdown. The advanced tier holds both 2572 the SAM1 families and the VFM (DINO / UNI) families (`_advanced_family_suffixes` and `_dino_families`). 2573 """ 2574 2575 # The classification tools have no automatic segmentation, so the state-caching option is hidden. 2576 supports_state_caching = False 2577 2578 size_order = ["tiny", "small", "base", "large", "huge", "giant"] 2579 2580 # The classifiers only run the image encoder and a lightweight classifier on top, so they stay 2581 # fast on the CPU and don't need the info popup. 2582 warn_on_cpu = False 2583 2584 # Advanced SAM1 families: UI label -> model-name suffix on the SAM1 'vit_' prefix, resolved in 2585 # '_get_model_size_options'. 2586 _advanced_family_suffixes = { 2587 "Natural Images (SAM1)": "", 2588 "Light Microscopy (µSAM)": "_lm", 2589 "Electron Microscopy (µSAM)": "_em_organelles", 2590 "Medical Imaging (MedicoSAM)": "_medical_imaging", 2591 "Histopathology (PathoSAM)": "_histopathology", 2592 } 2593 _advanced_size_map = {"t": "tiny", "b": "base", "l": "large", "h": "huge"} 2594 # Vision Foundation Model families beyond SAM: UI label -> the registry model_types in that family 2595 # (ordered by size). Sizes/names come from 'micro_sam.models.vfm.VFM_MODELS'/'VFM_SIZE_LABELS', not the 2596 # SAM1 naming scheme. DINOv2/v3 are natural-image (LVD-1689M) models. UNI/UNI2-h are histopathology. 2597 _dino_families = { 2598 "Natural Images (DINOv2)": ("vit_s_dinov2", "vit_b_dinov2", "vit_l_dinov2", "vit_g_dinov2"), 2599 "Natural Images (DINOv3)": ("vit_s_dinov3", "vit_b_dinov3", "vit_l_dinov3"), 2600 "Histopathology (UNI)": ("vit_uni", "vit_univ2"), 2601 "Natural Images (SAM3)": ("vit_sam3",), 2602 } 2603 # Older saved classifiers stored the primary SAM2 families under '(SAM2)' labels. Map them to the 2604 # current names so loading such a classifier still restores the right family. 2605 _primary_family_aliases = {"Natural Images (SAM2)": "Natural Images", "Microscopy (SAM2)": "Microscopy"} 2606 2607 def _all_advanced_families(self): 2608 # The advanced tier combines the SAM1 families and the VFM (DINO / UNI) families. 2609 return list(self._advanced_family_suffixes) + list(self._dino_families) 2610 2611 def _is_dino_active(self): 2612 return getattr(self, "model_family", None) in self._dino_families 2613 2614 def _advanced_active(self): 2615 # The single 'Model:' dropdown holds either the primary or the advanced families, so the 2616 # current family's membership is the source of truth (robust to the dropdown being blanked). 2617 return getattr(self, "model_family", None) in self._all_advanced_families() 2618 2619 def _add_extra_model_settings(self, layout): 2620 # 'Advanced Models' swaps the single 'Model:' dropdown above between the primary (SAM2) and the 2621 # advanced (SAM1) families - one dropdown only, to avoid confusion. Added last in the settings. 2622 self._primary_families = list(self.supported_dropdown_maps.keys()) 2623 # The default primary family ('Microscopy'), restored when advanced is switched back off. 2624 self._default_primary_family = self.model_family 2625 self.advanced = False 2626 self.advanced_checkbox = self._add_boolean_param( 2627 "advanced", self.advanced, title="Advanced Models", 2628 tooltip=get_tooltip("embedding", "advanced_model"), 2629 ) 2630 self.advanced_checkbox.stateChanged.connect(self._on_advanced_toggled) 2631 layout.addWidget(self.advanced_checkbox) 2632 2633 # The inherited dropdowns auto-bind their attribute by indexing the option list captured at 2634 # creation. We swap those lists (the families, and the per-family sizes), which makes the 2635 # captured index stale (wrong value, or out of range). Drop that auto-bind and let 2636 # '_update_model_type' (wired to 'currentTextChanged') sync the attribute from the text. 2637 for dropdown in (self.model_family_dropdown, self.model_size_dropdown): 2638 try: 2639 dropdown.currentIndexChanged.disconnect() 2640 except TypeError: 2641 pass 2642 2643 def _set_family_choices(self, families, select=None): 2644 # Replace the 'Model:' dropdown items, select 'select' (default first), then resolve the model. 2645 if select not in families: 2646 select = families[0] 2647 self.model_family_dropdown.blockSignals(True) 2648 self.model_family_dropdown.clear() 2649 self.model_family_dropdown.addItems(families) 2650 self.model_family_dropdown.setCurrentText(select) 2651 self.model_family_dropdown.blockSignals(False) 2652 self.model_family = select 2653 self._update_model_type() 2654 2655 def _on_advanced_toggled(self, state): 2656 advanced = self.advanced_checkbox.isChecked() 2657 if advanced: 2658 self._set_family_choices(self._all_advanced_families()) 2659 else: # Back to the SAM2 families, defaulting to 'Microscopy' rather than the first entry. 2660 self._set_family_choices(self._primary_families, select=self._default_primary_family) 2661 # Reflect the active tier in the 'Model:' dropdown tooltip. 2662 self.model_family_dropdown.setToolTip( 2663 get_tooltip("embedding", "model_family_advanced" if advanced else "model_family") 2664 ) 2665 2666 def _reset_inputs_to_defaults(self): 2667 # Turning off advanced mode restores the primary families. The base reset then selects the default. 2668 if getattr(self, "advanced_checkbox", None) is not None and self.advanced_checkbox.isChecked(): 2669 self.advanced_checkbox.setChecked(False) 2670 super()._reset_inputs_to_defaults() 2671 2672 def set_model_family_size(self, family, size): 2673 """Restore a saved (family, size): swap the dropdown to the matching tier, then select it.""" 2674 family = self._primary_family_aliases.get(family, family) 2675 self.advanced_checkbox.setChecked(family in self._all_advanced_families()) 2676 self.model_family_dropdown.setCurrentText(family) 2677 if size: 2678 self.model_size_dropdown.setCurrentText(size) 2679 2680 def _validate_model_support(self): 2681 # The vit-tiny backbone needs MobileSAM. Warn (instead of crashing later) if it is selected 2682 # without MobileSAM installed. The model stays selectable - we just block this compute. 2683 from ..util import VIT_T_SUPPORT 2684 if not VIT_T_SUPPORT and (self.model_type or "").startswith("vit_t"): 2685 return _generate_message( 2686 "error", 2687 f"'{self.model_type}' (vit-tiny) requires MobileSAM. Install MobileSAM or pick another size.", 2688 ) 2689 return False 2690 2691 def _family_and_size_for_model(self, model_name): 2692 """Map a stored model name to its (family label, size label) for this widget's dropdowns.""" 2693 full_size_map = {"t": "tiny", "s": "small", "b": "base", "l": "large", "h": "huge"} 2694 for family, models in self._dino_families.items(): # VFM families (DINO / UNI). 2695 if model_name in models: 2696 from ..models.vfm import VFM_SIZE_LABELS 2697 return family, VFM_SIZE_LABELS.get(model_name) 2698 if model_name.startswith("hvit_"): # SAM2 (primary families). 2699 size = full_size_map.get(model_name[5]) 2700 family = self._family_for_sam2_model(model_name) 2701 else: # SAM1 (advanced families): 'vit_<size><suffix>'. 2702 size = full_size_map.get(model_name[4]) 2703 suffix = model_name[5:] 2704 family = {v: k for k, v in self._advanced_family_suffixes.items()}.get(suffix, "Natural Images (SAM1)") 2705 return family, size 2706 2707 def _apply_loaded_model_selection(self, model_name): 2708 # Set the family (primary or advanced) and size dropdowns to match the loaded embeddings. 2709 family, size = self._family_and_size_for_model(model_name) 2710 self.set_model_family_size(family, size) 2711 2712 def _get_model_size_options(self): 2713 # Primary (SAM2) sizes come from the inherited logic. Advanced families resolve to SAM1/DINO names. 2714 if not self._advanced_active(): 2715 return super()._get_model_size_options() 2716 if self._is_dino_active(): 2717 from ..models.vfm import VFM_SIZE_LABELS 2718 models = self._dino_families[self.model_family] 2719 self.model_size_mapping = {VFM_SIZE_LABELS[m]: m for m in models} 2720 self.model_size_options = sorted(self.model_size_mapping.keys(), key=self.size_order.index) 2721 return 2722 from ..v1.util import get_model_names 2723 suffix = self._advanced_family_suffixes[self.model_family] 2724 available = {m for m in get_model_names() if not m.endswith("decoder")} 2725 self.model_size_mapping = {} 2726 for key, label in self._advanced_size_map.items(): 2727 name = f"vit_{key}{suffix}" 2728 if name in available: 2729 self.model_size_mapping[label] = name 2730 self.model_size_options = sorted(self.model_size_mapping.keys(), key=self.size_order.index) 2731 2732 def _update_model_type(self): 2733 # Sync the family from the dropdown first: the inherited auto-bind closure captures the original 2734 # (primary) option list, so after the dropdown is swapped to the advanced families it can set a 2735 # stale value. Re-reading the current text here is authoritative and decides the branch below. 2736 self.model_family = self.model_family_dropdown.currentText() or self.model_family 2737 # Primary mode defers to the inherited SAM2 logic. Advanced mode rebuilds the size dropdown for 2738 # the current SAM1 family and resolves its model name. 2739 if not self._advanced_active(): 2740 return super()._update_model_type() 2741 current_selection = self.model_size_dropdown.currentText() 2742 self._get_model_size_options() 2743 2744 self.model_size_dropdown.blockSignals(True) 2745 self.model_size_dropdown.clear() 2746 self.model_size_dropdown.addItems(self.model_size_options) 2747 if current_selection in self.model_size_options: 2748 self.model_size = current_selection 2749 elif self.model_size_options: 2750 self.model_size = self.model_size_options[0] 2751 self.model_type = self.model_size_mapping.get(self.model_size) 2752 self.model_size_dropdown.setCurrentText(self.model_size) 2753 self.model_size_dropdown.update() 2754 self.model_size_dropdown.blockSignals(False) 2755 # This branch does not go through the inherited update, so refresh the batch size here too: 2756 # the advanced families include the VFM encoders, which do not support batching. 2757 if getattr(self, "_batch_size_widget", None) is not None: 2758 self._refresh_batch_size() 2759 2760 def _validate_model_type_and_custom_weights(self): 2761 # DINO families always resolve from the registry. DINOv3 weights load from HuggingFace using the 2762 # user's own HF access (huggingface-cli login / HF_TOKEN), not the custom-weights field. 2763 if self._is_dino_active(): 2764 self._get_model_size_options() 2765 self.model_type = self.model_size_mapping.get(self.model_size, self.model_type) 2766 return 2767 # Advanced SAM1 mode (without custom weights): resolve the SAM1 model name from family + size. 2768 if self._advanced_active() and not self.custom_weights: 2769 self._get_model_size_options() 2770 self.model_type = self.model_size_mapping.get(self.model_size, self.model_type) 2771 return 2772 # Primary mode, or custom weights: the inherited logic resolves the type and blanks the dropdown. 2773 super()._validate_model_type_and_custom_weights()
Embedding widget for the classification tools (pixel and object classification).
The model selection mirrors the segmentation/tracking EmbeddingWidget exactly: the same single
'Model:' dropdown with the SAM2 'Natural Images' and 'Microscopy' families (same names and config).
Since classification operates directly on the image-encoder embeddings, it can additionally use
models beyond SAM2. An opt-in 'Advanced Models' checkbox in the embedding settings swaps that one
dropdown to the advanced families instead of adding a second dropdown. The advanced tier holds both
the SAM1 families and the VFM (DINO / UNI) families (_advanced_family_suffixes and _dino_families).
2672 def set_model_family_size(self, family, size): 2673 """Restore a saved (family, size): swap the dropdown to the matching tier, then select it.""" 2674 family = self._primary_family_aliases.get(family, family) 2675 self.advanced_checkbox.setChecked(family in self._all_advanced_families()) 2676 self.model_family_dropdown.setCurrentText(family) 2677 if size: 2678 self.model_size_dropdown.setCurrentText(size)
Restore a saved (family, size): swap the dropdown to the matching tier, then select it.
Inherited Members
2839class UnifiedSegmentWidget(_WidgetBase): 2840 """Unified widget for 3D segmentation (per-slice and volumetric). 2841 """ 2842 2843 def __init__(self, viewer, tracking=False, parent=None): 2844 """Initialize the unified segmentation widget. 2845 2846 Args: 2847 viewer: The napari viewer. 2848 tracking: Whether this is used for tracking (vs volumetric). 2849 parent: Parent Qt widget. 2850 """ 2851 super().__init__(parent=parent) 2852 self._viewer = viewer 2853 self.tracking = tracking 2854 2855 # Initialize volume mode state 2856 self.apply_to_volume = False 2857 2858 # The progress bar pumps the Qt event loop, so a key press during a run would start a nested one. 2859 self.is_running = False 2860 # The key and result of the last volume propagation, so a re-press without changes reuses it. 2861 self._last_volume_run = None 2862 2863 # Create the widget UI 2864 self._create_widget() 2865 2866 def _create_widget(self): 2867 """Create the widget UI elements.""" 2868 # 1. Add volume mode checkbox 2869 volume_title = ( 2870 "Apply to All Frames" if self.tracking else "Apply to Volume" 2871 ) 2872 self.volume_checkbox = self._add_boolean_param( 2873 "apply_to_volume", 2874 self.apply_to_volume, 2875 title=volume_title, 2876 tooltip=get_tooltip("unified_segment", "apply_to_volume"), 2877 ) 2878 self.volume_checkbox.stateChanged.connect(self._on_volume_mode_changed) 2879 self.layout().addWidget(self.volume_checkbox) 2880 2881 # 2. Add the batched checkbox. It stays hidden until the embeddings exist and are not tiled. 2882 self.batched = False 2883 self.batched_checkbox = self._add_boolean_param( 2884 "batched", 2885 self.batched, 2886 title="Batched", 2887 tooltip=get_tooltip("unified_segment", "batched"), 2888 ) 2889 self.batched_checkbox.setVisible(False) # Initially hidden 2890 self.layout().addWidget(self.batched_checkbox) 2891 2892 # 3. Store the settings for volume propagation. The InteractiveSegmentationWidget shows the controls. 2893 # 'early_stop_patience': the number of empty slices after which propagation stops (0 disables it). 2894 # 'z_range': the inclusive (z_min, z_max) range for propagation, or None for the full volume. 2895 self.early_stop_patience = 2 2896 self.z_range = None 2897 2898 # 4. Add run button 2899 self.run_button = QtWidgets.QPushButton(self._get_button_text()) 2900 self.run_button.setToolTip(get_tooltip("unified_segment", "segment_button")) 2901 self.run_button.clicked.connect(self.__call__) 2902 self.layout().addWidget(self.run_button) 2903 2904 # 5. Set the visibility of the batched checkbox. 2905 self._update_batched_visibility() 2906 2907 def _on_volume_mode_changed(self, state): 2908 """Handle volume mode checkbox state change. 2909 2910 Args: 2911 state: Qt checkbox state (0=unchecked, 2=checked). 2912 """ 2913 # Update button text 2914 self.run_button.setText(self._get_button_text()) 2915 2916 # Update batched checkbox visibility 2917 self._update_batched_visibility() 2918 2919 def _update_batched_visibility(self): 2920 """Show the batched checkbox only for computed embeddings that are not tiled.""" 2921 state = AnnotatorState() 2922 2923 # Batched prompts do not work with tiled embeddings. They work in the slice and in the volume mode. 2924 should_show = state.image_embeddings is not None and not _embeddings_are_tiled(state) 2925 if not should_show and getattr(self, "batched", False): 2926 self.batched_checkbox.setChecked(False) 2927 self.batched_checkbox.setVisible(should_show) 2928 2929 def _get_button_text(self): 2930 """Get dynamic button text based on current mode.""" 2931 if self.tracking: 2932 return ( 2933 "Segment All Frames [S]" 2934 if self.apply_to_volume 2935 else "Segment Frame [S]" 2936 ) 2937 else: 2938 return ( 2939 "Segment Volume [S]" 2940 if self.apply_to_volume 2941 else "Segment Slice [S]" 2942 ) 2943 2944 def __call__(self, viewer=None): 2945 """Execute segmentation based on current mode. 2946 2947 Args: 2948 viewer: Optional napari viewer (for keybinding compatibility). 2949 """ 2950 if self.is_running: 2951 show_info("The segmentation is still running. Wait until it finishes.") 2952 return None 2953 2954 # Validation 2955 if _validate_embeddings(self._viewer): 2956 return None 2957 if _validate_layers(self._viewer): 2958 return None 2959 2960 self.is_running = True 2961 try: 2962 # Route to appropriate implementation 2963 if self.apply_to_volume: 2964 if self.tracking: 2965 return self._run_tracking() 2966 else: 2967 return self._run_volumetric_segmentation() 2968 else: 2969 if self.tracking: 2970 return self._run_frame_segmentation() 2971 else: 2972 return self._run_slice_segmentation() 2973 finally: 2974 self.is_running = False 2975 2976 def reset_last_volume_run(self): 2977 """Forget the last volume propagation, so the next run propagates again.""" 2978 self._last_volume_run = None 2979 2980 def _run_slice_segmentation(self): 2981 """Execute per-slice segmentation. 2982 """ 2983 shape = self._viewer.layers["current_object"].data.shape[1:] 2984 2985 z = vutil.current_slice(self._viewer, self._viewer.layers["point_prompts"]) 2986 2987 prompt_layer = self._viewer.layers["prompts"] 2988 prompts = vutil.collect_frame_prompts( 2989 self._viewer.layers["point_prompts"], prompt_layer, shape, i=z, 2990 ) 2991 # this is a stop prompt, we do nothing 2992 if prompts.is_stop: 2993 return 2994 2995 points, labels, boxes, masks = prompts.points, prompts.labels, prompts.boxes, prompts.masks 2996 have_scribbles = prompts.have_scribbles 2997 if have_scribbles and not boxes and not np.any(labels == 1): 2998 return _generate_message( 2999 "error", 3000 "A negative scribble needs a positive point, positive scribble, box or mask prompt.", 3001 ) 3002 3003 state = AnnotatorState() 3004 batched = _batched_disabled_when_tiled(state, bool(self.batched)) 3005 if have_scribbles and batched: 3006 show_info( 3007 "Batched segmentation is not supported with scribble prompts. " 3008 "It runs single-object segmentation instead." 3009 ) 3010 batched = False 3011 3012 boxes = [box[[1, 0, 3, 2]] for box in boxes] 3013 if batched: 3014 seg = self._segment_slice_batched(z, points, labels, boxes, masks, shape) 3015 else: 3016 seg = state.interactive_segmenter.segment_slice( 3017 frame_idx=z, 3018 points=points[:, ::-1].copy(), 3019 labels=labels, 3020 boxes=boxes, 3021 masks=masks, 3022 ) 3023 3024 # No prompts were given or prompts were invalid, skip segmentation. 3025 if seg is None: 3026 print( 3027 "You either haven't provided any prompts or invalid prompts. The segmentation will be skipped." 3028 ) 3029 return 3030 3031 self._viewer.layers["current_object"].data[z] = seg 3032 self._viewer.layers["current_object"].refresh() 3033 3034 def _segment_slice_batched(self, z, points, labels, boxes, masks, shape): 3035 """Batched multi-object segmentation for a single slice with SAM2. 3036 3037 Mirrors the 2d batched convention: one object per positive point (each combined with the 3038 shared negative points) and one object per box. A box from a polygon/ellipse (its entry in 3039 `masks` is not None) also carries its soft mask cue. The boxes are expected in the reordered 3040 layout used by `segment_slice`. 3041 """ 3042 state = AnnotatorState() 3043 points = np.zeros((0, 2)) if points is None else np.asarray(points) 3044 labels = np.zeros((0,), dtype=int) if labels is None else np.asarray(labels) 3045 positive_points = points[labels == 1] 3046 negative_points = points[labels != 1] 3047 n_neg = len(negative_points) 3048 3049 seg = np.zeros(tuple(shape), dtype="uint32") 3050 object_id = 0 3051 3052 # One object per positive point, each combined with the shared negative points. 3053 for pos in positive_points: 3054 pts = np.concatenate([pos[None], negative_points], axis=0) if n_neg else pos[None] 3055 lbs = np.concatenate([[1], np.zeros(n_neg, dtype=int)]) if n_neg else np.array([1]) 3056 object_id += 1 3057 mask = state.interactive_segmenter.segment_slice( 3058 frame_idx=z, points=pts[:, ::-1].copy(), labels=lbs, object_id=object_id, 3059 ) 3060 if mask is not None: 3061 seg[mask > 0] = object_id 3062 3063 # One object per box (with its mask cue if it is a polygon/ellipse), each combined with the 3064 # shared negative points. 3065 for bidx, box in enumerate(boxes): 3066 neg = negative_points[:, ::-1].copy() if n_neg else None 3067 neg_labels = np.zeros(n_neg, dtype=int) if n_neg else None 3068 object_id += 1 3069 mask = state.interactive_segmenter.segment_slice( 3070 frame_idx=z, points=neg, labels=neg_labels, boxes=[box], 3071 masks=[masks[bidx]] if masks is not None else None, object_id=object_id, 3072 ) 3073 if mask is not None: 3074 seg[mask > 0] = object_id 3075 3076 return seg 3077 3078 def _segment_track_on_frame(self, state, t, track_id, shape): 3079 """Segment a single track's object on frame 't'. Returns the binary mask or None.""" 3080 prompt_layer = self._viewer.layers["prompts"] 3081 prompts = vutil.collect_frame_prompts( 3082 self._viewer.layers["point_prompts"], prompt_layer, shape, i=t, track_id=track_id, 3083 ) 3084 # A single negative point is a stop prompt: nothing to segment for this track here. 3085 if prompts.is_stop: 3086 return None 3087 3088 points, labels, boxes, masks = prompts.points, prompts.labels, prompts.boxes, prompts.masks 3089 if prompts.have_scribbles and not boxes and not np.any(labels == 1): 3090 show_info( 3091 "A negative scribble alone cannot segment an object. " 3092 "Add a positive point, positive scribble, box or mask prompt." 3093 ) 3094 return None 3095 3096 # The tracking annotator is SAM2-only: segment the frame via the video predictor. 3097 # Points are reordered to (x, y) and boxes to (x0, y0, x1, y1), matching the per-slice path. 3098 sam2_boxes = [box[[1, 0, 3, 2]] for box in boxes] 3099 seg = state.interactive_segmenter.segment_slice( 3100 frame_idx=t, 3101 points=points[:, ::-1].copy() if len(points) else points, 3102 labels=labels, 3103 boxes=sam2_boxes, 3104 masks=masks, 3105 ) 3106 return None if seg is None else (seg.squeeze() == 1) 3107 3108 def _run_frame_segmentation(self): 3109 """Execute per-frame segmentation for the current track (tracking mode).""" 3110 state = AnnotatorState() 3111 shape = state.image_shape[1:] 3112 t = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3113 3114 track_id = state.current_track_id 3115 new_mask = self._segment_track_on_frame(state, t, track_id, shape) 3116 if new_mask is None: 3117 print( 3118 "You either haven't provided any prompts or invalid prompts. The segmentation will be skipped." 3119 ) 3120 return 3121 3122 # Clear the old segmentation for this track id, then set the new one. 3123 layer = self._viewer.layers["current_object"] 3124 layer.data[t][layer.data[t] == track_id] = 0 3125 layer.data[t][new_mask] = track_id 3126 layer.refresh() 3127 3128 def _run_volumetric_segmentation(self): 3129 """Execute volumetric segmentation. 3130 """ 3131 pbar, pbar_signals = _create_pbar_for_threadworker() 3132 3133 def emit_progress(update): 3134 # The run is synchronous, so pump the Qt event loop to repaint the bar live instead of 3135 # only updating the terminal tqdm. 3136 pbar_signals.pbar_update.emit(update) 3137 QtWidgets.QApplication.processEvents() 3138 3139 # @thread_worker 3140 def volumetric_segmentation_impl(): 3141 state = AnnotatorState() 3142 shape = state.image_shape 3143 3144 pbar_signals.pbar_total.emit(shape[0]) 3145 pbar_signals.pbar_description.emit("Segment object") 3146 3147 # Prepare the prompts 3148 point_prompts = self._viewer.layers["point_prompts"] 3149 box_prompts = self._viewer.layers["prompts"] 3150 z_values_points = np.round(point_prompts.data[:, 0]) 3151 z_values_scribbles = vutil.get_scribble_slices(box_prompts) 3152 have_scribbles = len(z_values_scribbles) > 0 3153 z_values_boxes = np.round( 3154 np.asarray([ 3155 shape[0, 0] 3156 for shape, shape_type in zip(box_prompts.data, box_prompts.shape_type) 3157 if shape_type not in vutil.SCRIBBLE_SHAPE_TYPES 3158 ]) 3159 ).astype("int") 3160 3161 # Whether the user decide to provide batched prompts for multi-object segmentation. 3162 is_batched = _batched_disabled_when_tiled(state, bool(self.batched)) 3163 if have_scribbles and is_batched: 3164 show_info( 3165 "Batched segmentation is not supported with scribble prompts. " 3166 "It runs single-object segmentation instead." 3167 ) 3168 is_batched = False 3169 3170 # Collect every prompt first: a slice's negative points must be known when the boxes 3171 # and masks on that slice are assigned their object ids, and the complete set is 3172 # needed to detect prompts that changed since the last run. 3173 shape_yx = state.image_shape[-2:] 3174 point_slices = np.unique(np.concatenate([z_values_points, z_values_scribbles])).astype("int") 3175 merged_prompts, shape_prompts, stop_slices = {}, {}, [] 3176 for curr_z in np.unique(np.concatenate([point_slices, z_values_boxes])).astype("int"): 3177 prompts = vutil.collect_frame_prompts(point_prompts, box_prompts, shape_yx, i=curr_z) 3178 # A slice whose only prompt is a single negative point is a 'stop' annotation. 3179 if prompts.is_stop: 3180 stop_slices.append(int(curr_z)) 3181 elif len(prompts.points): 3182 merged_prompts[int(curr_z)] = (prompts.points, prompts.labels) 3183 rect_boxes, poly_masks = prompts.split_shapes() 3184 if rect_boxes or poly_masks: 3185 shape_prompts[int(curr_z)] = (rect_boxes, poly_masks) 3186 3187 have_positive_points = any(np.any(labels == 1) for _, labels in merged_prompts.values()) 3188 have_shape_cue = len(shape_prompts) > 0 3189 if have_scribbles and not have_positive_points and not have_shape_cue: 3190 pbar_signals.pbar_stop.emit() 3191 _generate_message( 3192 "error", 3193 "A negative scribble needs a positive point, positive scribble, box or mask prompt.", 3194 ) 3195 return None 3196 if is_batched and not have_positive_points and not have_shape_cue: 3197 # A batched object needs a positive cue; a negative point only corrects one. 3198 pbar_signals.pbar_stop.emit() 3199 _generate_message( 3200 "error", 3201 "Batched segmentation needs a positive point, box or mask prompt.", 3202 ) 3203 return None 3204 3205 # Plan the whole round before touching the state: the object each prompt is routed to 3206 # depends on the prompt set as a whole, and the sync below needs that routing. 3207 plan = _plan_volume_prompts(merged_prompts, shape_prompts, is_batched) 3208 signatures = _volume_prompt_signatures(plan) 3209 3210 # A patience of 0 disables early stopping (propagate through the whole volume). 3211 early_stop_patience = self.early_stop_patience if self.early_stop_patience > 0 else None 3212 prompted_slices = set(merged_prompts) | set(shape_prompts) 3213 z_range, ignored_stops = _bound_z_range_by_stops( 3214 prompted_slices, stop_slices, shape[0], self.z_range 3215 ) 3216 if ignored_stops: 3217 show_info( 3218 f"Ignoring the stop annotation (single negative point) in slice(s) {ignored_stops}: " 3219 "a stop must lie below or above all prompted slices." 3220 ) 3221 3222 # Propagating the same prompts again costs a full pass and drifts from the first result. 3223 run_key = ( 3224 id(state.interactive_segmenter), is_batched, frozenset(signatures), z_range, early_stop_patience 3225 ) 3226 if self._last_volume_run is not None and self._last_volume_run[0] == run_key: 3227 pbar_signals.pbar_stop.emit() 3228 return self._last_volume_run[1].copy() 3229 3230 # Rebuild the persistent state when a prompt was deleted, moved, relabelled or routed 3231 # to a different object since the last run. A round that only adds prompts and leaves 3232 # the existing routing intact keeps the state, so only the new prompts are pushed. 3233 state.interactive_segmenter.sync_prompt_state(signatures) 3234 _push_volume_prompts(state.interactive_segmenter, plan) 3235 3236 # Propagate the prompts throughout the volume and combine the propagated segmentations. 3237 # Tiled segmenters count one step per slice in each tile activated above. 3238 n_propagation_steps = state.interactive_segmenter.get_progress_total(z_range) 3239 pbar_signals.pbar_total.emit(n_propagation_steps) 3240 pbar_signals.pbar_description.emit("Propagate in volume") 3241 seg = state.interactive_segmenter.predict( 3242 update_progress=emit_progress, 3243 early_stop_patience=early_stop_patience, z_range=z_range, 3244 ) 3245 self._last_volume_run = (run_key, seg.copy()) 3246 3247 pbar_signals.pbar_stop.emit() 3248 3249 return seg 3250 3251 def update_segmentation(seg): 3252 self._viewer.layers["current_object"].data = seg 3253 self._viewer.layers["current_object"].refresh() 3254 3255 seg = volumetric_segmentation_impl() 3256 if seg is None: 3257 return None 3258 self._viewer.layers["current_object"].data = seg 3259 self._viewer.layers["current_object"].refresh() 3260 # worker = volumetric_segmentation_impl() 3261 # worker.returned.connect(update_segmentation) 3262 # worker.start() 3263 # return worker 3264 3265 def _run_tracking(self): 3266 """Execute interactive tracking by propagating the current track's prompts across frames. 3267 3268 Design boundary: SAM2 only does per-object mask propagation across frames. It has no concept 3269 of a division / lineage event and never signals one. Everything division-related here is 3270 mechanistic orchestration on top of the model (reading the user's 'division' annotation, 3271 bounding propagation, seeding daughters, recording lineage edges) - none of it is a SAM2 3272 capability. Genuine automatic division detection lives in the automatic-tracking path via 3273 trackastra, which predicts lineages from per-frame segmentations; it is not SAM2. 3274 """ 3275 state = AnnotatorState() 3276 pbar, pbar_signals = _create_pbar_for_threadworker() 3277 3278 def emit_progress(update): 3279 # Synchronous run: pump the Qt event loop so the bar repaints live, not only in the terminal. 3280 pbar_signals.pbar_update.emit(update) 3281 QtWidgets.QApplication.processEvents() 3282 3283 def propagate_track(track_id, division_frame): 3284 # Propagate a single track's prompts forward in time with the SAM2 predictor. Tracking 3285 # is forward-only: it starts at the first prompted frame and never runs to earlier 3286 # frames. A frame whose only prompt for this track is a single negative point is a 3287 # 'stop' annotation. A stop on the highest annotated frame bounds propagation above. 3288 shape = state.image_shape 3289 point_layer = self._viewer.layers["point_prompts"] 3290 box_layer = self._viewer.layers["prompts"] 3291 3292 # Reset so a re-run does not accumulate prompts from a previous propagation. 3293 state.interactive_segmenter.reset_predictor() 3294 pbar_signals.pbar_description.emit(f"Track object {track_id}") 3295 3296 # Add the point and scribble prompts for this track, one frame at a time, recording the 3297 # prompted frames and the stop annotations. A scribble expands into several point prompts 3298 # on its frame, in the same (y, x) order as the point prompts. 3299 prompted_frames, stop_frames = [], [] 3300 z_points = ( 3301 np.unique(np.round(point_layer.data[:, 0]).astype(int)) 3302 if len(point_layer.data) else np.zeros(0, dtype=int) 3303 ) 3304 z_scribbles = vutil.get_scribble_slices(box_layer, track_id=track_id) 3305 have_positive_cue = False 3306 for t in sorted({int(t) for t in z_points} | {int(t) for t in z_scribbles}): 3307 # Exclude division markers: they signal a lineage event and bound propagation 3308 # (see below), but must not be fed to SAM2 as conditioning prompts - doing so 3309 # adds a second conditioning frame that corrupts the mother track's propagation. 3310 prompts = vutil.collect_frame_prompts( 3311 point_layer, box_layer, shape[1:], i=t, track_id=track_id, 3312 exclude_states=("division",), 3313 ) 3314 if prompts.is_stop: # Single negative point: a stop annotation for this track. 3315 stop_frames.append(t) 3316 continue 3317 if len(prompts.points) == 0: # This track has no point prompts on this frame. 3318 continue 3319 have_positive_cue = have_positive_cue or bool(np.any(prompts.labels == 1)) 3320 state.interactive_segmenter.add_point_prompts( 3321 frame_ids=t, points=prompts.points, point_labels=prompts.labels, 3322 ) 3323 prompted_frames.append(t) 3324 3325 # Add the box prompts for this track. 3326 z_boxes = ( 3327 np.unique(np.concatenate([box[:1, 0] for box in box_layer.data]).round().astype(int)) 3328 if box_layer.data else np.zeros(0, dtype=int) 3329 ) 3330 for t in z_boxes: 3331 boxes, _ = vutil.shape_layer_to_prompts(box_layer, shape=shape[1:], i=int(t), track_id=track_id) 3332 for box in boxes: 3333 state.interactive_segmenter.add_box_prompts(frame_ids=int(t), boxes=[box]) 3334 if boxes: 3335 have_positive_cue = True 3336 prompted_frames.append(int(t)) 3337 3338 if not prompted_frames: 3339 return None 3340 if not have_positive_cue: 3341 show_info( 3342 "Negative prompts alone cannot track an object. " 3343 "Add a positive point, positive scribble or box prompt." 3344 ) 3345 return None 3346 3347 # Forward-only propagation: start at the first prompted frame and never go to earlier 3348 # frames. A stop annotation on the highest annotated frame bounds propagation above 3349 # ('predict' enforces the z-range); a division bounds the mother at the division frame - 3350 # its last frame (only reached when the mother is not segmented yet, see 'tracking_impl'). 3351 annotated = sorted(set(prompted_frames) | set(stop_frames)) 3352 stop_upper = annotated[-1] in stop_frames 3353 z_lo = min(prompted_frames) 3354 z_hi = max(prompted_frames) if stop_upper else shape[0] - 1 3355 if division_frame is not None: # The division frame is the mother's last frame. 3356 z_hi = min(z_hi, division_frame) 3357 3358 if z_hi < z_lo: # The division precedes the track's first frame: nothing to segment. 3359 return None 3360 3361 pbar_signals.pbar_total.emit( 3362 state.interactive_segmenter.get_progress_total((z_lo, z_hi)) 3363 ) 3364 seg = state.interactive_segmenter.predict( 3365 update_progress=emit_progress, 3366 early_stop_patience=None, z_range=(z_lo, z_hi), 3367 ) 3368 return seg 3369 3370 def tracking_impl(): 3371 # Propagate the current track. Its propagated mask is labelled with its track id. 3372 track_ids = [state.current_track_id] 3373 point_layer = self._viewer.layers["point_prompts"] 3374 seg_layer = self._viewer.layers["current_object"] 3375 results = {} 3376 for track_id in track_ids: 3377 division_frame = _division_frame_for_track(point_layer, track_id) 3378 # A division is a cleanup, not a (re)segmentation: when the mother is already 3379 # segmented, its frames up to and including the division are correct (tracking is 3380 # forward-only), so we just erase it AFTER the division frame and seed the daughters 3381 # - no SAM2 re-run. Only when the mother is not segmented yet do we fall back to a 3382 # bounded propagation so it still gets created up to the division frame. 3383 segmented = division_frame is not None and bool( 3384 np.any(seg_layer.data[:division_frame + 1] == track_id) 3385 ) 3386 if segmented: 3387 results[track_id] = {"truncate_from": division_frame + 1} 3388 _update_lineage(self._viewer, mother=track_id) 3389 continue 3390 3391 seg = propagate_track(track_id, division_frame) 3392 if seg is not None: 3393 res = {"seg": seg} 3394 # A daughter must not occupy its mother's frames: clip its mask to start the 3395 # frame after the mother's division, no matter where the user prompted it. 3396 mother_division = _mother_division_frame(point_layer, state.lineage, track_id) 3397 if mother_division is not None: 3398 res["min_frame"] = mother_division + 1 3399 results[track_id] = res 3400 # A division seeds two daughter tracks, so the user can continue from the division. 3401 if division_frame is not None: 3402 _update_lineage(self._viewer, mother=track_id) 3403 pbar_signals.pbar_stop.emit() 3404 return results 3405 3406 def update_segmentation(results): 3407 if not results: 3408 print("No prompts were given for the track(s). The tracking will be skipped.") 3409 return 3410 3411 layer = self._viewer.layers["current_object"] 3412 for track_id, res in results.items(): 3413 if "truncate_from" in res: 3414 # Division cleanup: erase the mother after the division frame, leaving its 3415 # frames up to and including the division (already correct) untouched. 3416 f = res["truncate_from"] 3417 layer.data[f:][layer.data[f:] == track_id] = 0 3418 else: 3419 # Clear the old mask for this track, then set the propagated one. A daughter is 3420 # clipped to start the frame after its mother's division (it did not exist yet). 3421 seg = res["seg"] 3422 min_frame = res.get("min_frame") 3423 if min_frame is not None: 3424 seg = seg.copy() 3425 seg[:min_frame] = 0 3426 layer.data[layer.data == track_id] = 0 3427 layer.data[seg == 1] = track_id 3428 layer.refresh() 3429 3430 results = tracking_impl() 3431 update_segmentation(results)
Unified widget for 3D segmentation (per-slice and volumetric).
2843 def __init__(self, viewer, tracking=False, parent=None): 2844 """Initialize the unified segmentation widget. 2845 2846 Args: 2847 viewer: The napari viewer. 2848 tracking: Whether this is used for tracking (vs volumetric). 2849 parent: Parent Qt widget. 2850 """ 2851 super().__init__(parent=parent) 2852 self._viewer = viewer 2853 self.tracking = tracking 2854 2855 # Initialize volume mode state 2856 self.apply_to_volume = False 2857 2858 # The progress bar pumps the Qt event loop, so a key press during a run would start a nested one. 2859 self.is_running = False 2860 # The key and result of the last volume propagation, so a re-press without changes reuses it. 2861 self._last_volume_run = None 2862 2863 # Create the widget UI 2864 self._create_widget()
Initialize the unified segmentation widget.
Arguments:
- viewer: The napari viewer.
- tracking: Whether this is used for tracking (vs volumetric).
- parent: Parent Qt widget.
3439class InteractiveSegmentationWidget(_WidgetBase): 3440 """Interactive segmentation widget combining the prompt menu, segmentation and clearing. 3441 3442 This widget adapts to the data dimensionality and works with both SAM and SAM2 models. 3443 For 3d data it exposes a single 'Apply to Volume' checkbox that governs both segmentation and 3444 clearing (current slice vs. the whole volume / all slices), plus a batched toggle (SAM2 volume 3445 mode) for multi-object segmentation. 3446 3447 Args: 3448 viewer: The napari viewer. 3449 ndim: The number of spatial dimensions of the data (2 or 3). 3450 prompt_widget: The point prompt label menu created by `create_prompt_menu`. 3451 parent: The parent Qt widget. 3452 """ 3453 3454 segment_requested = Signal() 3455 3456 def __init__(self, viewer, ndim, prompt_widget, parent=None): 3457 super().__init__(parent=parent) 3458 self._viewer = viewer 3459 self._ndim = ndim 3460 self._prompt_widget = prompt_widget 3461 self.batched = False 3462 self.apply_to_volume = False 3463 self._segment_widget = None 3464 self._propagation_settings = None 3465 self._create_widget() 3466 3467 def _create_widget(self): 3468 # Prompt label menu. 3469 self.layout().addWidget(self._prompt_widget.native) 3470 3471 self.clear_button = QtWidgets.QPushButton("Clear Annotations [Shift + C]") 3472 self.clear_button.setToolTip(get_tooltip("unified_segment", "clear_button")) 3473 self.clear_button.clicked.connect(lambda: self.clear()) 3474 3475 self.segment_button = QtWidgets.QPushButton("Segment Object [S]") 3476 self.segment_button.setToolTip(get_tooltip("unified_segment", "segment_button")) 3477 self.segment_button.clicked.connect(lambda: self.segment()) 3478 3479 # Segmentation controls. 3480 if self._ndim == 2: 3481 # 2d: a 'batched' toggle above the side-by-side segment and clear buttons. 3482 self.batched_checkbox = self._add_boolean_param( 3483 "batched", 3484 self.batched, 3485 title="Batched", 3486 tooltip=get_tooltip("unified_segment", "batched"), 3487 ) 3488 self.layout().addWidget(self.batched_checkbox) 3489 else: 3490 # 3d: use the volumetric segmentation widget purely as the segmentation engine. 3491 # It does not show its own controls. The interactive widget owns the 'Apply to Volume' 3492 # and 'Batched' checkboxes and drives the engine's attributes. The 'Apply to Volume' 3493 # checkbox governs both segmentation (slice vs. volume) and clearing (current slice 3494 # vs. all slices). It is kept hidden but parented so it does not float as a window. 3495 self._segment_widget = UnifiedSegmentWidget(self._viewer, tracking=False) 3496 self._segment_widget.setVisible(False) 3497 self.layout().addWidget(self._segment_widget) 3498 3499 # Batched multi-object segmentation. Works for both a single slice and the whole 3500 # volume, so it is always available. 3501 self.batched_checkbox = self._add_boolean_param( 3502 "batched", 3503 self.batched, 3504 title="Batched", 3505 tooltip=get_tooltip("unified_segment", "batched"), 3506 ) 3507 self.batched_checkbox.stateChanged.connect(self._on_batched_changed) 3508 3509 self.apply_to_volume_checkbox = self._add_boolean_param( 3510 "apply_to_volume", 3511 self.apply_to_volume, 3512 title="Apply to Volume", 3513 tooltip=get_tooltip("unified_segment", "apply_to_volume"), 3514 ) 3515 self.apply_to_volume_checkbox.stateChanged.connect(self._on_apply_to_volume_changed) 3516 3517 # Place the two checkboxes side by side: 'Batched' on the left, 'Apply to Volume' 3518 # pushed to the right. 3519 checkbox_row = QtWidgets.QHBoxLayout() 3520 checkbox_row.addWidget(self.batched_checkbox) 3521 checkbox_row.addStretch() 3522 checkbox_row.addWidget(self.apply_to_volume_checkbox) 3523 self.layout().addLayout(checkbox_row) 3524 3525 # SAM2 volume-mode propagation controls (early stopping + z-range). Hidden until the 3526 # user enables 'Apply to Volume' with a SAM2 model. The controls drive the engine. 3527 self._propagation_settings = self._create_propagation_settings() 3528 self._propagation_settings.setVisible(False) 3529 self.layout().addWidget(self._propagation_settings) 3530 3531 # Place the segment and clear buttons side by side. 3532 button_row = QtWidgets.QHBoxLayout() 3533 button_row.addWidget(self.segment_button) 3534 button_row.addWidget(self.clear_button) 3535 self.layout().addLayout(button_row) 3536 3537 # Scribbles describe corrections for one object and cannot be assigned unambiguously to 3538 # separate objects in batched mode. Keep the control in sync as scribbles are added or 3539 # removed from the shared prompt layer. 3540 self._viewer.layers["prompts"].events.data.connect(self._update_batched_visibility) 3541 3542 # Hide the batched control if the (already loaded) embeddings are tiled. 3543 self._update_batched_visibility() 3544 3545 def _update_batched_visibility(self, event=None): 3546 """Disable batched segmentation while one or more scribble prompts are present.""" 3547 super()._update_batched_visibility() 3548 3549 prompt_layer = self._viewer.layers["prompts"] 3550 have_scribbles = any( 3551 shape_type in vutil.SCRIBBLE_SHAPE_TYPES for shape_type in prompt_layer.shape_type 3552 ) 3553 if have_scribbles and self.batched_checkbox.isChecked(): 3554 self.batched_checkbox.setChecked(False) 3555 3556 self.batched_checkbox.setEnabled(not have_scribbles) 3557 tooltip_key = "batched_scribble_disabled" if have_scribbles else "batched" 3558 self.batched_checkbox.setToolTip(get_tooltip("unified_segment", tooltip_key)) 3559 3560 def _create_propagation_settings(self): 3561 """Build the SAM2 volume-mode propagation controls (early stopping + z-range slider). 3562 3563 The controls live on the visible interactive widget and write their values into the hidden 3564 'UnifiedSegmentWidget' engine, which reads 'early_stop_patience' and 'z_range' at run time. 3565 """ 3566 container = QtWidgets.QWidget() 3567 container.setLayout(QtWidgets.QVBoxLayout()) 3568 3569 # Stop after this many consecutive empty slices (0 disables early stopping). 3570 self.early_stop_patience = 2 3571 self.early_stop_patience_param, layout = self._add_int_param( 3572 "early_stop_patience", self.early_stop_patience, min_val=0, max_val=100, 3573 title="Stop after empty slices", tooltip=get_tooltip("segmentnd", "early_stop_patience"), 3574 ) 3575 self.early_stop_patience_param.valueChanged.connect(self._sync_propagation_settings) 3576 container.layout().addLayout(layout) 3577 3578 # Full-volume propagation (default) vs. a restricted z-range. 3579 self.use_full_z_range = True 3580 self.full_z_range_checkbox = self._add_boolean_param( 3581 "use_full_z_range", self.use_full_z_range, 3582 title="Propagate through all slices", 3583 tooltip=get_tooltip("segmentnd", "use_full_z_range"), 3584 ) 3585 container.layout().addWidget(self.full_z_range_checkbox) 3586 3587 # The labeled range slider collapses to zero height when sharing a row with a text label, 3588 # so it gets its own full-width row with the caption above it and a minimum height. 3589 z_range_label = QtWidgets.QLabel("Propagation z-range") 3590 z_range_label.setToolTip(get_tooltip("segmentnd", "z_range")) 3591 container.layout().addWidget(z_range_label) 3592 self.z_range_slider = QLabeledRangeSlider(Qt.Orientation.Horizontal) 3593 self.z_range_slider.setRange(0, 1) 3594 self.z_range_slider.setValue((0, 1)) 3595 self.z_range_slider.setToolTip(get_tooltip("segmentnd", "z_range")) 3596 self.z_range_slider.setEnabled(not self.use_full_z_range) 3597 self.z_range_slider.setMinimumHeight(40) 3598 self.z_range_slider.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) 3599 container.layout().addWidget(self.z_range_slider) 3600 3601 self.full_z_range_checkbox.stateChanged.connect(self._on_full_z_range_changed) 3602 self.z_range_slider.valueChanged.connect(self._sync_propagation_settings) 3603 3604 return _make_collapsible( 3605 container, title="Volume Propagation Settings", tooltip=get_tooltip("segmentnd", "settings"), 3606 ) 3607 3608 def _on_full_z_range_changed(self, state): 3609 """Enable/disable the z-range slider and push the change to the engine.""" 3610 self.use_full_z_range = bool(state) 3611 self.z_range_slider.setEnabled(not self.use_full_z_range) 3612 self._sync_propagation_settings() 3613 3614 def _update_z_range_slider(self): 3615 """Match the z-range slider extent to the depth of the loaded volume.""" 3616 state = AnnotatorState() 3617 if state.image_shape is None: 3618 return 3619 z_max = int(state.image_shape[0]) - 1 3620 if z_max < 0: 3621 return 3622 lo, hi = self.z_range_slider.value() 3623 self.z_range_slider.setRange(0, z_max) 3624 if not self.use_full_z_range and hi <= z_max and lo < hi: 3625 self.z_range_slider.setValue((lo, hi)) 3626 else: 3627 self.z_range_slider.setValue((0, z_max)) 3628 3629 def _sync_propagation_settings(self, *args): 3630 """Write the propagation controls into the hidden segmentation engine.""" 3631 if self._segment_widget is None: 3632 return 3633 self._segment_widget.early_stop_patience = int(self.early_stop_patience_param.value()) 3634 if bool(self.use_full_z_range): 3635 self._segment_widget.z_range = None 3636 else: 3637 self._segment_widget.z_range = tuple(int(v) for v in self.z_range_slider.value()) 3638 3639 def _on_apply_to_volume_changed(self, state): 3640 """Sync the shared volume mode to the segmentation engine.""" 3641 self.apply_to_volume = bool(state) 3642 self._segment_widget.apply_to_volume = self.apply_to_volume 3643 3644 # Show the propagation controls only in volume mode with a loaded model. Then fit the slider to the volume. 3645 if self._propagation_settings is not None: 3646 show = self.apply_to_volume and AnnotatorState().predictor is not None 3647 self._propagation_settings.setVisible(show) 3648 if show: 3649 self._update_z_range_slider() 3650 self._sync_propagation_settings() 3651 3652 def _on_batched_changed(self, state): 3653 """Sync the batched mode to the segmentation engine.""" 3654 self.batched = bool(state) 3655 self._segment_widget.batched = self.batched 3656 3657 def segment(self, viewer=None): 3658 """Run interactive segmentation for the current prompts.""" 3659 self.segment_requested.emit() 3660 if self._ndim == 2: 3661 _segment_object_2d(self._viewer, batched=bool(self.batched)) 3662 else: 3663 self._sync_propagation_settings() 3664 self._segment_widget(self._viewer) 3665 3666 def clear(self, viewer=None): 3667 """Clear the current annotations.""" 3668 if self._segment_widget is not None: 3669 if self._segment_widget.is_running: 3670 show_info("The segmentation is still running. Wait until it finishes.") 3671 return 3672 self._segment_widget.reset_last_volume_run() 3673 3674 if self._ndim == 2 or self.apply_to_volume: 3675 vutil.clear_annotations(self._viewer) 3676 else: 3677 i = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3678 vutil.clear_annotations_slice(self._viewer, i=i) 3679 3680 # If this is a SAM2 promptable segmentation workflow, 3681 # reset the prompts after the user clears the annotations. 3682 state = AnnotatorState() 3683 if state.interactive_segmenter is not None: 3684 state.interactive_segmenter.reset_predictor() 3685 3686 gc.collect()
Interactive segmentation widget combining the prompt menu, segmentation and clearing.
This widget adapts to the data dimensionality and works with both SAM and SAM2 models. For 3d data it exposes a single 'Apply to Volume' checkbox that governs both segmentation and clearing (current slice vs. the whole volume / all slices), plus a batched toggle (SAM2 volume mode) for multi-object segmentation.
Arguments:
- viewer: The napari viewer.
- ndim: The number of spatial dimensions of the data (2 or 3).
- prompt_widget: The point prompt label menu created by
create_prompt_menu. - parent: The parent Qt widget.
3456 def __init__(self, viewer, ndim, prompt_widget, parent=None): 3457 super().__init__(parent=parent) 3458 self._viewer = viewer 3459 self._ndim = ndim 3460 self._prompt_widget = prompt_widget 3461 self.batched = False 3462 self.apply_to_volume = False 3463 self._segment_widget = None 3464 self._propagation_settings = None 3465 self._create_widget()
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
3657 def segment(self, viewer=None): 3658 """Run interactive segmentation for the current prompts.""" 3659 self.segment_requested.emit() 3660 if self._ndim == 2: 3661 _segment_object_2d(self._viewer, batched=bool(self.batched)) 3662 else: 3663 self._sync_propagation_settings() 3664 self._segment_widget(self._viewer)
Run interactive segmentation for the current prompts.
3666 def clear(self, viewer=None): 3667 """Clear the current annotations.""" 3668 if self._segment_widget is not None: 3669 if self._segment_widget.is_running: 3670 show_info("The segmentation is still running. Wait until it finishes.") 3671 return 3672 self._segment_widget.reset_last_volume_run() 3673 3674 if self._ndim == 2 or self.apply_to_volume: 3675 vutil.clear_annotations(self._viewer) 3676 else: 3677 i = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3678 vutil.clear_annotations_slice(self._viewer, i=i) 3679 3680 # If this is a SAM2 promptable segmentation workflow, 3681 # reset the prompts after the user clears the annotations. 3682 state = AnnotatorState() 3683 if state.interactive_segmenter is not None: 3684 state.interactive_segmenter.reset_predictor() 3685 3686 gc.collect()
Clear the current annotations.
3689class InteractiveTrackingWidget(_WidgetBase): 3690 """Merged interactive widget for the tracking annotator. 3691 3692 Combines the prompt label menu, the track id / track state menus and the segment / clear 3693 controls into a single container, mirroring the segmentation annotator's 3694 'InteractiveSegmentationWidget'. The 'Apply to All Frames' checkbox governs both segmentation 3695 (current frame vs. propagating across the whole video) and clearing (current frame vs. all 3696 frames). A hidden 'UnifiedSegmentWidget' is used purely as the segmentation engine. 3697 3698 Args: 3699 viewer: The napari viewer. 3700 tracking_widget: The combined prompt label / track id / track state menu created by 3701 'create_tracking_menu'. 3702 parent: The parent Qt widget. 3703 """ 3704 3705 segment_requested = Signal() 3706 3707 def __init__(self, viewer, tracking_widget, parent=None): 3708 super().__init__(parent=parent) 3709 self._viewer = viewer 3710 self._tracking_widget = tracking_widget 3711 self.apply_to_volume = False 3712 self._segment_widget = None 3713 self._create_widget() 3714 3715 def _create_widget(self): 3716 # The combined prompt label / track id / track state menus (one container so the three 3717 # dropdowns share an aligned label column). Lay each row out as label-left, box-right. 3718 self.layout().addWidget(self._tracking_widget.native) 3719 self._align_menu_rows() 3720 3721 # Hidden segmentation engine: owns the per-frame and propagation logic, driven via its 3722 # 'apply_to_volume' attribute. Its own controls are not shown. 3723 self._segment_widget = UnifiedSegmentWidget(self._viewer, tracking=True) 3724 self._segment_widget.setVisible(False) 3725 self.layout().addWidget(self._segment_widget) 3726 3727 # 'Apply to All Frames' toggles between segmenting the current frame and propagating the track. 3728 self.apply_to_volume_checkbox = self._add_boolean_param( 3729 "apply_to_volume", self.apply_to_volume, title="Apply to All Frames", 3730 tooltip=get_tooltip("unified_segment", "apply_to_volume"), 3731 ) 3732 self.apply_to_volume_checkbox.stateChanged.connect(self._on_apply_to_volume_changed) 3733 self.layout().addWidget(self.apply_to_volume_checkbox) 3734 3735 # 'Segment Object' / 'Clear Annotations' side by side. 3736 self.segment_button = QtWidgets.QPushButton("Segment Object [S]") 3737 self.segment_button.setToolTip(get_tooltip("unified_segment", "segment_button")) 3738 self.segment_button.clicked.connect(lambda: self.segment()) 3739 self.clear_button = QtWidgets.QPushButton("Clear Annotations [Shift + C]") 3740 self.clear_button.setToolTip(get_tooltip("unified_segment", "clear_button")) 3741 self.clear_button.clicked.connect(lambda: self.clear()) 3742 button_row = QtWidgets.QHBoxLayout() 3743 button_row.addWidget(self.segment_button) 3744 button_row.addWidget(self.clear_button) 3745 self.layout().addLayout(button_row) 3746 3747 def _align_menu_rows(self): 3748 # Each menu row is a QHBoxLayout of [QLabel, QComboBox]. Insert a stretch between them so the 3749 # label stays left and the (fixed-width) combo box is right-aligned. Idempotent, since the 3750 # menu container persists across layout rebuilds. 3751 container_layout = self._tracking_widget.native.layout() 3752 for i in range(container_layout.count()): 3753 row = container_layout.itemAt(i).widget() 3754 row_layout = None if row is None else row.layout() 3755 if row_layout is None or row_layout.count() < 2: 3756 continue 3757 combo = row_layout.itemAt(row_layout.count() - 1).widget() 3758 if combo is not None: 3759 combo.setFixedWidth(300) 3760 if row_layout.count() < 3: # No stretch inserted yet. 3761 row_layout.insertStretch(1) 3762 3763 def _on_apply_to_volume_changed(self, state): 3764 self.apply_to_volume = bool(state) 3765 self._segment_widget.apply_to_volume = self.apply_to_volume 3766 3767 def segment(self, viewer=None): 3768 """Run interactive tracking segmentation for the current prompts.""" 3769 self.segment_requested.emit() 3770 self._segment_widget(self._viewer) 3771 3772 def clear(self, viewer=None): 3773 """Clear the annotations: the current frame, or all frames in 'Apply to All Frames' mode.""" 3774 if self._segment_widget.is_running: 3775 show_info("The segmentation is still running. Wait until it finishes.") 3776 return 3777 3778 if self.apply_to_volume: 3779 _reset_tracking_state(self._viewer) 3780 vutil.clear_annotations(self._viewer) 3781 else: 3782 i = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3783 vutil.clear_annotations_slice(self._viewer, i=i) 3784 3785 state = AnnotatorState() 3786 if state.interactive_segmenter is not None: 3787 state.interactive_segmenter.reset_predictor() 3788 gc.collect()
Merged interactive widget for the tracking annotator.
Combines the prompt label menu, the track id / track state menus and the segment / clear controls into a single container, mirroring the segmentation annotator's 'InteractiveSegmentationWidget'. The 'Apply to All Frames' checkbox governs both segmentation (current frame vs. propagating across the whole video) and clearing (current frame vs. all frames). A hidden 'UnifiedSegmentWidget' is used purely as the segmentation engine.
Arguments:
- viewer: The napari viewer.
- tracking_widget: The combined prompt label / track id / track state menu created by 'create_tracking_menu'.
- parent: The parent Qt widget.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
3767 def segment(self, viewer=None): 3768 """Run interactive tracking segmentation for the current prompts.""" 3769 self.segment_requested.emit() 3770 self._segment_widget(self._viewer)
Run interactive tracking segmentation for the current prompts.
3772 def clear(self, viewer=None): 3773 """Clear the annotations: the current frame, or all frames in 'Apply to All Frames' mode.""" 3774 if self._segment_widget.is_running: 3775 show_info("The segmentation is still running. Wait until it finishes.") 3776 return 3777 3778 if self.apply_to_volume: 3779 _reset_tracking_state(self._viewer) 3780 vutil.clear_annotations(self._viewer) 3781 else: 3782 i = vutil.current_slice(self._viewer, self._viewer.layers["current_object"]) 3783 vutil.clear_annotations_slice(self._viewer, i=i) 3784 3785 state = AnnotatorState() 3786 if state.interactive_segmenter is not None: 3787 state.interactive_segmenter.reset_predictor() 3788 gc.collect()
Clear the annotations: the current frame, or all frames in 'Apply to All Frames' mode.
3849class AutoSegmentWidget(_WidgetBase): 3850 """Automatic segmentation widget for SAM2 with the APG, sparse and dense modes. 3851 3852 Subclasses set `_is_tracking = True` to hide the z-tiling controls (tracking segments per frame 3853 in 2d, so z-tiling does not apply). 3854 3855 All modes need a UniSAM2 decoder. Automatic prompt generation (APG) derives point prompts from 3856 the decoder predictions and applies them to the interactive branch; it is the default on CUDA 3857 and MPS. The sparse mode (AIS) is the CPU default. Sparse and dense modes post-process the 3858 decoder predictions directly. Without a decoder there is no automatic segmentation: the run 3859 button is disabled until a model that has one is loaded. 3860 3861 Disk-backed caching of the state is opted into via the 'cache automatic segmentation state' 3862 checkbox in the embedding settings (read here through the embedding widget); when off, the state 3863 is kept in memory only. 3864 3865 Args: 3866 viewer: The napari viewer. 3867 with_decoder: Whether the loaded model has a UniSAM2 decoder for automatic segmentation. 3868 volumetric: Whether the data is volumetric (3d). 3869 parent: The parent Qt widget. 3870 """ 3871 3872 segmentation_finished = Signal() 3873 3874 _is_tracking = False 3875 MODES = ("apg", "sparse", "dense") 3876 # The (section, name) of the run button's tooltip; the tracking subclass has its own. 3877 _RUN_TOOLTIP = ("autosegment", "run_button") 3878 3879 def __init__(self, viewer, with_decoder, volumetric, parent=None): 3880 super().__init__(parent) 3881 self._viewer = viewer 3882 self.with_decoder = with_decoder 3883 self.volumetric = volumetric 3884 # Every mode needs a decoder. APG additionally needs an accelerator for volumetric data and 3885 # for tracking, so it is dropped from the list there - see '_available_modes'. 3886 self.mode = self._default_mode() 3887 self.settings = None 3888 # z block / halo for 3d decoder inference: the volume is decoded in z chunks to bound memory. 3889 # These only matter for volumetric decoder modes. Set 'tile_z' >= the slice count for no z-tiling. 3890 from micro_sam.v2.util import DEFAULT_TILE_Z, DEFAULT_HALO_Z 3891 self.tile_z, self.halo_z = DEFAULT_TILE_Z, DEFAULT_HALO_Z 3892 # Cache of the (initialized) segmentation generator so changing post-processing parameters 3893 # only re-runs 'generate', not the expensive UniSAM2 inference. Keyed by the inputs. 3894 self._segmenter = None 3895 self._segmenter_key = None 3896 # The decoder prediction the generator is built from. It does not depend on the mode, so it 3897 # outlives the generator and is shared by 'sparse', 'dense' and 'apg'. 3898 self._decoder_state = None 3899 self._decoder_state_key = None 3900 self._decoder_state_save_path = None 3901 # The APG proposals, so that changing only the merge parameters skips the prompting. 3902 self._proposals = None 3903 self._proposals_key = None 3904 self._create_widget() 3905 3906 def _apg_is_available(self): 3907 # A plain 2d image prompts the image predictor and runs anywhere. Volumetric data and a 3908 # timeseries go through the video predictor, which needs an accelerator. Before the model is 3909 # loaded ('Compute Embeddings') the device is not known yet, so APG is offered and the sync 3910 # afterwards ('_reset_segmentation_mode') settles it. 3911 if not (self.volumetric or self._is_tracking): 3912 return True 3913 state = AnnotatorState() 3914 return state.decoder is None or _apg_runs_on_this_device(state) 3915 3916 def _available_modes(self): 3917 """The modes offered for this widget's data on the loaded device. 3918 3919 Returns: 3920 The mode names, in dropdown order. The first is the default. 3921 """ 3922 from micro_sam._model_settings import DEFAULT_POSTPROCESSING 3923 from micro_sam.v2.util import DEFAULT_MODEL, parameter_family 3924 3925 # Only a model with dense defaults segments neurites, e.g. not the EM organelle models. 3926 model_type = getattr(self, "model_type", None) or DEFAULT_MODEL 3927 has_dense = "dense" in DEFAULT_POSTPROCESSING.get(parameter_family(model_type), {}).get(model_type[:6], {}) 3928 modes = self.MODES if has_dense else tuple(mode for mode in self.MODES if mode != "dense") 3929 if not self._apg_is_available(): 3930 return tuple(mode for mode in modes if mode != "apg") 3931 3932 # Tiled APG can take hours on CPU. Prefer the direct decoder post-processing there, 3933 # while retaining APG as an explicit choice for 2d images. Before model loading, use 3934 # the available hardware; afterwards the decoder's device is authoritative, including 3935 # when the user explicitly chose CPU on a machine with an accelerator. 3936 state = AnnotatorState() 3937 device = util.get_device() if state.decoder is None else next(state.decoder.parameters()).device 3938 if util.device_type(device) not in APG_ACCELERATORS: 3939 return ("sparse", *(mode for mode in modes if mode != "sparse")) 3940 return modes 3941 3942 def _default_mode(self): 3943 return self._available_modes()[0] 3944 3945 def _mode_choices(self): 3946 return tuple(self.mode_dropdown.itemText(i) for i in range(self.mode_dropdown.count())) 3947 3948 def _create_widget(self): 3949 # Top row: the mode dropdown on the left, the 'Apply to Volume' switch (3d only) on the right. 3950 top_row = QtWidgets.QHBoxLayout() 3951 3952 self.mode_dropdown, mode_layout = self._add_choice_param( 3953 "mode", 3954 self.mode, 3955 list(self._available_modes()), 3956 title="mode:", 3957 update=self._on_mode_changed, 3958 tooltip=get_tooltip("autosegment", "mode"), 3959 ) 3960 # Keep the label at its text width so that the dropdown starts right after it and covers 3961 # the rest of the row. 3962 mode_layout.setStretch(0, 0) 3963 mode_layout.setStretch(1, 1) 3964 top_row.addLayout(mode_layout) 3965 3966 if self.volumetric: 3967 self.apply_to_volume = False 3968 self.apply_to_volume_checkbox = self._add_boolean_param( 3969 "apply_to_volume", 3970 self.apply_to_volume, 3971 title="Apply to Volume", 3972 tooltip=get_tooltip("autosegment", "apply_to_volume"), 3973 ) 3974 # The handler reads 'apply_to_volume', so it must run after the checkbox updates it. 3975 self.apply_to_volume_checkbox.stateChanged.connect(self._on_apply_to_volume_changed) 3976 top_row.addWidget(self.apply_to_volume_checkbox) 3977 3978 self.layout().addLayout(top_row) 3979 3980 # Advanced post-processing settings, shown inline and refreshed on mode change. 3981 self.settings = self._make_settings_widget() 3982 self.layout().addWidget(self.settings) 3983 3984 # Run button. It is only active with a decoder, since every mode needs one. 3985 self.run_button = QtWidgets.QPushButton("Automatic Segmentation") 3986 self.run_button.clicked.connect(self.__call__) 3987 self.layout().addWidget(self.run_button) 3988 self._update_run_button() 3989 3990 def _update_run_button(self): 3991 # Without a decoder none of the modes can run, so the button is disabled and says why. 3992 self.run_button.setEnabled(self.with_decoder) 3993 self.run_button.setToolTip( 3994 get_tooltip(*self._RUN_TOOLTIP) if self.with_decoder else NO_DECODER_MESSAGE 3995 ) 3996 3997 def _reset_segmentation_mode(self, with_decoder, model_type=None): 3998 # If neither the decoder availability, the offered modes nor the model changed there is nothing 3999 # to rebuild. The device can change the offered modes (volumes/tracking) or their order 4000 # (the CPU default is sparse, even for 2d), triggering a reset to the new default. The model 4001 # selects the default parameters, see 'default_postprocessing' and 'default_prompt_generation'. 4002 modes = self._available_modes() 4003 model_changed = model_type is not None and model_type != getattr(self, "model_type", None) 4004 if with_decoder == self.with_decoder and modes == self._mode_choices() and not model_changed: 4005 return 4006 if model_type is not None: 4007 self.model_type = model_type 4008 modes = self._available_modes() 4009 self.with_decoder = with_decoder 4010 self._update_run_button() 4011 4012 # Rebuild the list and go back to the default mode for the newly loaded model. 4013 self.mode_dropdown.blockSignals(True) 4014 self.mode_dropdown.clear() 4015 self.mode_dropdown.addItems(list(modes)) 4016 self.mode_dropdown.setCurrentText(self._default_mode()) 4017 self.mode_dropdown.blockSignals(False) 4018 4019 # Drop the cached segmenter and the decoder prediction, since the loaded model (and so its 4020 # predictions) changed, and refresh the settings panel to match the new default mode. 4021 self._release_segmenter() 4022 self._drop_decoder_state() 4023 self._on_mode_changed() 4024 4025 def _on_mode_changed(self, index=None): 4026 self.mode = self.mode_dropdown.currentText() 4027 new_settings = self._make_settings_widget() 4028 self.layout().replaceWidget(self.settings, new_settings) 4029 self.settings.deleteLater() 4030 self.settings = new_settings 4031 4032 def _make_settings_widget(self): 4033 # All hyperparameters (except mode and apply-to-volume) live in one collapsible 4034 # 'Advanced Settings' panel. The z block / halo (3d decoder modes) sit at the very top. 4035 advanced = QtWidgets.QWidget() 4036 advanced.setLayout(QtWidgets.QVBoxLayout()) 4037 advanced.layout().setContentsMargins(0, 0, 0, 0) 4038 self._add_z_tiling_params(advanced) 4039 if self.mode == "apg": 4040 self._apg_settings(advanced) 4041 elif self.mode == "dense": 4042 self._dense_settings(advanced) 4043 else: 4044 self._sparse_settings(advanced) 4045 4046 settings = QtWidgets.QWidget() 4047 settings.setLayout(QtWidgets.QVBoxLayout()) 4048 settings.layout().setContentsMargins(0, 0, 0, 0) 4049 advanced_tooltip = get_tooltip("autosegment", "advanced_settings") 4050 settings.layout().addWidget( 4051 _make_collapsible(advanced, title="Advanced Settings", tooltip=advanced_tooltip) 4052 ) 4053 return settings 4054 4055 def _add_density_threshold(self, settings): 4056 self.density_threshold_param, layout = self._add_float_param( 4057 "density_threshold", self.density_threshold, min_val=0.0, max_val=100.0, step=1.0, 4058 tooltip=get_tooltip("autosegment", "density_threshold"), 4059 ) 4060 settings.layout().addLayout(layout) 4061 4062 def _add_z_tiling_params(self, settings): 4063 # 3d decoder inference decodes the volume in z blocks (with a halo for context) to bound 4064 # memory. 'tile_z' and 'halo_z' sit side by side at the top of the settings. Only for 4065 # volumetric segmentation - not 2d and not tracking (which segments each frame in 2d). 4066 if not self.volumetric or self._is_tracking: 4067 return 4068 row = QtWidgets.QHBoxLayout() 4069 self.tile_z_param, _ = self._add_int_param( 4070 "tile_z", self.tile_z, min_val=1, max_val=512, title="tile_z:", 4071 tooltip=get_tooltip("autosegment", "tile_z"), layout=row, 4072 ) 4073 self.halo_z_param, _ = self._add_int_param( 4074 "halo_z", self.halo_z, min_val=0, max_val=128, title="overlap_z:", 4075 tooltip=get_tooltip("autosegment", "halo_z"), layout=row, 4076 ) 4077 settings.layout().addLayout(row) 4078 4079 def _add_flow_integration_params(self, settings, n_iter, dt=0.5, sigma=1.0): 4080 self.n_iter = n_iter 4081 self.n_iter_param, layout = self._add_int_param( 4082 "n_iter", self.n_iter, min_val=1, max_val=1000, tooltip=get_tooltip("autosegment", "n_iter"), 4083 ) 4084 settings.layout().addLayout(layout) 4085 4086 self.dt = dt 4087 self.dt_param, layout = self._add_float_param( 4088 "dt", self.dt, min_val=0.0, max_val=5.0, step=0.1, tooltip=get_tooltip("autosegment", "dt"), 4089 ) 4090 settings.layout().addLayout(layout) 4091 4092 self.sigma = sigma 4093 self.sigma_param, layout = self._add_float_param( 4094 "sigma", self.sigma, min_val=0.0, max_val=10.0, step=0.1, tooltip=get_tooltip("autosegment", "sigma"), 4095 ) 4096 settings.layout().addLayout(layout) 4097 4098 # Default to 8 threads for the post-processing flow/multicut backends (a sensible default that 4099 # does not oversubscribe. The user can raise it up to the spinbox maximum). 4100 self.n_threads = min(8, mp.cpu_count()) 4101 self.n_threads_param, layout = self._add_int_param( 4102 "n_threads", self.n_threads, min_val=1, max_val=64, tooltip=get_tooltip("autosegment", "n_threads"), 4103 ) 4104 settings.layout().addLayout(layout) 4105 4106 def _sparse_settings(self, settings): 4107 # Flow-based instance segmentation parameters (LM data). 4108 from micro_sam.v2.postprocessing import default_postprocessing 4109 from micro_sam.v2.util import DEFAULT_MODEL 4110 defaults = default_postprocessing( 4111 getattr(self, "model_type", None) or DEFAULT_MODEL, "sparse", is_volume=self._run_ndim() == 3, 4112 ) 4113 4114 self.foreground_threshold = defaults["foreground_threshold"] 4115 self.foreground_threshold_param, layout = self._add_float_param( 4116 "foreground_threshold", self.foreground_threshold, min_val=0.0, max_val=1.0, step=0.05, 4117 tooltip=get_tooltip("autosegment", "foreground_threshold"), 4118 ) 4119 settings.layout().addLayout(layout) 4120 4121 self.density_threshold = defaults["density_threshold"] 4122 self._add_density_threshold(settings) 4123 4124 self.min_object_size = defaults["min_size"] 4125 self.min_object_size_param, layout = self._add_int_param( 4126 "min_object_size", self.min_object_size, min_val=0, max_val=int(1e4), 4127 tooltip=get_tooltip("autosegment", "min_object_size"), 4128 ) 4129 settings.layout().addLayout(layout) 4130 4131 self._add_flow_integration_params( 4132 settings, 4133 n_iter=defaults["n_iter"], 4134 dt=defaults["dt"], 4135 sigma=defaults["sigma"], 4136 ) 4137 4138 def _dense_settings(self, settings): 4139 # Multicut-based instance segmentation parameters (EM data, 2d and 3d). 4140 from micro_sam.v2.postprocessing import default_postprocessing 4141 from micro_sam.v2.util import DEFAULT_MODEL 4142 defaults = default_postprocessing(getattr(self, "model_type", None) or DEFAULT_MODEL, "dense") 4143 4144 self.beta = defaults["beta"] 4145 self.beta_param, layout = self._add_float_param( 4146 "beta", self.beta, min_val=0.0, max_val=1.0, step=0.05, 4147 tooltip=get_tooltip("autosegment", "beta"), 4148 ) 4149 settings.layout().addLayout(layout) 4150 4151 self.density_threshold = defaults["density_threshold"] 4152 self._add_density_threshold(settings) 4153 4154 self._add_flow_integration_params( 4155 settings, 4156 n_iter=defaults["n_iter"], 4157 dt=defaults["dt"], 4158 sigma=defaults["sigma"], 4159 ) 4160 4161 # The APG parameters with other defaults for a volume, as (widget attribute, key of the defaults). 4162 _APG_DIMENSION_PARAMS = ( 4163 ("candidate_threshold", "candidate_threshold"), ("min_candidate_size", "min_candidate_size"), 4164 ("score_threshold", "score_threshold"), ("max_overlap", "max_overlap"), 4165 ("min_object_size", "min_size"), ("sigma", "sigma"), ("foreground_threshold", "foreground_threshold"), 4166 ) 4167 4168 def _apg_default_values(self, is_volume): 4169 """The defaults of the APG parameters that depend on the dimensionality of the run. 4170 4171 Args: 4172 is_volume: Whether the run segments a whole volume rather than an image or a slice. 4173 4174 Returns: 4175 The default values, keyed by the widget attribute. 4176 """ 4177 from micro_sam.v2.util import DEFAULT_MODEL 4178 from micro_sam.v2.automatic_prompt_generation import default_prompt_generation 4179 model_type = getattr(self, "model_type", None) or DEFAULT_MODEL 4180 defaults = default_prompt_generation(model_type, is_volume=is_volume) 4181 values = {attribute: defaults[key] for attribute, key in self._APG_DIMENSION_PARAMS} 4182 if is_volume: # A volume has a (low, high) pair of candidate thresholds. 4183 values["candidate_threshold"], values["candidate_threshold_high"] = defaults["candidate_threshold"] 4184 values["refine_with_box_prompts"] = defaults["refinement"] == "boxes" 4185 return values 4186 4187 def _on_apply_to_volume_changed(self, state=None): 4188 # Show the parameters of the next run. A slice run and a volume run keep their own values. 4189 if self.mode != "apg" or len(self._apg_values) < 2: 4190 return 4191 is_volume = self._run_ndim() == 3 4192 previous = self._apg_values[not is_volume] 4193 for attribute in previous: 4194 previous[attribute] = getattr(self, attribute) 4195 for attribute, value in self._apg_values[is_volume].items(): 4196 if attribute == "refine_with_box_prompts": 4197 self.refine_with_box_prompts_checkbox.setChecked(bool(value)) # also updates the attribute 4198 else: 4199 getattr(self, f"{attribute}_param").setValue(value) # also updates the attribute 4200 self.candidate_threshold_high_row.setVisible(is_volume) 4201 4202 def _apg_settings(self, settings): 4203 from micro_sam.v2.automatic_prompt_generation import ( 4204 DEFAULT_PROMPT_GENERATION, DEFAULT_REFINEMENT, default_prompt_generation, 4205 ) 4206 from micro_sam.v2.util import DEFAULT_MODEL 4207 model_type = getattr(self, "model_type", None) or DEFAULT_MODEL 4208 defaults = default_prompt_generation(model_type, is_volume=False) 4209 4210 # The parameters of a slice run (False) and of a volume run (True). 4211 self._apg_values = {False: self._apg_default_values(is_volume=False)} 4212 if self.volumetric and not self._is_tracking: 4213 self._apg_values[True] = self._apg_default_values(is_volume=True) 4214 is_volume = self._run_ndim() == 3 4215 values = self._apg_values[is_volume] 4216 4217 self.candidate_threshold = values["candidate_threshold"] 4218 self.candidate_threshold_param, layout = self._add_float_param( 4219 "candidate_threshold", self.candidate_threshold, min_val=0.0, max_val=100.0, step=0.1, 4220 tooltip=get_tooltip("autosegment", "candidate_threshold"), 4221 ) 4222 settings.layout().addLayout(layout) 4223 4224 if self.volumetric and not self._is_tracking: 4225 # Only a volume run uses the second threshold. 4226 self.candidate_threshold_high = self._apg_values[True]["candidate_threshold_high"] 4227 self.candidate_threshold_high_param, layout = self._add_float_param( 4228 "candidate_threshold_high", self.candidate_threshold_high, min_val=0.0, max_val=100.0, step=0.1, 4229 tooltip=get_tooltip("autosegment", "candidate_threshold_high"), 4230 ) 4231 layout.setContentsMargins(0, 0, 0, 0) 4232 self.candidate_threshold_high_row = QtWidgets.QWidget() 4233 self.candidate_threshold_high_row.setLayout(layout) 4234 self.candidate_threshold_high_row.setVisible(is_volume) 4235 settings.layout().addWidget(self.candidate_threshold_high_row) 4236 4237 self.foreground_threshold = values["foreground_threshold"] 4238 self.foreground_threshold_param, layout = self._add_float_param( 4239 "foreground_threshold", self.foreground_threshold, min_val=0.0, max_val=1.0, step=0.05, 4240 tooltip=get_tooltip("autosegment", "foreground_threshold"), 4241 ) 4242 settings.layout().addLayout(layout) 4243 4244 self.min_candidate_size = values["min_candidate_size"] 4245 self.min_candidate_size_param, layout = self._add_int_param( 4246 "min_candidate_size", self.min_candidate_size, min_val=0, max_val=int(1e4), 4247 tooltip=get_tooltip("autosegment", "min_candidate_size"), 4248 ) 4249 settings.layout().addLayout(layout) 4250 4251 self.score_threshold = values["score_threshold"] 4252 self.score_threshold_param, layout = self._add_float_param( 4253 "score_threshold", self.score_threshold, min_val=0.0, max_val=1.0, step=0.05, 4254 tooltip=get_tooltip("autosegment", "score_threshold"), 4255 ) 4256 settings.layout().addLayout(layout) 4257 4258 self.max_overlap = values["max_overlap"] 4259 self.max_overlap_param, layout = self._add_float_param( 4260 "max_overlap", self.max_overlap, min_val=0.0, max_val=1.0, step=0.05, 4261 tooltip=get_tooltip("autosegment", "max_overlap"), 4262 ) 4263 settings.layout().addLayout(layout) 4264 4265 self.min_object_size = values["min_object_size"] 4266 self.min_object_size_param, layout = self._add_int_param( 4267 "min_object_size", self.min_object_size, min_val=0, max_val=int(1e4), 4268 tooltip=get_tooltip("autosegment", "min_object_size"), 4269 ) 4270 settings.layout().addLayout(layout) 4271 4272 self.multimasking = DEFAULT_PROMPT_GENERATION["multimasking"] 4273 self.multimasking_checkbox = self._add_boolean_param( 4274 "multimasking", self.multimasking, tooltip=get_tooltip("autosegment", "multimasking"), 4275 ) 4276 settings.layout().addWidget(self.multimasking_checkbox) 4277 4278 self.refine_with_box_prompts = values["refine_with_box_prompts"] 4279 self.refine_with_box_prompts_checkbox = self._add_boolean_param( 4280 "refine_with_box_prompts", self.refine_with_box_prompts, 4281 tooltip=get_tooltip("autosegment", "refine_with_box_prompts"), 4282 ) 4283 settings.layout().addWidget(self.refine_with_box_prompts_checkbox) 4284 4285 self.box_extension = DEFAULT_REFINEMENT["box_extension"] 4286 self.box_extension_param, layout = self._add_int_param( 4287 "box_extension", self.box_extension, min_val=0, max_val=100, 4288 tooltip=get_tooltip("autosegment", "box_extension"), 4289 ) 4290 settings.layout().addLayout(layout) 4291 4292 self.prompt_batch_size = DEFAULT_PROMPT_GENERATION["batch_size"] 4293 self.prompt_batch_size_param, layout = self._add_int_param( 4294 "prompt_batch_size", self.prompt_batch_size, min_val=1, max_val=1024, 4295 tooltip=get_tooltip("autosegment", "prompt_batch_size"), 4296 ) 4297 settings.layout().addLayout(layout) 4298 4299 if self.volumetric and not self._is_tracking: 4300 self.n_objects_per_pass = DEFAULT_PROMPT_GENERATION["n_objects_per_pass"] 4301 self.n_objects_per_pass_param, layout = self._add_int_param( 4302 "n_objects_per_pass", self.n_objects_per_pass, min_val=1, max_val=1024, 4303 tooltip=get_tooltip("autosegment", "n_objects_per_pass"), 4304 ) 4305 settings.layout().addLayout(layout) 4306 4307 self.early_stop_patience = DEFAULT_PROMPT_GENERATION["early_stop_patience"] 4308 self.early_stop_patience_param, layout = self._add_int_param( 4309 "early_stop_patience", self.early_stop_patience, min_val=0, max_val=1024, 4310 tooltip=get_tooltip("autosegment", "early_stop_patience"), 4311 ) 4312 settings.layout().addLayout(layout) 4313 4314 self._add_flow_integration_params( 4315 settings, n_iter=defaults["n_iter"], dt=DEFAULT_PROMPT_GENERATION["dt"], sigma=values["sigma"], 4316 ) 4317 4318 def _postproc_kwargs(self): 4319 if self.mode == "dense": 4320 return dict( 4321 beta=self.beta, density_threshold=self.density_threshold, n_iter=self.n_iter, 4322 dt=self.dt, sigma=self.sigma, n_threads=self.n_threads, 4323 ) 4324 return dict( 4325 foreground_threshold=self.foreground_threshold, density_threshold=self.density_threshold, 4326 min_size=self.min_object_size, n_iter=self.n_iter, dt=self.dt, sigma=self.sigma, 4327 n_threads=self.n_threads, 4328 ) 4329 4330 def _apg_kwargs(self, ndim): 4331 candidate_threshold = self.candidate_threshold 4332 if ndim == 3: 4333 candidate_threshold = (candidate_threshold, self.candidate_threshold_high) 4334 refinement = "boxes" if self.refine_with_box_prompts else None 4335 refinement_kwargs = {"box_extension": self.box_extension} if refinement is not None else None 4336 4337 kwargs = dict( 4338 candidate_threshold=candidate_threshold, foreground_threshold=self.foreground_threshold, 4339 min_candidate_size=self.min_candidate_size, score_threshold=self.score_threshold, 4340 max_overlap=self.max_overlap, min_size=self.min_object_size, 4341 refinement=refinement, refinement_kwargs=refinement_kwargs, 4342 multimasking=bool(self.multimasking), batch_size=self.prompt_batch_size, 4343 n_iter=self.n_iter, dt=self.dt, sigma=self.sigma, n_threads=self.n_threads, 4344 ) 4345 if ndim == 3: 4346 kwargs["n_objects_per_pass"] = self.n_objects_per_pass 4347 kwargs["early_stop_patience"] = self.early_stop_patience or None 4348 return kwargs 4349 4350 def _apg_propose_kwargs(self): 4351 # The prompting stage: everything that decides which candidates are prompted, and how. 4352 return dict( 4353 candidate_threshold=self.candidate_threshold, foreground_threshold=self.foreground_threshold, 4354 n_iter=self.n_iter, dt=self.dt, sigma=self.sigma, min_candidate_size=self.min_candidate_size, 4355 multimasking=bool(self.multimasking), batch_size=self.prompt_batch_size, n_threads=self.n_threads, 4356 ) 4357 4358 def _apg_select_kwargs(self): 4359 # The merge stage: post-processing of the proposals, cheap next to the prompting. 4360 refinement = "boxes" if self.refine_with_box_prompts else None 4361 refinement_kwargs = {"box_extension": self.box_extension} if refinement is not None else None 4362 return dict( 4363 score_threshold=self.score_threshold, max_overlap=self.max_overlap, min_size=self.min_object_size, 4364 refinement=refinement, refinement_kwargs=refinement_kwargs, 4365 batch_size=self.prompt_batch_size, 4366 ) 4367 4368 def _run_ndim(self): 4369 # The dimensionality of the next run: 3 only for a volume segmented as a whole. Tracking 4370 # segments each frame in 2d, so it stays 2 there even with 'Track Timeseries' on. 4371 if self.volumetric and not self._is_tracking and getattr(self, "apply_to_volume", False): 4372 return 3 4373 return 2 4374 4375 def commit_settings(self): 4376 """The parameters of the current automatic segmentation, for the commit history. 4377 4378 Returns: 4379 A json-serializable dict with the mode and the parameters that mode runs with. 4380 """ 4381 settings = {"mode": self.mode} 4382 if self.mode == "apg": 4383 settings.update(self._apg_kwargs(self._run_ndim())) 4384 else: 4385 settings.update(self._postproc_kwargs()) 4386 4387 if self.volumetric: 4388 settings["apply_to_volume"] = bool(getattr(self, "apply_to_volume", False)) 4389 # The z block / halo exist only while the z-tiling controls are shown, see '_add_z_tiling_params'. 4390 if hasattr(self, "tile_z_param"): 4391 settings["tile_z"], settings["halo_z"] = self.tile_z, self.halo_z 4392 4393 return settings 4394 4395 def _z_tiling(self, n_slices): 4396 # The z block / halo for 3d decoder inference. 'tile_z' >= the slice count means no z-tiling 4397 # (the whole volume is decoded in one z block). 4398 z_block = self.tile_z if 0 < self.tile_z < n_slices else n_slices 4399 z_halo = self.halo_z if z_block < n_slices else 0 4400 return z_block, z_halo 4401 4402 def _state_save_path(self, state): 4403 # The state cache is opted into via the embedding settings' 'cache automatic segmentation state' 4404 # checkbox. When on, it persists next to the embeddings, else in-memory only ('_segmenter' cache). 4405 embed_widget = state.widgets.get("embeddings") 4406 return state.embedding_path if getattr(embed_widget, "cache_state", False) else None 4407 4408 def _release_segmenter(self): 4409 # Dropping the reference is not enough: the volumetric prompt generator holds a SAM2 video 4410 # inference state and an ephemeral embedding store, which only 'clear_state' releases. 4411 if self._segmenter is not None: 4412 self._segmenter.clear_state() 4413 self._segmenter = None 4414 self._segmenter_key = None 4415 self._proposals = None 4416 self._proposals_key = None 4417 4418 def _decoder_key(self, state, ndim, z, is_tiled, z_block, z_halo): 4419 # What the decoder prediction depends on. The mode is deliberately absent: the same 4420 # prediction feeds the 'sparse' and 'dense' post-processing and the 'apg' prompt generation. 4421 return (state.data_signature, ndim, z, is_tiled, z_block, z_halo) 4422 4423 def _cached_decoder_state(self, key): 4424 return self._decoder_state if self._decoder_state_key == key else None 4425 4426 def _store_decoder_state(self, key, decoder_state, save_path=None): 4427 self._decoder_state = dict(decoder_state) 4428 self._decoder_state_key = key 4429 self._decoder_state_save_path = save_path 4430 4431 def _persist_decoder_state(self, decoder_state, save_path, state_index, model_type): 4432 if save_path is None or getattr(self, "_decoder_state_save_path", None) == save_path: 4433 return 4434 from micro_sam.precompute_state import save_ais_state 4435 save_ais_state(decoder_state, save_path, state_index=state_index, model_type=model_type) 4436 self._decoder_state_save_path = save_path 4437 4438 def _drop_decoder_state(self): 4439 # Only for a new input or a new model: the prediction is derived from both. 4440 self._decoder_state = None 4441 self._decoder_state_key = None 4442 self._decoder_state_save_path = None 4443 4444 def _run_unisam2(self, state, run_raw, ndim, z, pbar_init=None, pbar_update=None): 4445 from micro_sam.precompute_state import cache_autoseg_state 4446 4447 device = next(state.decoder.parameters()).device 4448 model_type = getattr(state.predictor, "model_type", None) 4449 save_path = self._state_save_path(state) 4450 4451 # All decoder auto-seg cases reuse the precomputed embeddings and run the decoder on them (no 4452 # encoder re-run). The in-plane tiling is taken from the embeddings (tiled embeddings have a 4453 # top-level 'input_size' of None), so only the z entry of 'tile_shape'/'halo' below matters - 4454 # the y, x entries are filler, ignored by the decoder-from-embeddings path. This covers 2d 4455 # and 3d, tiled and untiled. 4456 tile_shape, halo = None, None 4457 z_block, z_halo = None, None 4458 if not self.volumetric or ndim == 3: 4459 # Plain 2d image, or the whole 3d volume: the precomputed embeddings match directly. 4460 image_embeddings = state.image_embeddings 4461 is_tiled = image_embeddings["input_size"] is None 4462 if ndim == 3: # the decoder pass is z-chunked using the auto-seg z block / halo controls. 4463 z_block, z_halo = self._z_tiling(int(run_raw.shape[0])) 4464 tile_shape = (z_block, run_raw.shape[1], run_raw.shape[2]) 4465 halo = (z_halo, 0, 0) 4466 else: 4467 # A single slice of a 3d volume: reuse that slice's features (no re-encode). For untiled 4468 # embeddings, build the slice's 2d embedding. For tiled embeddings, pass the tiled 3d 4469 # embeddings + slice index 'z' and let the segmenter reconstruct each tile's slice. 4470 emb3d = state.image_embeddings 4471 if emb3d is not None and emb3d.get("input_size") is not None: 4472 image_embeddings = { 4473 "features": np.asarray(emb3d["features"][z:z + 1]), 4474 "input_size": emb3d["input_size"], "original_size": emb3d["original_size"], 4475 } 4476 is_tiled = False 4477 else: 4478 image_embeddings, is_tiled = emb3d, True 4479 4480 # The in-memory cache avoids re-running the model when only the post-processing parameters 4481 # change. 'cache_autoseg_state' additionally persists the decoder predictions in the 4482 # embedding Zarr so a later run or session reuses them. The whole volume is 4483 # cached under one key ('state'); a single segmented slice under 'state-{z}'. 4484 cache_key = ( 4485 state.data_signature, "unisam2", ndim, z, tile_shape, halo, z_block, z_halo, 4486 image_embeddings is not None, save_path, 4487 ) 4488 decoder_key = self._decoder_key(state, ndim, z, is_tiled, z_block, z_halo) 4489 if self._segmenter is None or self._segmenter_key != cache_key: 4490 self._release_segmenter() 4491 decoder_state = self._cached_decoder_state(decoder_key) 4492 if decoder_state is None: 4493 self._segmenter = cache_autoseg_state( 4494 "ais", state.decoder, run_raw, image_embeddings, save_path, ndim=ndim, 4495 model_type=model_type, 4496 i=z, state_index=(None if ndim == 3 else z), is_tiled=is_tiled, 4497 tile_shape=tile_shape, halo=halo, device=device, devices=state.inference_devices, 4498 pbar_init=pbar_init, pbar_update=pbar_update, verbose=False, 4499 ) 4500 decoder_state = self._segmenter.get_state() 4501 self._store_decoder_state(decoder_key, decoder_state, save_path=save_path) 4502 else: 4503 from micro_sam.v2.instance_segmentation import get_unisam2_segmentation_generator 4504 self._segmenter = get_unisam2_segmentation_generator( 4505 state.decoder, is_tiled=is_tiled, device=device, inference_device=state.inference_devices, 4506 ) 4507 self._segmenter.set_state(decoder_state) 4508 self._persist_decoder_state( 4509 decoder_state, save_path, state_index=(None if ndim == 3 else z), model_type=model_type, 4510 ) 4511 self._segmenter_key = cache_key 4512 4513 return self._segmenter.generate(mode=self.mode, **self._postproc_kwargs()) 4514 4515 def _run_apg(self, state, run_raw, ndim, z, pbar_init=None, pbar_update=None): 4516 from micro_sam.precompute_state import cache_autoseg_state 4517 from micro_sam.v2.instance_segmentation import get_instance_segmentation_generator 4518 4519 model = getattr(state.predictor, "model", state.predictor) 4520 model_type = getattr(state.predictor, "model_type", None) 4521 device = next(state.decoder.parameters()).device 4522 save_path = self._state_save_path(state) 4523 image_embeddings = state.image_embeddings 4524 is_tiled = image_embeddings is not None and image_embeddings.get("input_size") is None 4525 decoder_embeddings = image_embeddings 4526 if z is not None and not is_tiled: 4527 decoder_embeddings = { 4528 "features": np.asarray(image_embeddings["features"][z:z + 1]), 4529 "input_size": image_embeddings["input_size"], 4530 "original_size": image_embeddings["original_size"], 4531 } 4532 4533 tile_shape, halo = None, None 4534 if is_tiled: 4535 attrs = image_embeddings["features"].attrs 4536 tile_shape = tuple(int(value) for value in attrs["tile_shape"]) 4537 halo = tuple(int(value) for value in attrs["halo"]) 4538 4539 z_block, z_halo = None, None 4540 decoder_tile_shape, decoder_halo = tile_shape, halo 4541 if ndim == 3: 4542 z_block, z_halo = self._z_tiling(int(run_raw.shape[0])) 4543 # The decoder's z chunk goes in front; y, x are the in-plane tiling above, or filler 4544 # (ignored by the decoder-from-embeddings path) when there is none. 4545 decoder_tile_shape = (z_block, *(tile_shape or run_raw.shape[1:3])) 4546 decoder_halo = (z_halo, *(halo or (0, 0))) 4547 4548 cache_key = ( 4549 state.data_signature, "apg", ndim, z, tile_shape, halo, z_block, z_halo, 4550 image_embeddings is not None, save_path, 4551 ) 4552 if self._segmenter is None or self._segmenter_key != cache_key: 4553 self._release_segmenter() 4554 self._segmenter = get_instance_segmentation_generator( 4555 model=model, decoder=state.decoder, is_tiled=is_tiled, segmentation_mode="apg", 4556 device=device, inference_device=state.inference_devices, ndim=ndim, 4557 ) 4558 if is_tiled: 4559 # The blocks use the tiling of the embeddings, so each block reads its tile. 4560 self._segmenter.initialize( 4561 run_raw, ndim=ndim, tile_shape=decoder_tile_shape, halo=decoder_halo, verbose=False, 4562 image_embeddings=image_embeddings, i=z, 4563 ) 4564 else: 4565 decoder_key = self._decoder_key(state, ndim, z, is_tiled, z_block, z_halo) 4566 decoder_state = self._cached_decoder_state(decoder_key) 4567 if decoder_state is None: 4568 decoder_segmenter = cache_autoseg_state( 4569 "ais", state.decoder, run_raw, decoder_embeddings, save_path, ndim=ndim, 4570 model_type=model_type, i=z, state_index=(None if ndim == 3 else z), 4571 is_tiled=False, tile_shape=decoder_tile_shape, halo=decoder_halo, device=device, 4572 devices=state.inference_devices, 4573 pbar_init=pbar_init, pbar_update=pbar_update, verbose=False, 4574 ) 4575 decoder_state = decoder_segmenter.get_state() 4576 self._store_decoder_state(decoder_key, decoder_state, save_path=save_path) 4577 self._persist_decoder_state( 4578 decoder_state, save_path, state_index=(None if ndim == 3 else z), model_type=model_type, 4579 ) 4580 apg_state = dict(decoder_state) 4581 apg_state["image_embeddings"] = image_embeddings 4582 if z is not None: 4583 apg_state["i"] = z 4584 if ndim == 3: 4585 apg_state["volume"] = run_raw 4586 self._segmenter.set_state(apg_state) 4587 self._segmenter_key = cache_key 4588 4589 if is_tiled: 4590 return self._segmenter.generate( 4591 **self._apg_kwargs(ndim), pbar_init=pbar_init, pbar_update=pbar_update, 4592 ) 4593 4594 if ndim == 3: # One pass: the volumetric stages are not separable the way the 2d ones are. 4595 return self._segmenter.generate( 4596 **self._apg_kwargs(ndim), pbar_init=pbar_init, pbar_update=pbar_update, 4597 ) 4598 4599 # 'propose' does the prompting and 'select' only merges, so re-running with a different 4600 # score / overlap / size replays the merge instead of prompting the model again. 4601 propose_kwargs = self._apg_propose_kwargs() 4602 proposals_key = (cache_key, tuple(sorted(propose_kwargs.items()))) 4603 if self._proposals is None or self._proposals_key != proposals_key: 4604 self._proposals = self._segmenter.propose( 4605 **propose_kwargs, pbar_init=pbar_init, pbar_update=pbar_update, 4606 ) 4607 self._proposals_key = proposals_key 4608 if pbar_init is not None: 4609 pbar_init(1, "APG: merging masks") 4610 segmentation = self._segmenter.select(self._proposals, **self._apg_select_kwargs()) 4611 if pbar_update is not None: 4612 pbar_update(1) 4613 return segmentation 4614 4615 def __call__(self): 4616 state = AnnotatorState() 4617 if not self.with_decoder or state.decoder is None: 4618 return _generate_message("error", NO_DECODER_MESSAGE) 4619 if _validate_layers(self._viewer, automatic_segmentation=True): 4620 return 4621 # Every mode reuses the precomputed image embeddings, so they must exist and match 4622 # the current image. If embeddings were reset (e.g. after an image change) this prompts the 4623 # user to recompute them instead of segmenting with stale embeddings. 4624 if _validate_embeddings(self._viewer): 4625 return 4626 4627 # Get the raw image and determine the run dimensionality. 4628 image_name = state.get_image_name(self._viewer) 4629 raw = np.asarray(self._viewer.layers[image_name].data) 4630 4631 apply_to_volume = self.volumetric and getattr(self, "apply_to_volume", False) 4632 z = None 4633 if apply_to_volume: 4634 run_raw, ndim = raw, 3 4635 elif self.volumetric: # segment only the current slice 4636 z = vutil.current_slice(self._viewer, self._viewer.layers[image_name]) 4637 run_raw, ndim = raw[z], 2 4638 else: 4639 run_raw, ndim = raw, 2 4640 4641 if self.mode == "apg": 4642 apg_error = _apg_error(state, self.volumetric, is_tracking=self._is_tracking) 4643 if apg_error is not None: 4644 return _generate_message("error", apg_error) 4645 4646 # Show progress in the napari activity dock: decoder tiles/slices, then APG prompt batches, 4647 # scoring slices or propagation passes. Each stage resets the count and total. 4648 # This tool disables thread workers (see top of module), so the run is 4649 # synchronous. We drive the bar via callbacks the backends call between units and pump the Qt 4650 # event loop with 'processEvents' on each update so it repaints live. It is always closed in 4651 # the 'finally' block. Batched 3d inference forwards completed tile-slice increments from its 4652 # worker threads to this calling thread so napari can repaint them safely. 4653 pbar, pbar_signals = _create_pbar_for_threadworker() 4654 4655 def pbar_init(total, description): 4656 pbar_signals.pbar_reset.emit() 4657 pbar_signals.pbar_total.emit(total) 4658 pbar_signals.pbar_description.emit(description) 4659 QtWidgets.QApplication.processEvents() 4660 4661 def pbar_update(update=1): 4662 pbar_signals.pbar_update.emit(update) 4663 QtWidgets.QApplication.processEvents() 4664 4665 pbar_signals.pbar_description.emit(f"Running automatic segmentation ({self.mode})") 4666 QtWidgets.QApplication.processEvents() 4667 try: 4668 if self.mode == "apg": 4669 seg = self._run_apg(state, run_raw, ndim, z, pbar_init=pbar_init, pbar_update=pbar_update) 4670 else: 4671 seg = self._run_unisam2(state, run_raw, ndim, z, pbar_init=pbar_init, pbar_update=pbar_update) 4672 finally: 4673 pbar_signals.pbar_stop.emit() 4674 4675 if z is None: 4676 self._viewer.layers["auto_segmentation"].data = seg 4677 else: 4678 self._viewer.layers["auto_segmentation"].data[z] = seg 4679 self._viewer.layers["auto_segmentation"].refresh() 4680 _select_layer(self._viewer, "auto_segmentation") 4681 self.segmentation_finished.emit()
Automatic segmentation widget for SAM2 with the APG, sparse and dense modes.
Subclasses set _is_tracking = True to hide the z-tiling controls (tracking segments per frame
in 2d, so z-tiling does not apply).
All modes need a UniSAM2 decoder. Automatic prompt generation (APG) derives point prompts from the decoder predictions and applies them to the interactive branch; it is the default on CUDA and MPS. The sparse mode (AIS) is the CPU default. Sparse and dense modes post-process the decoder predictions directly. Without a decoder there is no automatic segmentation: the run button is disabled until a model that has one is loaded.
Disk-backed caching of the state is opted into via the 'cache automatic segmentation state' checkbox in the embedding settings (read here through the embedding widget); when off, the state is kept in memory only.
Arguments:
- viewer: The napari viewer.
- with_decoder: Whether the loaded model has a UniSAM2 decoder for automatic segmentation.
- volumetric: Whether the data is volumetric (3d).
- parent: The parent Qt widget.
3879 def __init__(self, viewer, with_decoder, volumetric, parent=None): 3880 super().__init__(parent) 3881 self._viewer = viewer 3882 self.with_decoder = with_decoder 3883 self.volumetric = volumetric 3884 # Every mode needs a decoder. APG additionally needs an accelerator for volumetric data and 3885 # for tracking, so it is dropped from the list there - see '_available_modes'. 3886 self.mode = self._default_mode() 3887 self.settings = None 3888 # z block / halo for 3d decoder inference: the volume is decoded in z chunks to bound memory. 3889 # These only matter for volumetric decoder modes. Set 'tile_z' >= the slice count for no z-tiling. 3890 from micro_sam.v2.util import DEFAULT_TILE_Z, DEFAULT_HALO_Z 3891 self.tile_z, self.halo_z = DEFAULT_TILE_Z, DEFAULT_HALO_Z 3892 # Cache of the (initialized) segmentation generator so changing post-processing parameters 3893 # only re-runs 'generate', not the expensive UniSAM2 inference. Keyed by the inputs. 3894 self._segmenter = None 3895 self._segmenter_key = None 3896 # The decoder prediction the generator is built from. It does not depend on the mode, so it 3897 # outlives the generator and is shared by 'sparse', 'dense' and 'apg'. 3898 self._decoder_state = None 3899 self._decoder_state_key = None 3900 self._decoder_state_save_path = None 3901 # The APG proposals, so that changing only the merge parameters skips the prompting. 3902 self._proposals = None 3903 self._proposals_key = None 3904 self._create_widget()
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
4375 def commit_settings(self): 4376 """The parameters of the current automatic segmentation, for the commit history. 4377 4378 Returns: 4379 A json-serializable dict with the mode and the parameters that mode runs with. 4380 """ 4381 settings = {"mode": self.mode} 4382 if self.mode == "apg": 4383 settings.update(self._apg_kwargs(self._run_ndim())) 4384 else: 4385 settings.update(self._postproc_kwargs()) 4386 4387 if self.volumetric: 4388 settings["apply_to_volume"] = bool(getattr(self, "apply_to_volume", False)) 4389 # The z block / halo exist only while the z-tiling controls are shown, see '_add_z_tiling_params'. 4390 if hasattr(self, "tile_z_param"): 4391 settings["tile_z"], settings["halo_z"] = self.tile_z, self.halo_z 4392 4393 return settings
The parameters of the current automatic segmentation, for the commit history.
Returns:
A json-serializable dict with the mode and the parameters that mode runs with.
4684class AutoTrackWidget(AutoSegmentWidget): 4685 _is_tracking = True 4686 _RUN_TOOLTIP = ("autotrack", "run_button") 4687 4688 def _create_widget(self): 4689 # Top row: the 'Track Timeseries' switch on the left, the mode dropdown on the right. 4690 top_row = QtWidgets.QHBoxLayout() 4691 4692 self.apply_to_volume = False 4693 self.apply_to_volume_checkbox = self._add_boolean_param( 4694 "apply_to_volume", 4695 self.apply_to_volume, 4696 title="Track Timeseries", 4697 tooltip=get_tooltip("autotrack", "run_tracking"), 4698 ) 4699 top_row.addWidget(self.apply_to_volume_checkbox) 4700 4701 self.mode_dropdown, mode_layout = self._add_choice_param( 4702 "mode", 4703 self.mode, 4704 list(self._available_modes()), 4705 title="mode:", 4706 update=self._on_mode_changed, 4707 tooltip=get_tooltip("autosegment", "mode"), 4708 ) 4709 # Keep the label at its text width so that the dropdown starts right after it and covers 4710 # the rest of the row. 4711 mode_layout.setStretch(0, 0) 4712 mode_layout.setStretch(1, 1) 4713 top_row.addLayout(mode_layout) 4714 4715 self.layout().addLayout(top_row) 4716 4717 self.settings = self._make_settings_widget() 4718 self.layout().addWidget(self.settings) 4719 4720 # The run button is only active with a decoder, since every mode needs one. 4721 self.run_button = QtWidgets.QPushButton("Automatic Tracking") 4722 self.run_button.clicked.connect(self.__call__) 4723 self.layout().addWidget(self.run_button) 4724 self._update_run_button() 4725 4726 def _empty_tracking_warning(self): 4727 return _generate_message( 4728 "error", 4729 "The automatic tracking result does not contain any objects. " 4730 "Try adjusting the automatic tracking settings.", 4731 ) 4732 4733 def _run_frame_segmentation(self, state, frame, frame_id, pbar_init=None, pbar_update=None): 4734 # Forward the progress callbacks so a frame advances the overall bar per tile (tiled) or by 4735 # one step (untiled). The caller passes a no-op 'pbar_init' so a frame cannot reset the total. 4736 if self.mode == "apg": 4737 return self._run_apg(state, frame, 2, frame_id, pbar_init=pbar_init, pbar_update=pbar_update) 4738 return self._run_unisam2(state, frame, 2, frame_id, pbar_init=pbar_init, pbar_update=pbar_update) 4739 4740 def _n_inplane_tiles(self, state, raw): 4741 # In-plane tiles per frame for the current run (1 if not tiled). The auto-tracking bar 4742 # advances per tile, so its total is this times the number of frames. 4743 from bioimage_cpp.utils import Blocking 4744 4745 # The modes reuse the precomputed embeddings; tiled ones have no top-level input_size. 4746 emb = state.image_embeddings 4747 tile_shape = None 4748 if emb is not None and emb.get("input_size") is None: 4749 tile_shape = tuple(int(s) for s in emb["features"].attrs["tile_shape"]) 4750 if tile_shape is None: 4751 return 1 4752 return Blocking([0, 0], list(raw.shape[1:3]), list(tile_shape)).number_of_blocks 4753 4754 def _track_timeseries(self, state, raw): 4755 segmentation = np.zeros_like(self._viewer.layers["auto_segmentation"].data) 4756 pbar, pbar_signals = _create_pbar_for_threadworker() 4757 offset = 0 4758 4759 def tracking_pbar_init(total, description): 4760 pbar_signals.pbar_total.emit(total) 4761 pbar_signals.pbar_description.emit(description) 4762 QtWidgets.QApplication.processEvents() 4763 4764 def tracking_pbar_update(update=1): 4765 pbar_signals.pbar_update.emit(update) 4766 QtWidgets.QApplication.processEvents() 4767 4768 # Decoder modes share a total over all frames. APG has candidate-dependent stages, 4769 # so reset for each stage and keep the frame number in its description. 4770 def frame_pbar_init(total, description): 4771 # APG reports several stages per frame, whose totals depend on its candidates. 4772 if self.mode == "apg": 4773 pbar_signals.pbar_reset.emit() 4774 tracking_pbar_init(total, f"Frame {frame_id + 1}/{len(raw)} - {description}") 4775 4776 n_tiles = self._n_inplane_tiles(state, raw) 4777 try: 4778 # Decoder modes advance per tile (or once per untiled frame). APG replaces this 4779 # initial total as soon as its first stage starts. 4780 pbar_signals.pbar_total.emit(n_tiles * len(raw)) 4781 QtWidgets.QApplication.processEvents() 4782 for frame_id, frame in enumerate(raw): 4783 pbar_signals.pbar_description.emit( 4784 f"Automatic segmentation ({self.mode}): frame {frame_id + 1}/{len(raw)}" 4785 ) 4786 QtWidgets.QApplication.processEvents() 4787 seg = self._run_frame_segmentation( 4788 state, frame, frame_id, pbar_init=frame_pbar_init, pbar_update=tracking_pbar_update, 4789 ) 4790 seg_max = int(seg.max()) 4791 if seg_max != 0: 4792 seg[seg != 0] += offset 4793 offset += seg_max 4794 segmentation[frame_id] = seg 4795 4796 if offset == 0: 4797 self._viewer.layers["auto_segmentation"].data = segmentation 4798 self._viewer.layers["auto_segmentation"].refresh() 4799 return self._empty_tracking_warning() 4800 4801 pbar_signals.pbar_reset.emit() 4802 segmentation, lineages = track_across_frames( 4803 raw, 4804 segmentation, 4805 verbose=True, 4806 pbar_init=tracking_pbar_init, 4807 pbar_update=tracking_pbar_update, 4808 ) 4809 finally: 4810 pbar_signals.pbar_stop.emit() 4811 4812 state.auto_lineages = lineages 4813 self._viewer.layers["auto_segmentation"].data = segmentation 4814 self._viewer.layers["auto_segmentation"].refresh() 4815 _select_layer(self._viewer, "auto_segmentation") 4816 self.segmentation_finished.emit() 4817 4818 def __call__(self): 4819 state = AnnotatorState() 4820 if not self.with_decoder or state.decoder is None: 4821 return _generate_message("error", NO_DECODER_MESSAGE) 4822 # Tracking prompts the video predictor per frame, so APG needs an accelerator here for a 4823 # single frame just as much as for the whole timeseries. Checked before the single-frame 4824 # delegation below so both paths are covered. 4825 if self.mode == "apg": 4826 apg_error = _apg_error(state, self.volumetric, is_tracking=True) 4827 if apg_error is not None: 4828 return _generate_message("error", apg_error) 4829 4830 if not (self.volumetric and getattr(self, "apply_to_volume", False)): 4831 return super().__call__() 4832 if _validate_layers(self._viewer, automatic_segmentation=True): 4833 return None 4834 if state.committed_lineages: 4835 return _generate_message( 4836 "error", 4837 "Automatic tracking can only be called if you have not committed interactive tracking results yet.", 4838 ) 4839 4840 image_name = state.get_image_name(self._viewer) 4841 raw = np.asarray(self._viewer.layers[image_name].data) 4842 if raw.ndim != 3: 4843 return _generate_message("error", "Automatic tracking expects a 2d timeseries.") 4844 return self._track_timeseries(state, raw)
Automatic segmentation widget for SAM2 with the APG, sparse and dense modes.
Subclasses set _is_tracking = True to hide the z-tiling controls (tracking segments per frame
in 2d, so z-tiling does not apply).
All modes need a UniSAM2 decoder. Automatic prompt generation (APG) derives point prompts from the decoder predictions and applies them to the interactive branch; it is the default on CUDA and MPS. The sparse mode (AIS) is the CPU default. Sparse and dense modes post-process the decoder predictions directly. Without a decoder there is no automatic segmentation: the run button is disabled until a model that has one is loaded.
Disk-backed caching of the state is opted into via the 'cache automatic segmentation state' checkbox in the embedding settings (read here through the embedding widget); when off, the state is kept in memory only.
Arguments:
- viewer: The napari viewer.
- with_decoder: Whether the loaded model has a UniSAM2 decoder for automatic segmentation.
- volumetric: Whether the data is volumetric (3d).
- parent: The parent Qt widget.