micro_sam.sam_annotator._batch_classification
Shared batch-annotation task for the object and pixel classifiers.
Both classifiers share the per-item batch flow: (re)initialize the predictor, build the classifier widget, store the per-item annotations and labeled features when leaving an item, restore them when going back to it, and save the prediction plus the trained classifier. Subclasses bind the concrete classifier widget class, the cached state-attribute names and any extra per-item layers (the object classifier adds a segmentation layer).
1"""Shared batch-annotation task for the object and pixel classifiers. 2 3Both classifiers share the per-item batch flow: (re)initialize the predictor, build the classifier 4widget, store the per-item annotations and labeled features when leaving an item, restore them when 5going back to it, and save the prediction plus the trained classifier. Subclasses bind the concrete 6classifier widget class, the cached state-attribute names and any extra per-item layers (the object 7classifier adds a segmentation layer). 8""" 9 10import os 11from joblib import dump 12 13import numpy as np 14import imageio.v3 as imageio 15 16from magicgui.widgets import CheckBox 17 18from ._titles import PLUGIN_NAME 19from ._state import AnnotatorState 20from ._tooltips import get_tooltip 21from ._batch import BatchAnnotatorTask 22from ..v2.util import resolve_default_tiling 23from .util import _sync_embedding_widget, _sync_tiling_widget 24 25 26class ClassificationBatchTask(BatchAnnotatorTask): 27 """Batch task base for the classifiers. Subclasses bind the concrete widget and state attributes.""" 28 29 # Bound by subclasses. 30 classifier_class = None # ObjectClassifier | PixelClassifier 31 dock_name = PLUGIN_NAME 32 features_attr = None # "object_features" | "pixel_features" 33 aux_attr = None # "seg_ids" | "pixel_grid_shape" 34 rf_attr = None # "object_rf" | "pixel_rf" 35 supports_previous = True 36 37 def __init__( 38 self, *, ndim, model_type, embedding_paths=None, tile_shape=None, halo=None, 39 checkpoint_path=None, device=None, batch_size=1, 40 ): 41 self.ndim = ndim 42 self.model_type = model_type 43 self.embedding_paths = embedding_paths 44 self.tile_shape = tile_shape 45 self.halo = halo 46 self.checkpoint_path = checkpoint_path 47 self.device = device 48 self.batch_size = batch_size 49 50 def _set_layers(self, viewer, index): 51 """Hook: add or update task-specific layers (e.g. the segmentation layer) for this item.""" 52 53 def _item_filename(self, entry, index, suffix): 54 if self.have_inputs_as_arrays: 55 return f"{suffix}_{index:05}.tif" 56 return os.path.splitext(os.path.basename(entry))[0] + f"_{suffix}.tif" 57 58 def result_filename(self, entry, index): 59 return self._item_filename(entry, index, "prediction") 60 61 def precompute(self, images): 62 # Start the batch with an empty training set and no cached features/classifier, so a new 63 # session does not inherit the state of a previous one (the state is a singleton). 64 state = AnnotatorState() 65 state.batch_training_data, state.batch_index = {}, None 66 self.annotations = {} 67 setattr(state, self.features_attr, None) 68 setattr(state, self.aux_attr, None) 69 setattr(state, self.rf_attr, None) 70 if self.embedding_paths is None: 71 return [None] * len(images) 72 return list(self.embedding_paths) 73 74 def _init_predictor(self, viewer, image, embedding_path, reuse): 75 state = AnnotatorState() 76 # Reuse the already-loaded model on subsequent items so it is not re-downloaded/rebuilt. 77 kwargs = {"predictor": state.predictor} if (reuse and state.predictor is not None) else {} 78 # The image is prepared by 'load_batch_image', so a channel axis is always the last one. 79 state.image_shape = image.shape[:self.ndim] 80 state.ndim = self.ndim 81 # Resolve the tiling per image, since the shapes can differ across the batch. 82 tile_shape, halo = resolve_default_tiling(state.image_shape, self.tile_shape, self.halo, embedding_path) 83 state.initialize_predictor( 84 image, model_type=self.model_type, save_path=embedding_path, halo=halo, 85 tile_shape=tile_shape, precompute_autoseg_state=False, ndim=self.ndim, 86 checkpoint_path=self.checkpoint_path, device=self.device, batch_size=self.batch_size, 87 use_cli=True, **kwargs, 88 ) 89 return tile_shape, halo 90 91 def _restore_annotations(self, viewer, entry, index): 92 # Restore the annotations of a revisited item, from this session or from an earlier one. 93 annotations = self.annotations.get(index) 94 path = os.path.join(self.output_folder, self._item_filename(entry, index, "annotations")) 95 if annotations is None and os.path.exists(path): 96 annotations = imageio.imread(path) 97 layer = viewer.layers["annotations"] 98 if annotations is None or annotations.shape != layer.data.shape: 99 return False 100 layer.data = annotations.copy() 101 return bool(annotations.any()) 102 103 def start(self, viewer, entry, image, embedding_path, index): 104 AnnotatorState().batch_index = index 105 tile_shape, halo = self._init_predictor(viewer, image, embedding_path, reuse=False) 106 viewer.add_image(image, name="image", rgb=image.ndim > self.ndim) 107 self._set_layers(viewer, index) 108 109 annotator = self.classifier_class(viewer) 110 annotator._update_image() 111 112 state = AnnotatorState() 113 viewer.window.add_dock_widget(annotator, name=self.dock_name) 114 _sync_embedding_widget( 115 widget=state.widgets["embeddings"], 116 model_type=self.model_type if self.checkpoint_path is None else state.predictor.model_type, 117 save_path=embedding_path, checkpoint_path=self.checkpoint_path, 118 device=self.device, tile_shape=tile_shape, halo=halo, 119 ) 120 if self._restore_annotations(viewer, entry, index): 121 annotator._run_train_and_predict() 122 return annotator 123 124 def nav_extra_widgets(self): 125 # A checkbox next to the navigation buttons (classification tasks only), on by default, to carry 126 # the classifier state forward across the batch. Tracked in the state so it is reachable in tests. 127 self._forward_state = CheckBox(value=True, text="Keep Classifier") 128 self._forward_state.native.setToolTip(get_tooltip("classification", "forward_classifier_state")) 129 AnnotatorState().widgets["batch_forward_state"] = self._forward_state 130 return [self._forward_state] 131 132 def _forward_state_enabled(self): 133 widget = getattr(self, "_forward_state", None) 134 return True if widget is None else bool(widget.value) 135 136 def advance(self, viewer, annotator, entry, image, embedding_path, index): 137 state = AnnotatorState() 138 state.batch_index = index 139 viewer.layers["image"].data = image 140 # The predictor first, because it sets the image shape that a new empty layer is made with. 141 tile_shape, halo = self._init_predictor(viewer, image, embedding_path, reuse=True) 142 self._set_layers(viewer, index) 143 _sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo) 144 annotator._update_image() 145 # Drop the cached features/aux of the previous image. 146 setattr(state, self.features_attr, None) 147 setattr(state, self.aux_attr, None) 148 if not self._forward_state_enabled(): 149 # Independent per image: drop the training set and the classifier of the other images. 150 state.batch_training_data = {} 151 setattr(state, self.rf_attr, None) 152 153 # Retrain a fresh random forest on the annotations of this image (if revisited) and, when the 154 # classifier is carried forward, of all other images. Then predict right away. 155 has_annotations = self._restore_annotations(viewer, entry, index) 156 if has_annotations or (self._forward_state_enabled() and self._has_other_training_data(index)): 157 annotator._run_train_and_predict() 158 159 def _has_other_training_data(self, index): 160 return any(idx != index for idx in AnnotatorState().batch_training_data) 161 162 def has_unsaved_content(self, viewer): 163 # Classification always has a prediction to save, so it never prompts on advance. 164 return True 165 166 def on_leave_item(self, viewer, entry, index): 167 state = AnnotatorState() 168 annotator = state.annotator 169 annotations = viewer.layers["annotations"].data 170 self.annotations[index] = annotations.copy() 171 path = os.path.join(self.output_folder, self._item_filename(entry, index, "annotations")) 172 imageio.imwrite(path, annotations, compression="zlib") 173 174 # Retrain if the annotations changed since the last run, so the saved classifier and prediction 175 # include all annotations. 176 forward = self._forward_state_enabled() 177 has_data = annotations.any() or (forward and self._has_other_training_data(index)) 178 if has_data and annotator.is_prediction_stale(): 179 annotator._run_train_and_predict() 180 181 if forward: 182 # Replace this image's entry in the training set, which is forwarded to the other images. 183 annotator.store_batch_training_data(index) 184 features, labels = annotator.batch_training_set() 185 if features is not None: 186 np.save(os.path.join(self.output_folder, "features.npy"), features) 187 np.save(os.path.join(self.output_folder, "labels.npy"), labels) 188 189 def on_close(self, viewer, entry, index): 190 # Save the annotations and the classifier, but not the prediction, so the item is not marked as 191 # done and a resumed session starts on it with its annotations restored. A programmatic 192 # 'viewer.close()' removes the layers before closing the window, so there is nothing to save then. 193 if "annotations" not in viewer.layers: 194 return 195 self.on_leave_item(viewer, entry, index) 196 self._save_rf() 197 198 def save_item(self, viewer, entry, index): 199 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 200 imageio.imwrite(save_path, viewer.layers["prediction"].data, compression="zlib") 201 self._save_rf() 202 203 def _save_rf(self): 204 state = AnnotatorState() 205 rf = getattr(state, self.rf_attr) 206 if rf is not None: 207 dump( 208 {"rf": rf, "model_spec": state.annotator._classifier_spec(rf)}, 209 os.path.join(self.output_folder, "rf.joblib"), 210 )
27class ClassificationBatchTask(BatchAnnotatorTask): 28 """Batch task base for the classifiers. Subclasses bind the concrete widget and state attributes.""" 29 30 # Bound by subclasses. 31 classifier_class = None # ObjectClassifier | PixelClassifier 32 dock_name = PLUGIN_NAME 33 features_attr = None # "object_features" | "pixel_features" 34 aux_attr = None # "seg_ids" | "pixel_grid_shape" 35 rf_attr = None # "object_rf" | "pixel_rf" 36 supports_previous = True 37 38 def __init__( 39 self, *, ndim, model_type, embedding_paths=None, tile_shape=None, halo=None, 40 checkpoint_path=None, device=None, batch_size=1, 41 ): 42 self.ndim = ndim 43 self.model_type = model_type 44 self.embedding_paths = embedding_paths 45 self.tile_shape = tile_shape 46 self.halo = halo 47 self.checkpoint_path = checkpoint_path 48 self.device = device 49 self.batch_size = batch_size 50 51 def _set_layers(self, viewer, index): 52 """Hook: add or update task-specific layers (e.g. the segmentation layer) for this item.""" 53 54 def _item_filename(self, entry, index, suffix): 55 if self.have_inputs_as_arrays: 56 return f"{suffix}_{index:05}.tif" 57 return os.path.splitext(os.path.basename(entry))[0] + f"_{suffix}.tif" 58 59 def result_filename(self, entry, index): 60 return self._item_filename(entry, index, "prediction") 61 62 def precompute(self, images): 63 # Start the batch with an empty training set and no cached features/classifier, so a new 64 # session does not inherit the state of a previous one (the state is a singleton). 65 state = AnnotatorState() 66 state.batch_training_data, state.batch_index = {}, None 67 self.annotations = {} 68 setattr(state, self.features_attr, None) 69 setattr(state, self.aux_attr, None) 70 setattr(state, self.rf_attr, None) 71 if self.embedding_paths is None: 72 return [None] * len(images) 73 return list(self.embedding_paths) 74 75 def _init_predictor(self, viewer, image, embedding_path, reuse): 76 state = AnnotatorState() 77 # Reuse the already-loaded model on subsequent items so it is not re-downloaded/rebuilt. 78 kwargs = {"predictor": state.predictor} if (reuse and state.predictor is not None) else {} 79 # The image is prepared by 'load_batch_image', so a channel axis is always the last one. 80 state.image_shape = image.shape[:self.ndim] 81 state.ndim = self.ndim 82 # Resolve the tiling per image, since the shapes can differ across the batch. 83 tile_shape, halo = resolve_default_tiling(state.image_shape, self.tile_shape, self.halo, embedding_path) 84 state.initialize_predictor( 85 image, model_type=self.model_type, save_path=embedding_path, halo=halo, 86 tile_shape=tile_shape, precompute_autoseg_state=False, ndim=self.ndim, 87 checkpoint_path=self.checkpoint_path, device=self.device, batch_size=self.batch_size, 88 use_cli=True, **kwargs, 89 ) 90 return tile_shape, halo 91 92 def _restore_annotations(self, viewer, entry, index): 93 # Restore the annotations of a revisited item, from this session or from an earlier one. 94 annotations = self.annotations.get(index) 95 path = os.path.join(self.output_folder, self._item_filename(entry, index, "annotations")) 96 if annotations is None and os.path.exists(path): 97 annotations = imageio.imread(path) 98 layer = viewer.layers["annotations"] 99 if annotations is None or annotations.shape != layer.data.shape: 100 return False 101 layer.data = annotations.copy() 102 return bool(annotations.any()) 103 104 def start(self, viewer, entry, image, embedding_path, index): 105 AnnotatorState().batch_index = index 106 tile_shape, halo = self._init_predictor(viewer, image, embedding_path, reuse=False) 107 viewer.add_image(image, name="image", rgb=image.ndim > self.ndim) 108 self._set_layers(viewer, index) 109 110 annotator = self.classifier_class(viewer) 111 annotator._update_image() 112 113 state = AnnotatorState() 114 viewer.window.add_dock_widget(annotator, name=self.dock_name) 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=embedding_path, checkpoint_path=self.checkpoint_path, 119 device=self.device, tile_shape=tile_shape, halo=halo, 120 ) 121 if self._restore_annotations(viewer, entry, index): 122 annotator._run_train_and_predict() 123 return annotator 124 125 def nav_extra_widgets(self): 126 # A checkbox next to the navigation buttons (classification tasks only), on by default, to carry 127 # the classifier state forward across the batch. Tracked in the state so it is reachable in tests. 128 self._forward_state = CheckBox(value=True, text="Keep Classifier") 129 self._forward_state.native.setToolTip(get_tooltip("classification", "forward_classifier_state")) 130 AnnotatorState().widgets["batch_forward_state"] = self._forward_state 131 return [self._forward_state] 132 133 def _forward_state_enabled(self): 134 widget = getattr(self, "_forward_state", None) 135 return True if widget is None else bool(widget.value) 136 137 def advance(self, viewer, annotator, entry, image, embedding_path, index): 138 state = AnnotatorState() 139 state.batch_index = index 140 viewer.layers["image"].data = image 141 # The predictor first, because it sets the image shape that a new empty layer is made with. 142 tile_shape, halo = self._init_predictor(viewer, image, embedding_path, reuse=True) 143 self._set_layers(viewer, index) 144 _sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo) 145 annotator._update_image() 146 # Drop the cached features/aux of the previous image. 147 setattr(state, self.features_attr, None) 148 setattr(state, self.aux_attr, None) 149 if not self._forward_state_enabled(): 150 # Independent per image: drop the training set and the classifier of the other images. 151 state.batch_training_data = {} 152 setattr(state, self.rf_attr, None) 153 154 # Retrain a fresh random forest on the annotations of this image (if revisited) and, when the 155 # classifier is carried forward, of all other images. Then predict right away. 156 has_annotations = self._restore_annotations(viewer, entry, index) 157 if has_annotations or (self._forward_state_enabled() and self._has_other_training_data(index)): 158 annotator._run_train_and_predict() 159 160 def _has_other_training_data(self, index): 161 return any(idx != index for idx in AnnotatorState().batch_training_data) 162 163 def has_unsaved_content(self, viewer): 164 # Classification always has a prediction to save, so it never prompts on advance. 165 return True 166 167 def on_leave_item(self, viewer, entry, index): 168 state = AnnotatorState() 169 annotator = state.annotator 170 annotations = viewer.layers["annotations"].data 171 self.annotations[index] = annotations.copy() 172 path = os.path.join(self.output_folder, self._item_filename(entry, index, "annotations")) 173 imageio.imwrite(path, annotations, compression="zlib") 174 175 # Retrain if the annotations changed since the last run, so the saved classifier and prediction 176 # include all annotations. 177 forward = self._forward_state_enabled() 178 has_data = annotations.any() or (forward and self._has_other_training_data(index)) 179 if has_data and annotator.is_prediction_stale(): 180 annotator._run_train_and_predict() 181 182 if forward: 183 # Replace this image's entry in the training set, which is forwarded to the other images. 184 annotator.store_batch_training_data(index) 185 features, labels = annotator.batch_training_set() 186 if features is not None: 187 np.save(os.path.join(self.output_folder, "features.npy"), features) 188 np.save(os.path.join(self.output_folder, "labels.npy"), labels) 189 190 def on_close(self, viewer, entry, index): 191 # Save the annotations and the classifier, but not the prediction, so the item is not marked as 192 # done and a resumed session starts on it with its annotations restored. A programmatic 193 # 'viewer.close()' removes the layers before closing the window, so there is nothing to save then. 194 if "annotations" not in viewer.layers: 195 return 196 self.on_leave_item(viewer, entry, index) 197 self._save_rf() 198 199 def save_item(self, viewer, entry, index): 200 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 201 imageio.imwrite(save_path, viewer.layers["prediction"].data, compression="zlib") 202 self._save_rf() 203 204 def _save_rf(self): 205 state = AnnotatorState() 206 rf = getattr(state, self.rf_attr) 207 if rf is not None: 208 dump( 209 {"rf": rf, "model_spec": state.annotator._classifier_spec(rf)}, 210 os.path.join(self.output_folder, "rf.joblib"), 211 )
Batch task base for the classifiers. Subclasses bind the concrete widget and state attributes.
38 def __init__( 39 self, *, ndim, model_type, embedding_paths=None, tile_shape=None, halo=None, 40 checkpoint_path=None, device=None, batch_size=1, 41 ): 42 self.ndim = ndim 43 self.model_type = model_type 44 self.embedding_paths = embedding_paths 45 self.tile_shape = tile_shape 46 self.halo = halo 47 self.checkpoint_path = checkpoint_path 48 self.device = device 49 self.batch_size = batch_size
59 def result_filename(self, entry, index): 60 return self._item_filename(entry, index, "prediction")
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.
62 def precompute(self, images): 63 # Start the batch with an empty training set and no cached features/classifier, so a new 64 # session does not inherit the state of a previous one (the state is a singleton). 65 state = AnnotatorState() 66 state.batch_training_data, state.batch_index = {}, None 67 self.annotations = {} 68 setattr(state, self.features_attr, None) 69 setattr(state, self.aux_attr, None) 70 setattr(state, self.rf_attr, None) 71 if self.embedding_paths is None: 72 return [None] * len(images) 73 return list(self.embedding_paths)
Prepare the shared model and per-item embeddings.
Returns a list with one embedding path (or None) per image, aligned to images.
104 def start(self, viewer, entry, image, embedding_path, index): 105 AnnotatorState().batch_index = index 106 tile_shape, halo = self._init_predictor(viewer, image, embedding_path, reuse=False) 107 viewer.add_image(image, name="image", rgb=image.ndim > self.ndim) 108 self._set_layers(viewer, index) 109 110 annotator = self.classifier_class(viewer) 111 annotator._update_image() 112 113 state = AnnotatorState() 114 viewer.window.add_dock_widget(annotator, name=self.dock_name) 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=embedding_path, checkpoint_path=self.checkpoint_path, 119 device=self.device, tile_shape=tile_shape, halo=halo, 120 ) 121 if self._restore_annotations(viewer, entry, index): 122 annotator._run_train_and_predict() 123 return annotator
Initialize the predictor/state for the first item, dock the annotator and return it.
137 def advance(self, viewer, annotator, entry, image, embedding_path, index): 138 state = AnnotatorState() 139 state.batch_index = index 140 viewer.layers["image"].data = image 141 # The predictor first, because it sets the image shape that a new empty layer is made with. 142 tile_shape, halo = self._init_predictor(viewer, image, embedding_path, reuse=True) 143 self._set_layers(viewer, index) 144 _sync_tiling_widget(AnnotatorState().widgets["embeddings"], tile_shape, halo) 145 annotator._update_image() 146 # Drop the cached features/aux of the previous image. 147 setattr(state, self.features_attr, None) 148 setattr(state, self.aux_attr, None) 149 if not self._forward_state_enabled(): 150 # Independent per image: drop the training set and the classifier of the other images. 151 state.batch_training_data = {} 152 setattr(state, self.rf_attr, None) 153 154 # Retrain a fresh random forest on the annotations of this image (if revisited) and, when the 155 # classifier is carried forward, of all other images. Then predict right away. 156 has_annotations = self._restore_annotations(viewer, entry, index) 157 if has_annotations or (self._forward_state_enabled() and self._has_other_training_data(index)): 158 annotator._run_train_and_predict()
Load a subsequent item into the existing viewer and annotator.
163 def has_unsaved_content(self, viewer): 164 # Classification always has a prediction to save, so it never prompts on advance. 165 return True
Whether the user produced anything worth saving for the current item.
167 def on_leave_item(self, viewer, entry, index): 168 state = AnnotatorState() 169 annotator = state.annotator 170 annotations = viewer.layers["annotations"].data 171 self.annotations[index] = annotations.copy() 172 path = os.path.join(self.output_folder, self._item_filename(entry, index, "annotations")) 173 imageio.imwrite(path, annotations, compression="zlib") 174 175 # Retrain if the annotations changed since the last run, so the saved classifier and prediction 176 # include all annotations. 177 forward = self._forward_state_enabled() 178 has_data = annotations.any() or (forward and self._has_other_training_data(index)) 179 if has_data and annotator.is_prediction_stale(): 180 annotator._run_train_and_predict() 181 182 if forward: 183 # Replace this image's entry in the training set, which is forwarded to the other images. 184 annotator.store_batch_training_data(index) 185 features, labels = annotator.batch_training_set() 186 if features is not None: 187 np.save(os.path.join(self.output_folder, "features.npy"), features) 188 np.save(os.path.join(self.output_folder, "labels.npy"), labels)
Hook called when navigating away from an item (e.g. classifier feature/RF accumulation).
190 def on_close(self, viewer, entry, index): 191 # Save the annotations and the classifier, but not the prediction, so the item is not marked as 192 # done and a resumed session starts on it with its annotations restored. A programmatic 193 # 'viewer.close()' removes the layers before closing the window, so there is nothing to save then. 194 if "annotations" not in viewer.layers: 195 return 196 self.on_leave_item(viewer, entry, index) 197 self._save_rf()
Hook called when the viewer is closed while showing an item.
199 def save_item(self, viewer, entry, index): 200 save_path = os.path.join(self.output_folder, self.result_filename(entry, index)) 201 imageio.imwrite(save_path, viewer.layers["prediction"].data, compression="zlib") 202 self._save_rf()
Persist the current item's result into output_folder.