micro_sam.sam_annotator.batch_annotator
1import os 2from glob import glob 3from typing import List, Optional, Union, Tuple 4 5import numpy as np 6import imageio.v3 as imageio 7 8import torch 9 10import napari 11 12from qtpy import QtWidgets 13from qtpy.QtCore import QTimer 14 15from .annotator import Annotator 16from . import _widgets as widgets 17from ._state import AnnotatorState 18from ._tooltips import get_tooltip 19from ._titles import get_dock_title 20from ..v2.util import DEFAULT_MODEL, resolve_default_tiling 21from ._batch import BatchAnnotatorTask, load_batch_image, run_batch 22from .util import _sync_embedding_widget, _sync_tiling_widget, _validate_sam2_model_type 23 24# The tasks supported by the unified batch annotator. 25TASKS = ["Segmentation", "Tracking", "Object Classification", "Pixel Classification"] 26 27 28class SegmentationBatchTask(BatchAnnotatorTask): 29 """Batch task for 2d/3d interactive segmentation.""" 30 31 empty_item_message = "Nothing is segmented yet. Do you wish to continue to the next image?" 32 33 def __init__( 34 self, *, ndim, model_type, embedding_path, tile_shape, halo, 35 precompute_autoseg_state, checkpoint_path, device, prefer_decoder, 36 initial_segmentations=None, batch_size=1, 37 ): 38 _validate_sam2_model_type(model_type, "segmentation") 39 self.ndim = ndim 40 self.model_type = model_type 41 self.embedding_path = embedding_path 42 self.tile_shape = tile_shape 43 self.halo = halo 44 self.precompute_autoseg_state = precompute_autoseg_state 45 self.checkpoint_path = checkpoint_path 46 self.device = device 47 self.prefer_decoder = prefer_decoder 48 self.initial_segmentations = initial_segmentations 49 self.batch_size = batch_size 50 self.predictor = None 51 self.decoder = None 52 53 def result_filename(self, entry, index): 54 if self.have_inputs_as_arrays: 55 return f"seg_{index:05}.tif" 56 return os.path.splitext(os.path.basename(entry))[0] + ".tif" 57 58 def precompute(self, images): 59 # The tool computes embeddings lazily per item in start and advance (via 'initialize_predictor', 60 # which loads the model once, then reuses it across items). Here we only 61 # build the per-item embedding paths. Each item is 'None' when no embedding folder is given. 62 if self.embedding_path is None: 63 return [None] * len(images) 64 os.makedirs(self.embedding_path, exist_ok=True) 65 if self.have_inputs_as_arrays: 66 return [os.path.join(self.embedding_path, f"embedding_{i:05}.zarr") for i in range(len(images))] 67 return [ 68 os.path.join(self.embedding_path, os.path.splitext(os.path.basename(p))[0] + ".zarr") for p in images 69 ] 70 71 def _resolve_initial_result(self, entry, index): 72 # Load an existing saved result if present, otherwise an initial segmentation if provided. 73 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 74 if os.path.exists(save_path): 75 return imageio.imread(save_path) 76 if self.initial_segmentations is not None: 77 initial = self.initial_segmentations[index] 78 return initial if isinstance(initial, np.ndarray) else imageio.imread(initial) 79 return None 80 81 def _init_predictor(self, viewer, image, embedding_path): 82 state = AnnotatorState() 83 # Only the first item loads the model and its decoder. The later items reuse them. 84 if self.predictor is not None: 85 kwargs = dict(predictor=self.predictor, decoder=self.decoder, prefer_decoder=False) 86 else: 87 kwargs = dict(prefer_decoder=self.prefer_decoder) 88 # The image is prepared by 'load_batch_image', so a channel axis is always the last one. 89 state.image_shape = image.shape[:self.ndim] 90 # Resolve the tiling per image, since the shapes can differ across the batch. 91 tile_shape, halo = resolve_default_tiling(state.image_shape, self.tile_shape, self.halo, embedding_path) 92 state.initialize_predictor( 93 image, model_type=self.model_type, save_path=embedding_path, halo=halo, tile_shape=tile_shape, 94 ndim=self.ndim, 95 precompute_autoseg_state=self.precompute_autoseg_state, 96 checkpoint_path=self.checkpoint_path, batch_size=self.batch_size, 97 device=self.device, use_cli=True, **kwargs, 98 ) 99 # Capture the loaded model so subsequent items reuse it instead of reloading. 100 self.predictor, self.decoder = state.predictor, state.decoder 101 # Establish the scale for this image (matching the segmentation annotator) so the layers do not 102 # inherit a stale 'image_scale' of a different dimensionality from a previous image / session. 103 state.image_scale = tuple(viewer.layers["image"].scale) 104 return tile_shape, halo 105 106 def start(self, viewer, entry, image, embedding_path, index): 107 viewer.add_image(image, name="image", rgb=image.ndim > self.ndim) 108 tile_shape, halo = self._init_predictor(viewer, image, embedding_path) 109 110 annotator = Annotator(viewer, ndim=self.ndim, reset_state=False) 111 annotator._update_image(segmentation_result=self._resolve_initial_result(entry, index)) 112 113 state = AnnotatorState() 114 viewer.window.add_dock_widget(annotator, name=get_dock_title("batch_segmentation")) 115 _sync_embedding_widget( 116 widget=state.widgets["embeddings"], 117 model_type=self.model_type if self.checkpoint_path is None else state.predictor.model_type, 118 save_path=self.embedding_path, checkpoint_path=self.checkpoint_path, 119 device=self.device, tile_shape=tile_shape, halo=halo, 120 ) 121 return annotator 122 123 def advance(self, viewer, annotator, entry, image, embedding_path, index): 124 # Clear the committed segmentation first to avoid laggy removal of the previous result. 125 viewer.layers["committed_objects"].data = np.zeros_like(viewer.layers["committed_objects"].data) 126 segmentation_result = self._resolve_initial_result(entry, index) 127 viewer.layers["image"].data = image 128 tile_shape, halo = self._init_predictor(viewer, image, embedding_path) 129 _sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo) 130 annotator._update_image(segmentation_result=segmentation_result) 131 132 def has_unsaved_content(self, viewer): 133 return viewer.layers["committed_objects"].data.sum() != 0 134 135 def save_item(self, viewer, entry, index): 136 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 137 imageio.imwrite(save_path, viewer.layers["committed_objects"].data, compression="zlib") 138 139 140def batch_annotator( 141 images: Union[List[Union[os.PathLike, str]], List[np.ndarray]], 142 output_folder: str, 143 *, 144 ndim: Optional[int] = None, 145 model_type: str = DEFAULT_MODEL, 146 embedding_path: Optional[str] = None, 147 initial_segmentations: Optional[Union[List[Union[os.PathLike, str]], List[np.ndarray]]] = None, 148 tile_shape: Optional[Tuple[int, int]] = None, 149 halo: Optional[Tuple[int, int]] = None, 150 viewer: Optional["napari.viewer.Viewer"] = None, 151 return_viewer: bool = False, 152 precompute_autoseg_state: bool = False, 153 checkpoint_path: Optional[str] = None, 154 device: Optional[Union[str, torch.device]] = None, 155 prefer_decoder: bool = True, 156 skip_segmented: bool = True, 157 batch_size: Optional[int] = 1, 158) -> Optional["napari.viewer.Viewer"]: 159 """Run the segmentation annotation tool for a batch of images (2d or 3d). 160 161 Args: 162 images: List of the file paths or list of (set of) slices for the images to be annotated. 163 output_folder: The folder where the segmentation results are saved. 164 ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape. 165 model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'. For the available 166 models, see https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 167 embedding_path: Filepath where to save the embeddings. 168 initial_segmentations: Initial segmentations to be corrected. 169 By default no initial segmentations are loaded. 170 If given, the initial segmentations will be loaded into 'committed_objects'. 171 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 172 already cached embeddings, else use the default tiling for images exceeding the in-plane 173 size threshold, and pass smaller images to Segment Anything without tiling. 174 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 175 If `None`, use the default overlap whenever tiling is active. 176 viewer: The viewer to which the Segment Anything functionality should be added. 177 This enables using a pre-initialized viewer. 178 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 179 By default, does not return the napari viewer. 180 precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder 181 predictions). Requires an embedding path and a model with a decoder; it is ignored for a 182 model without one. This will take more time when precomputing embeddings, but will then 183 make automatic segmentation much faster. By default, set to 'False'. 184 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 185 prefer_decoder: Whether to use decoder based instance segmentation if 186 the model used has an additional decoder for instance segmentation. 187 By default, set to 'True'. 188 batch_size: The number of tiles / slices per model call when computing the embeddings. 189 Only has an effect on a GPU. Pass None to select it per device from the free VRAM 190 (SAM2 only). By default a single tile / slice is used. 191 skip_segmented: Whether existing output files mark images as completed. If True, resume at 192 the first image without an output and skip any later completed images. If False, start 193 at the first image and load existing segmentations into the 'committed_objects' layer. 194 195 Returns: 196 The napari viewer, only returned if `return_viewer=True`. 197 """ 198 if initial_segmentations is not None and len(initial_segmentations) != len(images): 199 raise ValueError( 200 "You passed initial segmentations, but the number of images and segmentations is not the same: " 201 f"{len(images)} != {len(initial_segmentations)}." 202 ) 203 204 have_inputs_as_arrays = isinstance(images[0], np.ndarray) 205 206 # Derive the dimensionality from the first image if not given, and load every image with it. 207 if ndim is None: 208 ndim = load_batch_image(images[0])[1] 209 210 task = SegmentationBatchTask( 211 ndim=ndim, model_type=model_type, embedding_path=embedding_path, 212 tile_shape=tile_shape, halo=halo, 213 precompute_autoseg_state=precompute_autoseg_state, 214 checkpoint_path=checkpoint_path, device=device, prefer_decoder=prefer_decoder, 215 initial_segmentations=initial_segmentations, batch_size=batch_size, 216 ) 217 return run_batch( 218 images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays, 219 viewer=viewer, return_viewer=return_viewer, skip_done=skip_segmented, 220 ) 221 222 223def image_folder_annotator( 224 input_folder: str, 225 output_folder: str, 226 *, 227 ndim: Optional[int] = None, 228 pattern: str = "*", 229 initial_segmentation_folder: Optional[str] = None, 230 initial_segmentation_pattern: str = "*", 231 viewer: Optional["napari.viewer.Viewer"] = None, 232 return_viewer: bool = False, 233 **kwargs 234) -> Optional["napari.viewer.Viewer"]: 235 """Run the segmentation annotation tool for a batch of images (2d or 3d) in a folder. 236 237 Args: 238 input_folder: The folder with the images to be annotated. 239 output_folder: The folder where the segmentation results are saved. 240 ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape. 241 pattern: The glob pattern for loading files from `input_folder`. 242 By default all files will be loaded. 243 initial_segmentation_folder: A folder with initial segmentation results. 244 By default no initial segmentations are loaded. 245 initial_segmentation_pattern: The glob pattern for loading files from `initial_segmentation_folder`. 246 viewer: The viewer to which the Segment Anything functionality should be added. 247 This enables using a pre-initialized viewer. 248 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 249 By default, does not return the napari viewer. 250 kwargs: The keyword arguments for `micro_sam.sam_annotator.batch_annotator.batch_annotator`. 251 252 Returns: 253 The napari viewer, only returned if `return_viewer=True`. 254 """ 255 image_files = sorted(glob(os.path.join(input_folder, pattern))) 256 if initial_segmentation_folder is None: 257 initial_segmentations = None 258 else: 259 initial_segmentations = sorted(glob(os.path.join( 260 initial_segmentation_folder, initial_segmentation_pattern 261 ))) 262 263 return batch_annotator( 264 image_files, output_folder, ndim=ndim, 265 initial_segmentations=initial_segmentations, 266 viewer=viewer, return_viewer=return_viewer, **kwargs 267 ) 268 269 270def _hide_layout_widgets(item): 271 """Recursively hide every widget held by a layout item. 272 273 Used to hide the embedding widget's top image / model row once its model dropdown has been 274 relocated next to the launcher's Task dropdown. 275 """ 276 if item is None: 277 return 278 layout = item.layout() 279 if layout is None: 280 widget = item.widget() 281 if widget is not None: 282 widget.hide() 283 return 284 for i in range(layout.count()): 285 _hide_layout_widgets(layout.itemAt(i)) 286 287 288class BatchAnnotator(widgets._WidgetBase): 289 def __init__(self, viewer: napari.Viewer, parent=None): 290 super().__init__(parent=parent) 291 self._viewer = viewer 292 293 # Compose all of the console's menus inside a single scrollable, bordered container (a 294 # QGroupBox, matching the bordered boxes the annotators wrap their sections in), so it reads 295 # as one panel and scrolls when the (expanded) embedding settings make it taller than the dock. 296 self._content = QtWidgets.QGroupBox() 297 self._content.setLayout(QtWidgets.QVBoxLayout()) 298 299 # Create the UI: options + the embedded model / embedding settings. 300 self._create_options() 301 302 # Add the run button to trigger the embedding computation. 303 self.run_button = QtWidgets.QPushButton("Annotate Images") 304 self.run_button.clicked.connect(self.__call__) 305 self._content.layout().addWidget(self.run_button) 306 307 # Pack the menus to the top: the dock's extra vertical space collapses below the button 308 # instead of being distributed as fixed gaps between the rows. 309 self._content.layout().addStretch() 310 311 scroll = QtWidgets.QScrollArea() 312 scroll.setWidgetResizable(True) 313 scroll.setWidget(self._content) 314 self.layout().addWidget(scroll) 315 316 self._rebuilt_on_show = False 317 318 def showEvent(self, event): 319 # napari 0.9 caps the height of dock widget content at its size hint (napari/napari#9393). 320 size_policy = self.sizePolicy() 321 size_policy_enum = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 322 size_policy.setVerticalPolicy(size_policy_enum.Expanding) 323 self.setSizePolicy(size_policy) 324 325 # The first embedding widget is built before napari styles the console, so its path fields keep 326 # the wider default font and the console opens wider than it is after any task change. Build it 327 # once more here, under the same conditions as a task change, so the width stays the same. 328 super().showEvent(event) 329 if not self._rebuilt_on_show: 330 self._rebuilt_on_show = True 331 self._rebuild_embedding_widget() 332 333 def _create_options(self): 334 self.folder = None 335 self._folder_textbox, layout = self._add_path_param( 336 "folder", self.folder, "directory", 337 title="Input Folder", placeholder="Folder with images ...", 338 tooltip=get_tooltip("batch_annotator", "folder") 339 ) 340 self._content.layout().addLayout(layout) 341 self._folder_label = layout.itemAt(0).widget() 342 343 # File pattern qualifying the input folder: which files form the batch. 344 self.pattern = "*" 345 self._pattern_param, layout = self._add_string_param( 346 "pattern", self.pattern, tooltip=get_tooltip("batch_annotator", "pattern") 347 ) 348 self._content.layout().addLayout(layout) 349 self._pattern_label = layout.itemAt(0).widget() 350 351 # Segmentation folder (object classification only), toggled by the task selector. 352 self.segmentation_folder = None 353 self.segmentation_pattern = "*" 354 self._seg_folder_container = QtWidgets.QWidget() 355 seg_layout = QtWidgets.QVBoxLayout() 356 seg_layout.setContentsMargins(0, 0, 0, 0) 357 _, path_layout = self._add_path_param( 358 "segmentation_folder", self.segmentation_folder, "directory", 359 title="Segmentation Folder", placeholder="Folder with segmentations (optional) ...", 360 tooltip=get_tooltip("batch_annotator", "segmentation_folder"), 361 ) 362 seg_layout.addLayout(path_layout) 363 self._seg_folder_label = path_layout.itemAt(0).widget() 364 self._seg_folder_container.setLayout(seg_layout) 365 self._seg_folder_container.setVisible(False) 366 self._content.layout().addWidget(self._seg_folder_container) 367 368 self.output_folder = None 369 _, layout = self._add_path_param( 370 "output_folder", self.output_folder, "directory", 371 title="Output Folder", placeholder="Folder to save the results ...", 372 tooltip=get_tooltip("batch_annotator", "output_folder") 373 ) 374 self._content.layout().addLayout(layout) 375 self._output_label = layout.itemAt(0).widget() 376 377 # 'Continue Annotation' (segmentation only) gets its own row. Inside the output folder row its 378 # width would widen the whole console whenever the segmentation task is selected. 379 self.continue_annotation = True 380 self.continue_annotation_checkbox = self._add_boolean_param( 381 "continue_annotation", self.continue_annotation, title="Continue Annotation", 382 tooltip=get_tooltip("batch_annotator", "continue_annotation"), 383 ) 384 self._content.layout().addWidget(self.continue_annotation_checkbox) 385 386 # Model dropdown on top, then the Task dropdown below it (stacked). The model dropdown is owned 387 # by the embedded embedding widget and relocated into '_model_row' in '_rebuild_embedding_widget'. 388 self._model_row = QtWidgets.QHBoxLayout() 389 self._content.layout().addLayout(self._model_row) 390 self._model_label = None 391 self._relocated_model_dropdown = None 392 393 self.task = "Segmentation" 394 self.task_dropdown, task_layout = self._add_choice_param( 395 "task", self.task, TASKS, title="Task:", tooltip=get_tooltip("batch_annotator", "task"), 396 ) 397 # Let the dropdown absorb the row's extra width so the 'Task:' label hugs it (otherwise the 398 # label expands and leaves a gap between the text and the dropdown). 399 size_policy = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 400 self.task_dropdown.setSizePolicy(size_policy.Expanding, size_policy.Fixed) 401 self._content.layout().addLayout(task_layout) 402 self._task_label = task_layout.itemAt(0).widget() 403 404 # Embedded model / embedding settings, reusing the annotator's embedding widget so the model 405 # family/size, image-dimensions and tiling controls (and, for the classifier tasks, the 406 # 'Advanced Models' selector) are not duplicated. Swapped to match the selected task. 407 self._embedding_container = QtWidgets.QWidget() 408 self._embedding_container.setLayout(QtWidgets.QVBoxLayout()) 409 self._embedding_container.layout().setContentsMargins(0, 0, 0, 0) 410 self._content.layout().addWidget(self._embedding_container) 411 self._embedding_widget = None 412 self._rebuild_embedding_widget() 413 414 # Swap the embedding widget + toggle the segmentation folder on task change, and re-judge the 415 # default tiling from the first image when the input folder or pattern changes. 416 self.task_dropdown.currentTextChanged.connect(self._on_task_changed) 417 self._folder_textbox.textChanged.connect(self._update_default_tiling) 418 self._pattern_param.textChanged.connect(self._update_default_tiling) 419 420 def _build_embedding_widget(self): 421 # The classifier tasks use the classification embedding widget. Its 'Advanced Models' selector also 422 # offers SAM1. Tracking uses the timeseries widget. Segmentation uses the default widget. 423 if self.task in ("Object Classification", "Pixel Classification"): 424 ew = widgets.ClassificationEmbeddingWidget(ndim_choice=True) 425 elif self.task == "Tracking": 426 ew = widgets.EmbeddingWidget(is_timeseries=True) 427 else: 428 ew = widgets.EmbeddingWidget(ndim_choice=True) 429 # The launcher works on a folder and the harness computes embeddings itself, so the 430 # 'Compute Embeddings' button is not needed. The rebuild hides the image and model row, 431 # after it moves the model dropdown next to the Task dropdown. 432 ew.run_button.hide() 433 return ew 434 435 def _rebuild_embedding_widget(self, *args): 436 # Drop the previous embedding widget and the model row relocated from it. 437 if self._model_label is not None: 438 self._model_label.setParent(None) 439 self._model_label.deleteLater() 440 self._model_label = None 441 if self._relocated_model_dropdown is not None: 442 self._relocated_model_dropdown.setParent(None) 443 self._relocated_model_dropdown.deleteLater() 444 self._relocated_model_dropdown = None 445 if self._embedding_widget is not None: 446 self._embedding_widget.setParent(None) 447 self._embedding_widget.deleteLater() 448 449 self._embedding_widget = self._build_embedding_widget() 450 self._embedding_container.layout().addWidget(self._embedding_widget) 451 452 # Relocate the model-family dropdown into the model row (above Task), then hide the now-empty 453 # image / model row at the top of the embedding widget. 454 self._model_label = QtWidgets.QLabel("Model:") 455 self._relocated_model_dropdown = self._embedding_widget.model_family_dropdown 456 # Expanding so the 'Model:' label hugs the dropdown (matching the Task field). 457 size_policy = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 458 self._relocated_model_dropdown.setSizePolicy(size_policy.Expanding, size_policy.Fixed) 459 self._model_row.addWidget(self._model_label) 460 self._model_row.addWidget(self._relocated_model_dropdown) 461 _hide_layout_widgets(self._embedding_widget.layout().itemAt(0)) 462 463 # Uniform label widths so the input / segmentation / output / pattern fields and the model / 464 # task dropdowns all start at the same x and span the same width. 465 self._align_widths([ 466 self._folder_label, self._pattern_label, self._seg_folder_label, self._output_label, 467 self._task_label, self._model_label, 468 ]) 469 470 self._update_default_tiling() 471 472 def _on_task_changed(self, *args): 473 self.task = self.task_dropdown.currentText() 474 self._seg_folder_container.setVisible(self.task == "Object Classification") 475 self.continue_annotation_checkbox.setVisible(self.task == "Segmentation") 476 self._rebuild_embedding_widget() 477 478 def _update_default_tiling(self, *args): 479 # Judge default tiling from the first image in the batch, mirroring the embedding widget's 480 # per-image auto-tiling (which keys off a selected layer that the launcher does not have). 481 ew = self._embedding_widget 482 if ew is None or not self.folder: 483 return 484 files = sorted(glob(os.path.join(self.folder, self.pattern or "*"))) 485 if not files: 486 return 487 try: 488 shape = imageio.improps(files[0]).shape 489 except Exception: 490 return 491 # Drop a trailing channel axis (RGB/RGBA) for the in-plane size judgement. 492 spatial = shape[:-1] if (len(shape) >= 3 and shape[-1] in (3, 4)) else shape 493 ew._apply_default_tiling_for_shape(spatial) 494 495 def _validate_inputs(self): 496 missing_data = self.folder is None or len(glob(os.path.join(self.folder, self.pattern or "*"))) == 0 497 missing_output = self.output_folder is None 498 if missing_data or missing_output: 499 msg = "" 500 if missing_data: 501 msg += "The input folder is missing or empty. " 502 if missing_output: 503 msg += "The output folder is missing." 504 return widgets._generate_message("error", msg) 505 506 # For object classification with provided segmentations, the counts must match. 507 if self.task == "Object Classification" and self.segmentation_folder: 508 n_img = len(glob(os.path.join(self.folder, self.pattern or "*"))) 509 n_seg = len(glob(os.path.join(self.segmentation_folder, self.segmentation_pattern))) 510 if n_img != n_seg: 511 return widgets._generate_message( 512 "error", f"The number of images ({n_img}) and segmentations ({n_seg}) does not match." 513 ) 514 return False 515 516 def _embedding_paths_for(self, image_files): 517 # Per-item embedding zarr paths under the chosen folder (the batch classification functions 518 # take an explicit list); 'None' when no embedding folder is set. 519 save_path = self._embedding_widget.embeddings_save_path 520 if not save_path: 521 return None 522 os.makedirs(save_path, exist_ok=True) 523 return [ 524 os.path.join(save_path, os.path.splitext(os.path.basename(f))[0] + ".zarr") for f in image_files 525 ] 526 527 def __call__(self, skip_validate=False): 528 ew = self._embedding_widget 529 ew._validate_model_type_and_custom_weights() 530 531 if not skip_validate and self._validate_inputs(): 532 return 533 534 # Only forward tiling params when tiling is enabled (the tile/halo defaults are nonzero even 535 # when tiling is 'no'). 'ndim' comes from the image-dimensions dropdown (None = auto-detect). 536 if ew.tiling == "yes": 537 tile_shape, halo = widgets._process_tiling_inputs(ew.tile_x, ew.tile_y, ew.halo_x, ew.halo_y) 538 else: 539 tile_shape, halo = None, None 540 ndim = ew._ndim_override() 541 542 common = dict( 543 model_type=ew.model_type, tile_shape=tile_shape, halo=halo, 544 checkpoint_path=ew.custom_weights, device=ew.device, batch_size=ew._effective_batch_size(), 545 viewer=self._viewer, return_viewer=True, 546 ) 547 548 if self.task == "Segmentation": 549 launched_viewer = image_folder_annotator( 550 input_folder=self.folder, output_folder=self.output_folder, ndim=ndim, 551 pattern=self.pattern or "*", embedding_path=ew.embeddings_save_path, 552 skip_segmented=bool(self.continue_annotation), **common, 553 ) 554 else: 555 image_files = sorted(glob(os.path.join(self.folder, self.pattern or "*"))) 556 if self.task == "Tracking": 557 from .annotator_tracking import batch_tracking_annotator 558 launched_viewer = batch_tracking_annotator( 559 image_files, self.output_folder, embedding_path=ew.embeddings_save_path, **common, 560 ) 561 else: 562 embedding_paths = self._embedding_paths_for(image_files) 563 if self.task == "Pixel Classification": 564 from .pixel_classifier import batch_pixel_classifier 565 launched_viewer = batch_pixel_classifier( 566 image_files, self.output_folder, embedding_paths=embedding_paths, ndim=ndim, **common, 567 ) 568 else: 569 # Object Classification: load the per-image segmentations if a folder is given. 570 from .object_classifier import batch_object_classifier 571 seg_files = None 572 if self.segmentation_folder: 573 seg_files = sorted(glob(os.path.join(self.segmentation_folder, self.segmentation_pattern))) 574 launched_viewer = batch_object_classifier( 575 image_files, seg_files, self.output_folder, 576 embedding_paths=embedding_paths, ndim=ndim, **common, 577 ) 578 579 # A batch function returns None when all results already exist and continuing is enabled. 580 # Keep this launcher available so the user can restart for review or choose another output. 581 if launched_viewer is None: 582 message = "All images have already been annotated. " 583 if self.task == "Segmentation": 584 message += ( 585 "To review or edit them, uncheck 'Continue Annotation' and start the batch annotator again, " 586 "or choose a different output folder." 587 ) 588 else: 589 message += "Choose a different output folder to start another batch." 590 widgets._generate_message("info", message) 591 return 592 593 # The console has done its job (task + settings are locked in for this session); remove it so 594 # the annotator has the screen to itself. 595 self._dismiss() 596 597 def _dismiss(self): 598 # Remove the console dock after a successful launch. Deferred so it runs after this click 599 # handler returns (deleting the widget mid-handler is unsafe); a no-op if the console was not 600 # added as a dock (e.g. in tests that construct it directly). 601 def _remove(): 602 try: 603 self._viewer.window.remove_dock_widget(self) 604 except Exception: 605 pass 606 QTimer.singleShot(0, _remove)
29class SegmentationBatchTask(BatchAnnotatorTask): 30 """Batch task for 2d/3d interactive segmentation.""" 31 32 empty_item_message = "Nothing is segmented yet. Do you wish to continue to the next image?" 33 34 def __init__( 35 self, *, ndim, model_type, embedding_path, tile_shape, halo, 36 precompute_autoseg_state, checkpoint_path, device, prefer_decoder, 37 initial_segmentations=None, batch_size=1, 38 ): 39 _validate_sam2_model_type(model_type, "segmentation") 40 self.ndim = ndim 41 self.model_type = model_type 42 self.embedding_path = embedding_path 43 self.tile_shape = tile_shape 44 self.halo = halo 45 self.precompute_autoseg_state = precompute_autoseg_state 46 self.checkpoint_path = checkpoint_path 47 self.device = device 48 self.prefer_decoder = prefer_decoder 49 self.initial_segmentations = initial_segmentations 50 self.batch_size = batch_size 51 self.predictor = None 52 self.decoder = None 53 54 def result_filename(self, entry, index): 55 if self.have_inputs_as_arrays: 56 return f"seg_{index:05}.tif" 57 return os.path.splitext(os.path.basename(entry))[0] + ".tif" 58 59 def precompute(self, images): 60 # The tool computes embeddings lazily per item in start and advance (via 'initialize_predictor', 61 # which loads the model once, then reuses it across items). Here we only 62 # build the per-item embedding paths. Each item is 'None' when no embedding folder is given. 63 if self.embedding_path is None: 64 return [None] * len(images) 65 os.makedirs(self.embedding_path, exist_ok=True) 66 if self.have_inputs_as_arrays: 67 return [os.path.join(self.embedding_path, f"embedding_{i:05}.zarr") for i in range(len(images))] 68 return [ 69 os.path.join(self.embedding_path, os.path.splitext(os.path.basename(p))[0] + ".zarr") for p in images 70 ] 71 72 def _resolve_initial_result(self, entry, index): 73 # Load an existing saved result if present, otherwise an initial segmentation if provided. 74 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 75 if os.path.exists(save_path): 76 return imageio.imread(save_path) 77 if self.initial_segmentations is not None: 78 initial = self.initial_segmentations[index] 79 return initial if isinstance(initial, np.ndarray) else imageio.imread(initial) 80 return None 81 82 def _init_predictor(self, viewer, image, embedding_path): 83 state = AnnotatorState() 84 # Only the first item loads the model and its decoder. The later items reuse them. 85 if self.predictor is not None: 86 kwargs = dict(predictor=self.predictor, decoder=self.decoder, prefer_decoder=False) 87 else: 88 kwargs = dict(prefer_decoder=self.prefer_decoder) 89 # The image is prepared by 'load_batch_image', so a channel axis is always the last one. 90 state.image_shape = image.shape[:self.ndim] 91 # Resolve the tiling per image, since the shapes can differ across the batch. 92 tile_shape, halo = resolve_default_tiling(state.image_shape, self.tile_shape, self.halo, embedding_path) 93 state.initialize_predictor( 94 image, model_type=self.model_type, save_path=embedding_path, halo=halo, tile_shape=tile_shape, 95 ndim=self.ndim, 96 precompute_autoseg_state=self.precompute_autoseg_state, 97 checkpoint_path=self.checkpoint_path, batch_size=self.batch_size, 98 device=self.device, use_cli=True, **kwargs, 99 ) 100 # Capture the loaded model so subsequent items reuse it instead of reloading. 101 self.predictor, self.decoder = state.predictor, state.decoder 102 # Establish the scale for this image (matching the segmentation annotator) so the layers do not 103 # inherit a stale 'image_scale' of a different dimensionality from a previous image / session. 104 state.image_scale = tuple(viewer.layers["image"].scale) 105 return tile_shape, halo 106 107 def start(self, viewer, entry, image, embedding_path, index): 108 viewer.add_image(image, name="image", rgb=image.ndim > self.ndim) 109 tile_shape, halo = self._init_predictor(viewer, image, embedding_path) 110 111 annotator = Annotator(viewer, ndim=self.ndim, reset_state=False) 112 annotator._update_image(segmentation_result=self._resolve_initial_result(entry, index)) 113 114 state = AnnotatorState() 115 viewer.window.add_dock_widget(annotator, name=get_dock_title("batch_segmentation")) 116 _sync_embedding_widget( 117 widget=state.widgets["embeddings"], 118 model_type=self.model_type if self.checkpoint_path is None else state.predictor.model_type, 119 save_path=self.embedding_path, checkpoint_path=self.checkpoint_path, 120 device=self.device, tile_shape=tile_shape, halo=halo, 121 ) 122 return annotator 123 124 def advance(self, viewer, annotator, entry, image, embedding_path, index): 125 # Clear the committed segmentation first to avoid laggy removal of the previous result. 126 viewer.layers["committed_objects"].data = np.zeros_like(viewer.layers["committed_objects"].data) 127 segmentation_result = self._resolve_initial_result(entry, index) 128 viewer.layers["image"].data = image 129 tile_shape, halo = self._init_predictor(viewer, image, embedding_path) 130 _sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo) 131 annotator._update_image(segmentation_result=segmentation_result) 132 133 def has_unsaved_content(self, viewer): 134 return viewer.layers["committed_objects"].data.sum() != 0 135 136 def save_item(self, viewer, entry, index): 137 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 138 imageio.imwrite(save_path, viewer.layers["committed_objects"].data, compression="zlib")
Batch task for 2d/3d interactive segmentation.
34 def __init__( 35 self, *, ndim, model_type, embedding_path, tile_shape, halo, 36 precompute_autoseg_state, checkpoint_path, device, prefer_decoder, 37 initial_segmentations=None, batch_size=1, 38 ): 39 _validate_sam2_model_type(model_type, "segmentation") 40 self.ndim = ndim 41 self.model_type = model_type 42 self.embedding_path = embedding_path 43 self.tile_shape = tile_shape 44 self.halo = halo 45 self.precompute_autoseg_state = precompute_autoseg_state 46 self.checkpoint_path = checkpoint_path 47 self.device = device 48 self.prefer_decoder = prefer_decoder 49 self.initial_segmentations = initial_segmentations 50 self.batch_size = batch_size 51 self.predictor = None 52 self.decoder = None
54 def result_filename(self, entry, index): 55 if self.have_inputs_as_arrays: 56 return f"seg_{index:05}.tif" 57 return os.path.splitext(os.path.basename(entry))[0] + ".tif"
Return the filename (relative to output_folder) of this item's saved result.
Used to skip items that are already done. entry is the raw batch entry
(an array or a file path), index its position in the batch.
59 def precompute(self, images): 60 # The tool computes embeddings lazily per item in start and advance (via 'initialize_predictor', 61 # which loads the model once, then reuses it across items). Here we only 62 # build the per-item embedding paths. Each item is 'None' when no embedding folder is given. 63 if self.embedding_path is None: 64 return [None] * len(images) 65 os.makedirs(self.embedding_path, exist_ok=True) 66 if self.have_inputs_as_arrays: 67 return [os.path.join(self.embedding_path, f"embedding_{i:05}.zarr") for i in range(len(images))] 68 return [ 69 os.path.join(self.embedding_path, os.path.splitext(os.path.basename(p))[0] + ".zarr") for p in images 70 ]
Prepare the shared model and per-item embeddings.
Returns a list with one embedding path (or None) per image, aligned to images.
107 def start(self, viewer, entry, image, embedding_path, index): 108 viewer.add_image(image, name="image", rgb=image.ndim > self.ndim) 109 tile_shape, halo = self._init_predictor(viewer, image, embedding_path) 110 111 annotator = Annotator(viewer, ndim=self.ndim, reset_state=False) 112 annotator._update_image(segmentation_result=self._resolve_initial_result(entry, index)) 113 114 state = AnnotatorState() 115 viewer.window.add_dock_widget(annotator, name=get_dock_title("batch_segmentation")) 116 _sync_embedding_widget( 117 widget=state.widgets["embeddings"], 118 model_type=self.model_type if self.checkpoint_path is None else state.predictor.model_type, 119 save_path=self.embedding_path, checkpoint_path=self.checkpoint_path, 120 device=self.device, tile_shape=tile_shape, halo=halo, 121 ) 122 return annotator
Initialize the predictor/state for the first item, dock the annotator and return it.
124 def advance(self, viewer, annotator, entry, image, embedding_path, index): 125 # Clear the committed segmentation first to avoid laggy removal of the previous result. 126 viewer.layers["committed_objects"].data = np.zeros_like(viewer.layers["committed_objects"].data) 127 segmentation_result = self._resolve_initial_result(entry, index) 128 viewer.layers["image"].data = image 129 tile_shape, halo = self._init_predictor(viewer, image, embedding_path) 130 _sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo) 131 annotator._update_image(segmentation_result=segmentation_result)
Load a subsequent item into the existing viewer and annotator.
133 def has_unsaved_content(self, viewer): 134 return viewer.layers["committed_objects"].data.sum() != 0
Whether the user produced anything worth saving for the current item.
136 def save_item(self, viewer, entry, index): 137 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 138 imageio.imwrite(save_path, viewer.layers["committed_objects"].data, compression="zlib")
Persist the current item's result into output_folder.
141def batch_annotator( 142 images: Union[List[Union[os.PathLike, str]], List[np.ndarray]], 143 output_folder: str, 144 *, 145 ndim: Optional[int] = None, 146 model_type: str = DEFAULT_MODEL, 147 embedding_path: Optional[str] = None, 148 initial_segmentations: Optional[Union[List[Union[os.PathLike, str]], List[np.ndarray]]] = None, 149 tile_shape: Optional[Tuple[int, int]] = None, 150 halo: Optional[Tuple[int, int]] = None, 151 viewer: Optional["napari.viewer.Viewer"] = None, 152 return_viewer: bool = False, 153 precompute_autoseg_state: bool = False, 154 checkpoint_path: Optional[str] = None, 155 device: Optional[Union[str, torch.device]] = None, 156 prefer_decoder: bool = True, 157 skip_segmented: bool = True, 158 batch_size: Optional[int] = 1, 159) -> Optional["napari.viewer.Viewer"]: 160 """Run the segmentation annotation tool for a batch of images (2d or 3d). 161 162 Args: 163 images: List of the file paths or list of (set of) slices for the images to be annotated. 164 output_folder: The folder where the segmentation results are saved. 165 ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape. 166 model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'. For the available 167 models, see https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models. 168 embedding_path: Filepath where to save the embeddings. 169 initial_segmentations: Initial segmentations to be corrected. 170 By default no initial segmentations are loaded. 171 If given, the initial segmentations will be loaded into 'committed_objects'. 172 tile_shape: Shape of tiles for tiled embedding prediction. If `None`, reuse the tiling of 173 already cached embeddings, else use the default tiling for images exceeding the in-plane 174 size threshold, and pass smaller images to Segment Anything without tiling. 175 halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders. 176 If `None`, use the default overlap whenever tiling is active. 177 viewer: The viewer to which the Segment Anything functionality should be added. 178 This enables using a pre-initialized viewer. 179 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 180 By default, does not return the napari viewer. 181 precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder 182 predictions). Requires an embedding path and a model with a decoder; it is ignored for a 183 model without one. This will take more time when precomputing embeddings, but will then 184 make automatic segmentation much faster. By default, set to 'False'. 185 checkpoint_path: Path to a custom checkpoint from which to load the SAM model. 186 prefer_decoder: Whether to use decoder based instance segmentation if 187 the model used has an additional decoder for instance segmentation. 188 By default, set to 'True'. 189 batch_size: The number of tiles / slices per model call when computing the embeddings. 190 Only has an effect on a GPU. Pass None to select it per device from the free VRAM 191 (SAM2 only). By default a single tile / slice is used. 192 skip_segmented: Whether existing output files mark images as completed. If True, resume at 193 the first image without an output and skip any later completed images. If False, start 194 at the first image and load existing segmentations into the 'committed_objects' layer. 195 196 Returns: 197 The napari viewer, only returned if `return_viewer=True`. 198 """ 199 if initial_segmentations is not None and len(initial_segmentations) != len(images): 200 raise ValueError( 201 "You passed initial segmentations, but the number of images and segmentations is not the same: " 202 f"{len(images)} != {len(initial_segmentations)}." 203 ) 204 205 have_inputs_as_arrays = isinstance(images[0], np.ndarray) 206 207 # Derive the dimensionality from the first image if not given, and load every image with it. 208 if ndim is None: 209 ndim = load_batch_image(images[0])[1] 210 211 task = SegmentationBatchTask( 212 ndim=ndim, model_type=model_type, embedding_path=embedding_path, 213 tile_shape=tile_shape, halo=halo, 214 precompute_autoseg_state=precompute_autoseg_state, 215 checkpoint_path=checkpoint_path, device=device, prefer_decoder=prefer_decoder, 216 initial_segmentations=initial_segmentations, batch_size=batch_size, 217 ) 218 return run_batch( 219 images, output_folder, task, have_inputs_as_arrays=have_inputs_as_arrays, 220 viewer=viewer, return_viewer=return_viewer, skip_done=skip_segmented, 221 )
Run the segmentation annotation tool for a batch of images (2d or 3d).
Arguments:
- images: List of the file paths or list of (set of) slices for the images to be annotated.
- output_folder: The folder where the segmentation results are saved.
- ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape.
- model_type: The Segment Anything 2 model to use. The name must start with 'hvit_'. For the available models, see https://computational-cell-analytics.github.io/micro-sam/micro_sam.html#finetuned-models.
- embedding_path: Filepath where to save the embeddings.
- initial_segmentations: Initial segmentations to be corrected. By default no initial segmentations are loaded. If given, the initial segmentations will be loaded into 'committed_objects'.
- tile_shape: Shape of tiles for tiled embedding prediction. If
None, reuse the tiling of already cached embeddings, else use the default tiling for images exceeding the in-plane size threshold, and pass smaller images to Segment Anything without tiling. - halo: Shape of the overlap between tiles, which is needed to segment objects on tile borders.
If
None, use the default overlap whenever tiling is active. - viewer: The viewer to which the Segment Anything functionality should be added. This enables using a pre-initialized viewer.
- return_viewer: Whether to return the napari viewer to further modify it before starting the tool. By default, does not return the napari viewer.
- precompute_autoseg_state: Whether to precompute the automatic segmentation state (the decoder predictions). Requires an embedding path and a model with a decoder; it is ignored for a model without one. This will take more time when precomputing embeddings, but will then make automatic segmentation much faster. By default, set to 'False'.
- checkpoint_path: Path to a custom checkpoint from which to load the SAM model.
- prefer_decoder: Whether to use decoder based instance segmentation if the model used has an additional decoder for instance segmentation. By default, set to 'True'.
- batch_size: The number of tiles / slices per model call when computing the embeddings. Only has an effect on a GPU. Pass None to select it per device from the free VRAM (SAM2 only). By default a single tile / slice is used.
- skip_segmented: Whether existing output files mark images as completed. If True, resume at the first image without an output and skip any later completed images. If False, start at the first image and load existing segmentations into the 'committed_objects' layer.
Returns:
The napari viewer, only returned if
return_viewer=True.
224def image_folder_annotator( 225 input_folder: str, 226 output_folder: str, 227 *, 228 ndim: Optional[int] = None, 229 pattern: str = "*", 230 initial_segmentation_folder: Optional[str] = None, 231 initial_segmentation_pattern: str = "*", 232 viewer: Optional["napari.viewer.Viewer"] = None, 233 return_viewer: bool = False, 234 **kwargs 235) -> Optional["napari.viewer.Viewer"]: 236 """Run the segmentation annotation tool for a batch of images (2d or 3d) in a folder. 237 238 Args: 239 input_folder: The folder with the images to be annotated. 240 output_folder: The folder where the segmentation results are saved. 241 ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape. 242 pattern: The glob pattern for loading files from `input_folder`. 243 By default all files will be loaded. 244 initial_segmentation_folder: A folder with initial segmentation results. 245 By default no initial segmentations are loaded. 246 initial_segmentation_pattern: The glob pattern for loading files from `initial_segmentation_folder`. 247 viewer: The viewer to which the Segment Anything functionality should be added. 248 This enables using a pre-initialized viewer. 249 return_viewer: Whether to return the napari viewer to further modify it before starting the tool. 250 By default, does not return the napari viewer. 251 kwargs: The keyword arguments for `micro_sam.sam_annotator.batch_annotator.batch_annotator`. 252 253 Returns: 254 The napari viewer, only returned if `return_viewer=True`. 255 """ 256 image_files = sorted(glob(os.path.join(input_folder, pattern))) 257 if initial_segmentation_folder is None: 258 initial_segmentations = None 259 else: 260 initial_segmentations = sorted(glob(os.path.join( 261 initial_segmentation_folder, initial_segmentation_pattern 262 ))) 263 264 return batch_annotator( 265 image_files, output_folder, ndim=ndim, 266 initial_segmentations=initial_segmentations, 267 viewer=viewer, return_viewer=return_viewer, **kwargs 268 )
Run the segmentation annotation tool for a batch of images (2d or 3d) in a folder.
Arguments:
- input_folder: The folder with the images to be annotated.
- output_folder: The folder where the segmentation results are saved.
- ndim: The number of spatial dimensions (2 or 3). If None, auto-detected from image shape.
- pattern: The glob pattern for loading files from
input_folder. By default all files will be loaded. - initial_segmentation_folder: A folder with initial segmentation results. By default no initial segmentations are loaded.
- initial_segmentation_pattern: The glob pattern for loading files from
initial_segmentation_folder. - viewer: The viewer to which the Segment Anything functionality should be added. This enables using a pre-initialized viewer.
- return_viewer: Whether to return the napari viewer to further modify it before starting the tool. By default, does not return the napari viewer.
- kwargs: The keyword arguments for
micro_sam.sam_annotator.batch_annotator.batch_annotator.
Returns:
The napari viewer, only returned if
return_viewer=True.
289class BatchAnnotator(widgets._WidgetBase): 290 def __init__(self, viewer: napari.Viewer, parent=None): 291 super().__init__(parent=parent) 292 self._viewer = viewer 293 294 # Compose all of the console's menus inside a single scrollable, bordered container (a 295 # QGroupBox, matching the bordered boxes the annotators wrap their sections in), so it reads 296 # as one panel and scrolls when the (expanded) embedding settings make it taller than the dock. 297 self._content = QtWidgets.QGroupBox() 298 self._content.setLayout(QtWidgets.QVBoxLayout()) 299 300 # Create the UI: options + the embedded model / embedding settings. 301 self._create_options() 302 303 # Add the run button to trigger the embedding computation. 304 self.run_button = QtWidgets.QPushButton("Annotate Images") 305 self.run_button.clicked.connect(self.__call__) 306 self._content.layout().addWidget(self.run_button) 307 308 # Pack the menus to the top: the dock's extra vertical space collapses below the button 309 # instead of being distributed as fixed gaps between the rows. 310 self._content.layout().addStretch() 311 312 scroll = QtWidgets.QScrollArea() 313 scroll.setWidgetResizable(True) 314 scroll.setWidget(self._content) 315 self.layout().addWidget(scroll) 316 317 self._rebuilt_on_show = False 318 319 def showEvent(self, event): 320 # napari 0.9 caps the height of dock widget content at its size hint (napari/napari#9393). 321 size_policy = self.sizePolicy() 322 size_policy_enum = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 323 size_policy.setVerticalPolicy(size_policy_enum.Expanding) 324 self.setSizePolicy(size_policy) 325 326 # The first embedding widget is built before napari styles the console, so its path fields keep 327 # the wider default font and the console opens wider than it is after any task change. Build it 328 # once more here, under the same conditions as a task change, so the width stays the same. 329 super().showEvent(event) 330 if not self._rebuilt_on_show: 331 self._rebuilt_on_show = True 332 self._rebuild_embedding_widget() 333 334 def _create_options(self): 335 self.folder = None 336 self._folder_textbox, layout = self._add_path_param( 337 "folder", self.folder, "directory", 338 title="Input Folder", placeholder="Folder with images ...", 339 tooltip=get_tooltip("batch_annotator", "folder") 340 ) 341 self._content.layout().addLayout(layout) 342 self._folder_label = layout.itemAt(0).widget() 343 344 # File pattern qualifying the input folder: which files form the batch. 345 self.pattern = "*" 346 self._pattern_param, layout = self._add_string_param( 347 "pattern", self.pattern, tooltip=get_tooltip("batch_annotator", "pattern") 348 ) 349 self._content.layout().addLayout(layout) 350 self._pattern_label = layout.itemAt(0).widget() 351 352 # Segmentation folder (object classification only), toggled by the task selector. 353 self.segmentation_folder = None 354 self.segmentation_pattern = "*" 355 self._seg_folder_container = QtWidgets.QWidget() 356 seg_layout = QtWidgets.QVBoxLayout() 357 seg_layout.setContentsMargins(0, 0, 0, 0) 358 _, path_layout = self._add_path_param( 359 "segmentation_folder", self.segmentation_folder, "directory", 360 title="Segmentation Folder", placeholder="Folder with segmentations (optional) ...", 361 tooltip=get_tooltip("batch_annotator", "segmentation_folder"), 362 ) 363 seg_layout.addLayout(path_layout) 364 self._seg_folder_label = path_layout.itemAt(0).widget() 365 self._seg_folder_container.setLayout(seg_layout) 366 self._seg_folder_container.setVisible(False) 367 self._content.layout().addWidget(self._seg_folder_container) 368 369 self.output_folder = None 370 _, layout = self._add_path_param( 371 "output_folder", self.output_folder, "directory", 372 title="Output Folder", placeholder="Folder to save the results ...", 373 tooltip=get_tooltip("batch_annotator", "output_folder") 374 ) 375 self._content.layout().addLayout(layout) 376 self._output_label = layout.itemAt(0).widget() 377 378 # 'Continue Annotation' (segmentation only) gets its own row. Inside the output folder row its 379 # width would widen the whole console whenever the segmentation task is selected. 380 self.continue_annotation = True 381 self.continue_annotation_checkbox = self._add_boolean_param( 382 "continue_annotation", self.continue_annotation, title="Continue Annotation", 383 tooltip=get_tooltip("batch_annotator", "continue_annotation"), 384 ) 385 self._content.layout().addWidget(self.continue_annotation_checkbox) 386 387 # Model dropdown on top, then the Task dropdown below it (stacked). The model dropdown is owned 388 # by the embedded embedding widget and relocated into '_model_row' in '_rebuild_embedding_widget'. 389 self._model_row = QtWidgets.QHBoxLayout() 390 self._content.layout().addLayout(self._model_row) 391 self._model_label = None 392 self._relocated_model_dropdown = None 393 394 self.task = "Segmentation" 395 self.task_dropdown, task_layout = self._add_choice_param( 396 "task", self.task, TASKS, title="Task:", tooltip=get_tooltip("batch_annotator", "task"), 397 ) 398 # Let the dropdown absorb the row's extra width so the 'Task:' label hugs it (otherwise the 399 # label expands and leaves a gap between the text and the dropdown). 400 size_policy = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 401 self.task_dropdown.setSizePolicy(size_policy.Expanding, size_policy.Fixed) 402 self._content.layout().addLayout(task_layout) 403 self._task_label = task_layout.itemAt(0).widget() 404 405 # Embedded model / embedding settings, reusing the annotator's embedding widget so the model 406 # family/size, image-dimensions and tiling controls (and, for the classifier tasks, the 407 # 'Advanced Models' selector) are not duplicated. Swapped to match the selected task. 408 self._embedding_container = QtWidgets.QWidget() 409 self._embedding_container.setLayout(QtWidgets.QVBoxLayout()) 410 self._embedding_container.layout().setContentsMargins(0, 0, 0, 0) 411 self._content.layout().addWidget(self._embedding_container) 412 self._embedding_widget = None 413 self._rebuild_embedding_widget() 414 415 # Swap the embedding widget + toggle the segmentation folder on task change, and re-judge the 416 # default tiling from the first image when the input folder or pattern changes. 417 self.task_dropdown.currentTextChanged.connect(self._on_task_changed) 418 self._folder_textbox.textChanged.connect(self._update_default_tiling) 419 self._pattern_param.textChanged.connect(self._update_default_tiling) 420 421 def _build_embedding_widget(self): 422 # The classifier tasks use the classification embedding widget. Its 'Advanced Models' selector also 423 # offers SAM1. Tracking uses the timeseries widget. Segmentation uses the default widget. 424 if self.task in ("Object Classification", "Pixel Classification"): 425 ew = widgets.ClassificationEmbeddingWidget(ndim_choice=True) 426 elif self.task == "Tracking": 427 ew = widgets.EmbeddingWidget(is_timeseries=True) 428 else: 429 ew = widgets.EmbeddingWidget(ndim_choice=True) 430 # The launcher works on a folder and the harness computes embeddings itself, so the 431 # 'Compute Embeddings' button is not needed. The rebuild hides the image and model row, 432 # after it moves the model dropdown next to the Task dropdown. 433 ew.run_button.hide() 434 return ew 435 436 def _rebuild_embedding_widget(self, *args): 437 # Drop the previous embedding widget and the model row relocated from it. 438 if self._model_label is not None: 439 self._model_label.setParent(None) 440 self._model_label.deleteLater() 441 self._model_label = None 442 if self._relocated_model_dropdown is not None: 443 self._relocated_model_dropdown.setParent(None) 444 self._relocated_model_dropdown.deleteLater() 445 self._relocated_model_dropdown = None 446 if self._embedding_widget is not None: 447 self._embedding_widget.setParent(None) 448 self._embedding_widget.deleteLater() 449 450 self._embedding_widget = self._build_embedding_widget() 451 self._embedding_container.layout().addWidget(self._embedding_widget) 452 453 # Relocate the model-family dropdown into the model row (above Task), then hide the now-empty 454 # image / model row at the top of the embedding widget. 455 self._model_label = QtWidgets.QLabel("Model:") 456 self._relocated_model_dropdown = self._embedding_widget.model_family_dropdown 457 # Expanding so the 'Model:' label hugs the dropdown (matching the Task field). 458 size_policy = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 459 self._relocated_model_dropdown.setSizePolicy(size_policy.Expanding, size_policy.Fixed) 460 self._model_row.addWidget(self._model_label) 461 self._model_row.addWidget(self._relocated_model_dropdown) 462 _hide_layout_widgets(self._embedding_widget.layout().itemAt(0)) 463 464 # Uniform label widths so the input / segmentation / output / pattern fields and the model / 465 # task dropdowns all start at the same x and span the same width. 466 self._align_widths([ 467 self._folder_label, self._pattern_label, self._seg_folder_label, self._output_label, 468 self._task_label, self._model_label, 469 ]) 470 471 self._update_default_tiling() 472 473 def _on_task_changed(self, *args): 474 self.task = self.task_dropdown.currentText() 475 self._seg_folder_container.setVisible(self.task == "Object Classification") 476 self.continue_annotation_checkbox.setVisible(self.task == "Segmentation") 477 self._rebuild_embedding_widget() 478 479 def _update_default_tiling(self, *args): 480 # Judge default tiling from the first image in the batch, mirroring the embedding widget's 481 # per-image auto-tiling (which keys off a selected layer that the launcher does not have). 482 ew = self._embedding_widget 483 if ew is None or not self.folder: 484 return 485 files = sorted(glob(os.path.join(self.folder, self.pattern or "*"))) 486 if not files: 487 return 488 try: 489 shape = imageio.improps(files[0]).shape 490 except Exception: 491 return 492 # Drop a trailing channel axis (RGB/RGBA) for the in-plane size judgement. 493 spatial = shape[:-1] if (len(shape) >= 3 and shape[-1] in (3, 4)) else shape 494 ew._apply_default_tiling_for_shape(spatial) 495 496 def _validate_inputs(self): 497 missing_data = self.folder is None or len(glob(os.path.join(self.folder, self.pattern or "*"))) == 0 498 missing_output = self.output_folder is None 499 if missing_data or missing_output: 500 msg = "" 501 if missing_data: 502 msg += "The input folder is missing or empty. " 503 if missing_output: 504 msg += "The output folder is missing." 505 return widgets._generate_message("error", msg) 506 507 # For object classification with provided segmentations, the counts must match. 508 if self.task == "Object Classification" and self.segmentation_folder: 509 n_img = len(glob(os.path.join(self.folder, self.pattern or "*"))) 510 n_seg = len(glob(os.path.join(self.segmentation_folder, self.segmentation_pattern))) 511 if n_img != n_seg: 512 return widgets._generate_message( 513 "error", f"The number of images ({n_img}) and segmentations ({n_seg}) does not match." 514 ) 515 return False 516 517 def _embedding_paths_for(self, image_files): 518 # Per-item embedding zarr paths under the chosen folder (the batch classification functions 519 # take an explicit list); 'None' when no embedding folder is set. 520 save_path = self._embedding_widget.embeddings_save_path 521 if not save_path: 522 return None 523 os.makedirs(save_path, exist_ok=True) 524 return [ 525 os.path.join(save_path, os.path.splitext(os.path.basename(f))[0] + ".zarr") for f in image_files 526 ] 527 528 def __call__(self, skip_validate=False): 529 ew = self._embedding_widget 530 ew._validate_model_type_and_custom_weights() 531 532 if not skip_validate and self._validate_inputs(): 533 return 534 535 # Only forward tiling params when tiling is enabled (the tile/halo defaults are nonzero even 536 # when tiling is 'no'). 'ndim' comes from the image-dimensions dropdown (None = auto-detect). 537 if ew.tiling == "yes": 538 tile_shape, halo = widgets._process_tiling_inputs(ew.tile_x, ew.tile_y, ew.halo_x, ew.halo_y) 539 else: 540 tile_shape, halo = None, None 541 ndim = ew._ndim_override() 542 543 common = dict( 544 model_type=ew.model_type, tile_shape=tile_shape, halo=halo, 545 checkpoint_path=ew.custom_weights, device=ew.device, batch_size=ew._effective_batch_size(), 546 viewer=self._viewer, return_viewer=True, 547 ) 548 549 if self.task == "Segmentation": 550 launched_viewer = image_folder_annotator( 551 input_folder=self.folder, output_folder=self.output_folder, ndim=ndim, 552 pattern=self.pattern or "*", embedding_path=ew.embeddings_save_path, 553 skip_segmented=bool(self.continue_annotation), **common, 554 ) 555 else: 556 image_files = sorted(glob(os.path.join(self.folder, self.pattern or "*"))) 557 if self.task == "Tracking": 558 from .annotator_tracking import batch_tracking_annotator 559 launched_viewer = batch_tracking_annotator( 560 image_files, self.output_folder, embedding_path=ew.embeddings_save_path, **common, 561 ) 562 else: 563 embedding_paths = self._embedding_paths_for(image_files) 564 if self.task == "Pixel Classification": 565 from .pixel_classifier import batch_pixel_classifier 566 launched_viewer = batch_pixel_classifier( 567 image_files, self.output_folder, embedding_paths=embedding_paths, ndim=ndim, **common, 568 ) 569 else: 570 # Object Classification: load the per-image segmentations if a folder is given. 571 from .object_classifier import batch_object_classifier 572 seg_files = None 573 if self.segmentation_folder: 574 seg_files = sorted(glob(os.path.join(self.segmentation_folder, self.segmentation_pattern))) 575 launched_viewer = batch_object_classifier( 576 image_files, seg_files, self.output_folder, 577 embedding_paths=embedding_paths, ndim=ndim, **common, 578 ) 579 580 # A batch function returns None when all results already exist and continuing is enabled. 581 # Keep this launcher available so the user can restart for review or choose another output. 582 if launched_viewer is None: 583 message = "All images have already been annotated. " 584 if self.task == "Segmentation": 585 message += ( 586 "To review or edit them, uncheck 'Continue Annotation' and start the batch annotator again, " 587 "or choose a different output folder." 588 ) 589 else: 590 message += "Choose a different output folder to start another batch." 591 widgets._generate_message("info", message) 592 return 593 594 # The console has done its job (task + settings are locked in for this session); remove it so 595 # the annotator has the screen to itself. 596 self._dismiss() 597 598 def _dismiss(self): 599 # Remove the console dock after a successful launch. Deferred so it runs after this click 600 # handler returns (deleting the widget mid-handler is unsafe); a no-op if the console was not 601 # added as a dock (e.g. in tests that construct it directly). 602 def _remove(): 603 try: 604 self._viewer.window.remove_dock_widget(self) 605 except Exception: 606 pass 607 QTimer.singleShot(0, _remove)
QWidget(parent: Self = None, flags: Qt.WindowType = Qt.WindowFlags())
290 def __init__(self, viewer: napari.Viewer, parent=None): 291 super().__init__(parent=parent) 292 self._viewer = viewer 293 294 # Compose all of the console's menus inside a single scrollable, bordered container (a 295 # QGroupBox, matching the bordered boxes the annotators wrap their sections in), so it reads 296 # as one panel and scrolls when the (expanded) embedding settings make it taller than the dock. 297 self._content = QtWidgets.QGroupBox() 298 self._content.setLayout(QtWidgets.QVBoxLayout()) 299 300 # Create the UI: options + the embedded model / embedding settings. 301 self._create_options() 302 303 # Add the run button to trigger the embedding computation. 304 self.run_button = QtWidgets.QPushButton("Annotate Images") 305 self.run_button.clicked.connect(self.__call__) 306 self._content.layout().addWidget(self.run_button) 307 308 # Pack the menus to the top: the dock's extra vertical space collapses below the button 309 # instead of being distributed as fixed gaps between the rows. 310 self._content.layout().addStretch() 311 312 scroll = QtWidgets.QScrollArea() 313 scroll.setWidgetResizable(True) 314 scroll.setWidget(self._content) 315 self.layout().addWidget(scroll) 316 317 self._rebuilt_on_show = False
319 def showEvent(self, event): 320 # napari 0.9 caps the height of dock widget content at its size hint (napari/napari#9393). 321 size_policy = self.sizePolicy() 322 size_policy_enum = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 323 size_policy.setVerticalPolicy(size_policy_enum.Expanding) 324 self.setSizePolicy(size_policy) 325 326 # The first embedding widget is built before napari styles the console, so its path fields keep 327 # the wider default font and the console opens wider than it is after any task change. Build it 328 # once more here, under the same conditions as a task change, so the width stays the same. 329 super().showEvent(event) 330 if not self._rebuilt_on_show: 331 self._rebuilt_on_show = True 332 self._rebuild_embedding_widget()
showEvent(self, a0: QShowEvent | None, /)