micro_sam.sam_annotator._batch
Shared navigation harness for the batch annotator.
Hosts any per-task annotator (segmentation, tracking, classification) and drives
the navigation, the skip-already-done check and per-item loading/saving
through a small task-adapter interface (BatchAnnotatorTask). The harness is
task-agnostic; everything task-specific lives in the concrete adapter.
1"""Shared navigation harness for the batch annotator. 2 3Hosts any per-task annotator (segmentation, tracking, classification) and drives 4the navigation, the skip-already-done check and per-item loading/saving 5through a small task-adapter interface (`BatchAnnotatorTask`). The harness is 6task-agnostic; everything task-specific lives in the concrete adapter. 7""" 8 9import os 10 11import numpy as np 12import imageio.v3 as imageio 13 14import napari 15from magicgui.widgets import Container, PushButton 16 17from qtpy import QtWidgets 18from qtpy.QtCore import QEvent, QObject, Qt, QTimer 19 20from . import _widgets as widgets 21from ._state import AnnotatorState 22from ._titles import get_dock_title 23from ..util import prepare_annotation_image 24 25 26def load_batch_image(entry, ndim=None): 27 """Load one batch image and prepare it in the same way as the annotator does. 28 29 Singleton axes are squeezed and a channel axis is mapped to a trailing RGB axis, with 30 `micro_sam.util.prepare_annotation_image`, so all batch tools treat an image in the same way. 31 32 Args: 33 entry: The image as an array, or the path to its file. 34 ndim: The spatial dimensionality (2 or 3), or None to derive it from the image. 35 36 Returns: 37 The prepared image and its spatial dimensionality. 38 """ 39 image = entry if isinstance(entry, np.ndarray) else imageio.imread(entry) 40 image, ndim, _ = prepare_annotation_image(image, ndim=ndim) 41 return image, ndim 42 43 44def _hide_embedding_widget(annotator): 45 """Hide the docked annotator's embedding section during a batch session. 46 47 The launcher's advanced settings are the single source of truth for the model / tiling / device / 48 embedding-path / ndim, and the harness computes embeddings itself in 'start'/'advance', so the 49 annotator's embedding panel (and its 'Compute Embeddings' button) is redundant here. The widget 50 object is kept alive (just hidden) because '_sync_embedding_widget' and the classifier spec read 51 from it. Standalone (non-batch) annotators never call this, so their panel stays visible. 52 """ 53 ew = getattr(annotator, "_embedding_widget", None) 54 if ew is None: 55 return 56 # Each annotator wraps its widgets in a QGroupBox. Hide that wrapper so the whole section (frame 57 # included) disappears rather than leaving an empty box. 58 frame = ew 59 while frame is not None and not isinstance(frame, QtWidgets.QGroupBox): 60 frame = frame.parentWidget() 61 (frame or ew).hide() 62 63 64def _embed_navigation(viewer, annotator, nav_container): 65 """Add the navigation controls as a 'Batch Navigation' section inside the docked annotator. 66 67 Falls back to a standalone dock widget if the annotator has no embeddable inner layout. 68 """ 69 inner = getattr(annotator, "_annotator_widget", None) 70 if inner is None or inner.layout() is None: 71 viewer.window.add_dock_widget(nav_container, name=get_dock_title("batch_navigation")) 72 return 73 group = QtWidgets.QGroupBox("Batch Navigation") 74 group_layout = QtWidgets.QVBoxLayout() 75 # Add a top margin so the group title is not cramped against the navigation buttons. 76 group_layout.setContentsMargins(8, 14, 8, 8) 77 group_layout.addWidget(nav_container.native) 78 group.setLayout(group_layout) 79 # Pin to the top of the annotator panel so it stays visible (the task annotators are tall and 80 # the navigation would otherwise sit below the fold at the bottom of the scroll area). 81 inner.layout().insertWidget(0, group) 82 83 84class _CloseFilter(QObject): 85 """Call `callback` when the watched window receives a close event, before napari tears it down.""" 86 87 def __init__(self, callback, parent): 88 super().__init__(parent) 89 self._callback = callback 90 91 def eventFilter(self, obj, event): 92 if event.type() == QEvent.Type.Close: 93 self._callback() 94 return False 95 96 97def _maximize_dock_vertically(annotator): 98 """Expand the docked annotator to fill the available vertical space when it opens. 99 100 napari sizes a freshly docked widget to its (small) size hint, leaving it shrunk; this makes the 101 annotator claim the full window height instead. Best-effort and guarded, so it is a no-op in 102 headless / test runs where the main window is not shown. 103 """ 104 size_policy = getattr(QtWidgets.QSizePolicy, "Policy", QtWidgets.QSizePolicy) 105 annotator.setSizePolicy(size_policy.Preferred, size_policy.Expanding) 106 107 # Walk up to the QDockWidget that hosts the annotator. 108 dock = annotator 109 while dock is not None and not isinstance(dock, QtWidgets.QDockWidget): 110 dock = dock.parentWidget() 111 if dock is None: 112 return 113 114 # Resolve the main window through public Qt APIs. 115 main_window = dock.parentWidget() 116 while main_window is not None and not isinstance(main_window, QtWidgets.QMainWindow): 117 main_window = main_window.parentWidget() 118 if main_window is None: 119 return 120 121 def _resize(): 122 try: 123 main_window.resizeDocks([dock], [main_window.height()], Qt.Vertical) 124 except RuntimeError: 125 pass 126 127 # Defer until the window is shown, otherwise the initial dock layout overrides the resize. 128 QTimer.singleShot(0, _resize) 129 130 131class BatchAnnotatorTask: 132 """Adapter encoding the task-specific parts of a batch annotation session. 133 134 The harness owns navigation, the skip-already-done check and the end-of-batch dialog. 135 The adapter owns precomputing the model and embeddings, loading an item into the viewer, 136 deciding whether there is content worth saving, and saving the per-item result. Concrete 137 tasks: segmentation, tracking, object/pixel classification. 138 """ 139 140 #: Folder where per-item results are written. Set by the harness before the session starts. 141 output_folder = None 142 143 #: Whether the batch inputs are in-memory arrays (True) or file paths (False). Set by the harness. 144 have_inputs_as_arrays = False 145 146 #: Whether the task supports going back to the previous item. 147 supports_previous = False 148 149 #: The spatial dimensionality (2 or 3) that every item is loaded with. 150 ndim = None 151 152 def result_filename(self, entry, index: int) -> str: 153 """Return the filename (relative to `output_folder`) of this item's saved result. 154 155 Used to skip items that are already done. `entry` is the raw batch entry 156 (an array or a file path), `index` its position in the batch. 157 """ 158 raise NotImplementedError 159 160 def precompute(self, images): 161 """Prepare the shared model and per-item embeddings. 162 163 Returns a list with one embedding path (or None) per image, aligned to `images`. 164 """ 165 raise NotImplementedError 166 167 def start(self, viewer, entry, image, embedding_path, index: int): 168 """Initialize the predictor/state for the first item, dock the annotator and return it.""" 169 raise NotImplementedError 170 171 def advance(self, viewer, annotator, entry, image, embedding_path, index: int): 172 """Load a subsequent item into the existing viewer and annotator.""" 173 raise NotImplementedError 174 175 def has_unsaved_content(self, viewer) -> bool: 176 """Whether the user produced anything worth saving for the current item.""" 177 raise NotImplementedError 178 179 def save_item(self, viewer, entry, index: int) -> None: 180 """Persist the current item's result into `output_folder`.""" 181 raise NotImplementedError 182 183 def on_leave_item(self, viewer, entry, index: int) -> None: 184 """Hook called when navigating away from an item (e.g. classifier feature/RF accumulation).""" 185 186 def on_close(self, viewer, entry, index: int) -> None: 187 """Hook called when the viewer is closed while showing an item.""" 188 189 #: Message shown when the user advances without producing anything for the current item. 190 empty_item_message = "Nothing is annotated yet. Do you wish to continue to the next image?" 191 192 def nav_extra_widgets(self): 193 """Extra magicgui widgets to place next to the Next button in the Batch Navigation container. 194 195 Task-specific (e.g. the classifiers' 'Forward Classifier State' checkbox); none by default. 196 """ 197 return [] 198 199 200def run_batch( 201 images, 202 output_folder, 203 task: BatchAnnotatorTask, 204 *, 205 have_inputs_as_arrays: bool, 206 viewer=None, 207 return_viewer: bool = False, 208 skip_done: bool = True, 209): 210 """Drive a batch annotation session for any task. 211 212 Args: 213 images: The batch entries (in-memory arrays or file paths). 214 output_folder: The folder where per-item results are saved. 215 task: The task adapter that encodes the task-specific behavior. 216 have_inputs_as_arrays: Whether `images` holds arrays (True) or file paths (False). 217 viewer: An optional pre-initialized napari viewer. 218 return_viewer: Whether to return the viewer instead of starting the napari event loop. 219 skip_done: Whether to skip items whose result already exists in `output_folder`. 220 221 Returns: 222 The napari viewer, only if `return_viewer=True`. 223 """ 224 end_msg = "You annotated the last image. Do you want to close napari?" 225 os.makedirs(output_folder, exist_ok=True) 226 task.output_folder = output_folder 227 task.have_inputs_as_arrays = have_inputs_as_arrays 228 n_images = len(images) 229 230 # Items visited in this session are never skipped, so the user can go back and forth between them. 231 visited = set() 232 233 def _is_done(index): 234 if index in visited: 235 return False 236 path = os.path.join(output_folder, task.result_filename(images[index], index)) 237 return os.path.exists(path) 238 239 def _load_pixels(index): 240 return load_batch_image(images[index], ndim=task.ndim)[0] 241 242 # Prepare the shared model and per-item embeddings (task-specific). 243 embedding_paths = task.precompute(images) 244 245 # Find the first item to annotate, optionally skipping items that are already done. 246 current_index = 0 247 if skip_done: 248 while current_index < n_images and _is_done(current_index): 249 current_index += 1 250 if current_index == n_images: 251 # The batch launcher reports this in a dialog and stays open so its settings can be 252 # changed. Keep the terminal message for direct Python / CLI use, where no viewer was 253 # supplied to display that feedback. 254 if viewer is None: 255 print("All images have already been annotated and 'skip_done' is set. Nothing to do.") 256 return 257 if current_index != 0: 258 print("The first image to annotate is image number", current_index) 259 260 if viewer is None: 261 viewer = napari.Viewer() 262 263 visited.add(current_index) 264 image = _load_pixels(current_index) 265 annotator = task.start(viewer, images[current_index], image, embedding_paths[current_index], current_index) 266 267 # The launcher owns the model / embedding settings in a batch session, so hide the annotator's 268 # (now redundant) embedding section to avoid duplicating those controls. 269 _hide_embedding_widget(annotator) 270 271 # Open the annotator maximized vertically instead of shrunk to its size hint. 272 _maximize_dock_vertically(annotator) 273 274 def _go_to(index): 275 nonlocal current_index 276 current_index = index 277 visited.add(index) 278 image = _load_pixels(index) 279 print("Loading image:", images[index] if not have_inputs_as_arrays else f"at index {index}") 280 task.advance(viewer, annotator, images[index], image, embedding_paths[index], index) 281 if prev_button is not None: 282 prev_button.enabled = index > 0 283 284 def _save_current(): 285 task.on_leave_item(viewer, images[current_index], current_index) 286 task.save_item(viewer, images[current_index], current_index) 287 288 def _do_next(*args): 289 # Prompt before advancing if nothing was produced for this item. 290 if not task.has_unsaved_content(viewer): 291 if widgets._generate_message("info", task.empty_item_message): 292 return 293 294 _save_current() 295 296 # Find the next item, skipping already-done ones if requested. 297 index = current_index + 1 298 if skip_done: 299 while index < n_images and _is_done(index): 300 index += 1 301 if index >= n_images: 302 if not widgets._generate_message("info", end_msg): 303 QTimer.singleShot(0, viewer.close) 304 return 305 _go_to(index) 306 307 def _do_previous(*args): 308 if current_index == 0: 309 return 310 _save_current() 311 _go_to(current_index - 1) 312 313 # Embed the navigation controls in the docked annotator, so they travel with the batch 314 # annotator instead of as a separate floating dock widget. The action is also tracked in the 315 # shared state, so it can be triggered programmatically (e.g. in tests) just like the annotator's 316 # own widgets. 317 state = AnnotatorState() 318 next_button = PushButton(text="Next Image [N]") 319 next_button.clicked.connect(lambda: _do_next()) 320 state.widgets["batch_next"] = _do_next 321 322 nav_buttons = [next_button] 323 prev_button = None 324 if task.supports_previous: 325 prev_button = PushButton(text="Previous Image [Shift + N]", enabled=current_index > 0) 326 prev_button.clicked.connect(lambda: _do_previous()) 327 state.widgets["batch_previous"] = _do_previous 328 nav_buttons.insert(0, prev_button) 329 # Task-specific controls placed next to Next (e.g. the classifiers' 'Keep Classifier'). 330 nav_buttons.extend(task.nav_extra_widgets()) 331 332 nav_container = Container(layout="horizontal", widgets=nav_buttons, labels=False) 333 nav_container.native.layout().setContentsMargins(0, 0, 0, 0) 334 _embed_navigation(viewer, annotator, nav_container) 335 336 def _on_close(): 337 task.on_close(viewer, images[current_index], current_index) 338 339 # The docked annotator's top-level widget is the napari main window. As the filter's parent it 340 # keeps the filter alive. 'on_close' can run more than once, e.g. if the user cancels the closing. 341 main_window = annotator.window() 342 main_window.installEventFilter(_CloseFilter(_on_close, parent=main_window)) 343 344 @viewer.bind_key("n", overwrite=True) 345 def _next_image(viewer): 346 _do_next() 347 348 if task.supports_previous: 349 @viewer.bind_key("Shift-N", overwrite=True) 350 def _previous_image(viewer): 351 _do_previous() 352 353 if return_viewer: 354 return viewer 355 napari.run()
27def load_batch_image(entry, ndim=None): 28 """Load one batch image and prepare it in the same way as the annotator does. 29 30 Singleton axes are squeezed and a channel axis is mapped to a trailing RGB axis, with 31 `micro_sam.util.prepare_annotation_image`, so all batch tools treat an image in the same way. 32 33 Args: 34 entry: The image as an array, or the path to its file. 35 ndim: The spatial dimensionality (2 or 3), or None to derive it from the image. 36 37 Returns: 38 The prepared image and its spatial dimensionality. 39 """ 40 image = entry if isinstance(entry, np.ndarray) else imageio.imread(entry) 41 image, ndim, _ = prepare_annotation_image(image, ndim=ndim) 42 return image, ndim
Load one batch image and prepare it in the same way as the annotator does.
Singleton axes are squeezed and a channel axis is mapped to a trailing RGB axis, with
micro_sam.util.prepare_annotation_image, so all batch tools treat an image in the same way.
Arguments:
- entry: The image as an array, or the path to its file.
- ndim: The spatial dimensionality (2 or 3), or None to derive it from the image.
Returns:
The prepared image and its spatial dimensionality.
132class BatchAnnotatorTask: 133 """Adapter encoding the task-specific parts of a batch annotation session. 134 135 The harness owns navigation, the skip-already-done check and the end-of-batch dialog. 136 The adapter owns precomputing the model and embeddings, loading an item into the viewer, 137 deciding whether there is content worth saving, and saving the per-item result. Concrete 138 tasks: segmentation, tracking, object/pixel classification. 139 """ 140 141 #: Folder where per-item results are written. Set by the harness before the session starts. 142 output_folder = None 143 144 #: Whether the batch inputs are in-memory arrays (True) or file paths (False). Set by the harness. 145 have_inputs_as_arrays = False 146 147 #: Whether the task supports going back to the previous item. 148 supports_previous = False 149 150 #: The spatial dimensionality (2 or 3) that every item is loaded with. 151 ndim = None 152 153 def result_filename(self, entry, index: int) -> str: 154 """Return the filename (relative to `output_folder`) of this item's saved result. 155 156 Used to skip items that are already done. `entry` is the raw batch entry 157 (an array or a file path), `index` its position in the batch. 158 """ 159 raise NotImplementedError 160 161 def precompute(self, images): 162 """Prepare the shared model and per-item embeddings. 163 164 Returns a list with one embedding path (or None) per image, aligned to `images`. 165 """ 166 raise NotImplementedError 167 168 def start(self, viewer, entry, image, embedding_path, index: int): 169 """Initialize the predictor/state for the first item, dock the annotator and return it.""" 170 raise NotImplementedError 171 172 def advance(self, viewer, annotator, entry, image, embedding_path, index: int): 173 """Load a subsequent item into the existing viewer and annotator.""" 174 raise NotImplementedError 175 176 def has_unsaved_content(self, viewer) -> bool: 177 """Whether the user produced anything worth saving for the current item.""" 178 raise NotImplementedError 179 180 def save_item(self, viewer, entry, index: int) -> None: 181 """Persist the current item's result into `output_folder`.""" 182 raise NotImplementedError 183 184 def on_leave_item(self, viewer, entry, index: int) -> None: 185 """Hook called when navigating away from an item (e.g. classifier feature/RF accumulation).""" 186 187 def on_close(self, viewer, entry, index: int) -> None: 188 """Hook called when the viewer is closed while showing an item.""" 189 190 #: Message shown when the user advances without producing anything for the current item. 191 empty_item_message = "Nothing is annotated yet. Do you wish to continue to the next image?" 192 193 def nav_extra_widgets(self): 194 """Extra magicgui widgets to place next to the Next button in the Batch Navigation container. 195 196 Task-specific (e.g. the classifiers' 'Forward Classifier State' checkbox); none by default. 197 """ 198 return []
Adapter encoding the task-specific parts of a batch annotation session.
The harness owns navigation, the skip-already-done check and the end-of-batch dialog. The adapter owns precomputing the model and embeddings, loading an item into the viewer, deciding whether there is content worth saving, and saving the per-item result. Concrete tasks: segmentation, tracking, object/pixel classification.
153 def result_filename(self, entry, index: int) -> str: 154 """Return the filename (relative to `output_folder`) of this item's saved result. 155 156 Used to skip items that are already done. `entry` is the raw batch entry 157 (an array or a file path), `index` its position in the batch. 158 """ 159 raise NotImplementedError
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.
161 def precompute(self, images): 162 """Prepare the shared model and per-item embeddings. 163 164 Returns a list with one embedding path (or None) per image, aligned to `images`. 165 """ 166 raise NotImplementedError
Prepare the shared model and per-item embeddings.
Returns a list with one embedding path (or None) per image, aligned to images.
168 def start(self, viewer, entry, image, embedding_path, index: int): 169 """Initialize the predictor/state for the first item, dock the annotator and return it.""" 170 raise NotImplementedError
Initialize the predictor/state for the first item, dock the annotator and return it.
172 def advance(self, viewer, annotator, entry, image, embedding_path, index: int): 173 """Load a subsequent item into the existing viewer and annotator.""" 174 raise NotImplementedError
Load a subsequent item into the existing viewer and annotator.
176 def has_unsaved_content(self, viewer) -> bool: 177 """Whether the user produced anything worth saving for the current item.""" 178 raise NotImplementedError
Whether the user produced anything worth saving for the current item.
180 def save_item(self, viewer, entry, index: int) -> None: 181 """Persist the current item's result into `output_folder`.""" 182 raise NotImplementedError
Persist the current item's result into output_folder.
184 def on_leave_item(self, viewer, entry, index: int) -> None: 185 """Hook called when navigating away from an item (e.g. classifier feature/RF accumulation)."""
Hook called when navigating away from an item (e.g. classifier feature/RF accumulation).
201def run_batch( 202 images, 203 output_folder, 204 task: BatchAnnotatorTask, 205 *, 206 have_inputs_as_arrays: bool, 207 viewer=None, 208 return_viewer: bool = False, 209 skip_done: bool = True, 210): 211 """Drive a batch annotation session for any task. 212 213 Args: 214 images: The batch entries (in-memory arrays or file paths). 215 output_folder: The folder where per-item results are saved. 216 task: The task adapter that encodes the task-specific behavior. 217 have_inputs_as_arrays: Whether `images` holds arrays (True) or file paths (False). 218 viewer: An optional pre-initialized napari viewer. 219 return_viewer: Whether to return the viewer instead of starting the napari event loop. 220 skip_done: Whether to skip items whose result already exists in `output_folder`. 221 222 Returns: 223 The napari viewer, only if `return_viewer=True`. 224 """ 225 end_msg = "You annotated the last image. Do you want to close napari?" 226 os.makedirs(output_folder, exist_ok=True) 227 task.output_folder = output_folder 228 task.have_inputs_as_arrays = have_inputs_as_arrays 229 n_images = len(images) 230 231 # Items visited in this session are never skipped, so the user can go back and forth between them. 232 visited = set() 233 234 def _is_done(index): 235 if index in visited: 236 return False 237 path = os.path.join(output_folder, task.result_filename(images[index], index)) 238 return os.path.exists(path) 239 240 def _load_pixels(index): 241 return load_batch_image(images[index], ndim=task.ndim)[0] 242 243 # Prepare the shared model and per-item embeddings (task-specific). 244 embedding_paths = task.precompute(images) 245 246 # Find the first item to annotate, optionally skipping items that are already done. 247 current_index = 0 248 if skip_done: 249 while current_index < n_images and _is_done(current_index): 250 current_index += 1 251 if current_index == n_images: 252 # The batch launcher reports this in a dialog and stays open so its settings can be 253 # changed. Keep the terminal message for direct Python / CLI use, where no viewer was 254 # supplied to display that feedback. 255 if viewer is None: 256 print("All images have already been annotated and 'skip_done' is set. Nothing to do.") 257 return 258 if current_index != 0: 259 print("The first image to annotate is image number", current_index) 260 261 if viewer is None: 262 viewer = napari.Viewer() 263 264 visited.add(current_index) 265 image = _load_pixels(current_index) 266 annotator = task.start(viewer, images[current_index], image, embedding_paths[current_index], current_index) 267 268 # The launcher owns the model / embedding settings in a batch session, so hide the annotator's 269 # (now redundant) embedding section to avoid duplicating those controls. 270 _hide_embedding_widget(annotator) 271 272 # Open the annotator maximized vertically instead of shrunk to its size hint. 273 _maximize_dock_vertically(annotator) 274 275 def _go_to(index): 276 nonlocal current_index 277 current_index = index 278 visited.add(index) 279 image = _load_pixels(index) 280 print("Loading image:", images[index] if not have_inputs_as_arrays else f"at index {index}") 281 task.advance(viewer, annotator, images[index], image, embedding_paths[index], index) 282 if prev_button is not None: 283 prev_button.enabled = index > 0 284 285 def _save_current(): 286 task.on_leave_item(viewer, images[current_index], current_index) 287 task.save_item(viewer, images[current_index], current_index) 288 289 def _do_next(*args): 290 # Prompt before advancing if nothing was produced for this item. 291 if not task.has_unsaved_content(viewer): 292 if widgets._generate_message("info", task.empty_item_message): 293 return 294 295 _save_current() 296 297 # Find the next item, skipping already-done ones if requested. 298 index = current_index + 1 299 if skip_done: 300 while index < n_images and _is_done(index): 301 index += 1 302 if index >= n_images: 303 if not widgets._generate_message("info", end_msg): 304 QTimer.singleShot(0, viewer.close) 305 return 306 _go_to(index) 307 308 def _do_previous(*args): 309 if current_index == 0: 310 return 311 _save_current() 312 _go_to(current_index - 1) 313 314 # Embed the navigation controls in the docked annotator, so they travel with the batch 315 # annotator instead of as a separate floating dock widget. The action is also tracked in the 316 # shared state, so it can be triggered programmatically (e.g. in tests) just like the annotator's 317 # own widgets. 318 state = AnnotatorState() 319 next_button = PushButton(text="Next Image [N]") 320 next_button.clicked.connect(lambda: _do_next()) 321 state.widgets["batch_next"] = _do_next 322 323 nav_buttons = [next_button] 324 prev_button = None 325 if task.supports_previous: 326 prev_button = PushButton(text="Previous Image [Shift + N]", enabled=current_index > 0) 327 prev_button.clicked.connect(lambda: _do_previous()) 328 state.widgets["batch_previous"] = _do_previous 329 nav_buttons.insert(0, prev_button) 330 # Task-specific controls placed next to Next (e.g. the classifiers' 'Keep Classifier'). 331 nav_buttons.extend(task.nav_extra_widgets()) 332 333 nav_container = Container(layout="horizontal", widgets=nav_buttons, labels=False) 334 nav_container.native.layout().setContentsMargins(0, 0, 0, 0) 335 _embed_navigation(viewer, annotator, nav_container) 336 337 def _on_close(): 338 task.on_close(viewer, images[current_index], current_index) 339 340 # The docked annotator's top-level widget is the napari main window. As the filter's parent it 341 # keeps the filter alive. 'on_close' can run more than once, e.g. if the user cancels the closing. 342 main_window = annotator.window() 343 main_window.installEventFilter(_CloseFilter(_on_close, parent=main_window)) 344 345 @viewer.bind_key("n", overwrite=True) 346 def _next_image(viewer): 347 _do_next() 348 349 if task.supports_previous: 350 @viewer.bind_key("Shift-N", overwrite=True) 351 def _previous_image(viewer): 352 _do_previous() 353 354 if return_viewer: 355 return viewer 356 napari.run()
Drive a batch annotation session for any task.
Arguments:
- images: The batch entries (in-memory arrays or file paths).
- output_folder: The folder where per-item results are saved.
- task: The task adapter that encodes the task-specific behavior.
- have_inputs_as_arrays: Whether
imagesholds arrays (True) or file paths (False). - viewer: An optional pre-initialized napari viewer.
- return_viewer: Whether to return the viewer instead of starting the napari event loop.
- skip_done: Whether to skip items whose result already exists in
output_folder.
Returns:
The napari viewer, only if
return_viewer=True.