micro_sam.v2.automatic_segmentation
Front-end and CLI helpers for automatic instance segmentation and tracking with SAM2.
This module mirrors the micro-sam v1 automatic_segmentation module: it provides only the
CLI / front-end entry points and delegates all inference to the backend engines in
micro_sam.v2.instance_segmentation (grid-based AMG and decoder-based AIS with the UniSAM2 model).
get_predictor_and_segmenter: load the SAM2 predictor and the automatic segmentation generator.automatic_instance_segmentation: run automatic segmentation for a single 2d image or 3d volume.automatic_tracking: run automatic tracking for a timeseries.
1"""Front-end and CLI helpers for automatic instance segmentation and tracking with SAM2. 2 3This module mirrors the micro-sam v1 `automatic_segmentation` module: it provides only the 4CLI / front-end entry points and delegates all inference to the backend engines in 5`micro_sam.v2.instance_segmentation` (grid-based AMG and decoder-based AIS with the UniSAM2 model). 6 7- `get_predictor_and_segmenter`: load the SAM2 predictor and the automatic segmentation generator. 8- `automatic_instance_segmentation`: run automatic segmentation for a single 2d image or 3d volume. 9- `automatic_tracking`: run automatic tracking for a timeseries. 10""" 11 12import os 13from typing import Optional, Tuple, Union 14 15import numpy as np 16 17import torch 18 19from .util import DEFAULT_MODEL, Devices 20 21 22def get_predictor_and_segmenter( 23 model_type: str = DEFAULT_MODEL, 24 checkpoint: Optional[Union[str, os.PathLike]] = None, 25 device: Optional[Union[str, torch.device]] = None, 26 segmentation_mode: Optional[str] = None, 27 is_tiled: bool = False, 28 ndim: int = 2, 29 **kwargs, 30) -> Tuple[object, object]: 31 """Get the SAM2 predictor and the generator for automatic instance segmentation. 32 33 Automatic segmentation with SAM2 uses one of three engines, selected via `segmentation_mode`: 34 the decoder-based AIS (with a UniSAM2 decoder from a finetuned model, e.g. 'hvit_t_cells', or a 35 `checkpoint`), the grid-based AMG (no decoder), or APG, which derives candidates from the decoder 36 and prompts the interactive branch with them. By default AIS is used when a decoder is available 37 and AMG otherwise. APG costs several forward passes per image, so it is opt-in. 38 39 Args: 40 model_type: The SAM2 model. Either a finetuned model with a registered decoder (see 41 `micro_sam.v2.util.get_model_names`) or a base backbone combined with `checkpoint`. 42 checkpoint: Optional path to a custom checkpoint. It defines the SAM2 model, and the UniSAM2 decoder. 43 The model size is read from the checkpoint. 44 device: The torch device. By default the best available device is selected. 45 segmentation_mode: The segmentation engine, one of 'amg', 'ais' or 'apg'. By default 'ais' is 46 used if a decoder is available, otherwise 'amg'. 47 is_tiled: Whether to return a segmenter for in-plane (xy) tiled segmentation. 48 ndim: The number of spatial dimensions the segmenter is built for. Only APG needs to know: 49 it propagates its prompts through a volume, which needs the video predictor. 50 kwargs: Keyword arguments for the automatic mask generation (AMG) class. 51 52 Returns: 53 The SAM2 predictor (used to precompute embeddings) and the automatic segmentation generator. 54 55 Raises: 56 NoDecoderError: If `checkpoint` has no decoder, because it was trained for interactive segmentation 57 only, and `segmentation_mode` is not 'amg'. 58 """ 59 from ..util import get_device, _get_sam_model 60 from .instance_segmentation import NoDecoderError, get_decoder, get_instance_segmentation_generator 61 62 # Kept apart from the placement below, so 'use all visible GPUs' stays distinct from one device. 63 requested_device = device 64 model_device = get_device(device) 65 66 # Volumetric APG propagates its prompts, so it needs the video predictor, which also encodes. 67 predictor, _ = _get_sam_model( 68 model_type=model_type, ndim=3 if (segmentation_mode == "apg" and ndim == 3) else 2, 69 device=model_device, checkpoint_path=checkpoint, decoder_path=None, use_cli=True, 70 ) 71 # A custom checkpoint can hold another backbone than the name. 72 model_type = predictor.model_type 73 74 # 'ais' and 'apg' require a decoder, 'amg' never uses one, and 'auto' prefers one if it loads. 75 decoder = None 76 if segmentation_mode != "amg": 77 try: 78 # Reuse the predictor's encoder, so no second SAM2 backbone is built. 79 encoder = getattr(getattr(predictor, "model", predictor), "image_encoder", None) 80 decoder = get_decoder(model_type, checkpoint=checkpoint, device=model_device, encoder=encoder) 81 except NoDecoderError: 82 # A custom checkpoint without decoder was trained for interactive segmentation only. 83 raise 84 except Exception as e: 85 if segmentation_mode in ("ais", "apg"): 86 raise 87 print(f"Could not load a UniSAM2 decoder for '{model_type}', falling back to AMG: {e}") 88 89 # An explicit mode is honored; only the automatic choice falls back to what the decoder allows. 90 if segmentation_mode is None: 91 engine = "ais" if decoder is not None else "amg" 92 else: 93 engine = segmentation_mode 94 if engine == "amg": # Tags the cached embeddings, so the AMG state is not reused across models. 95 kwargs.setdefault("model_type", model_type) 96 segmenter = get_instance_segmentation_generator( 97 # The video predictor is the SAM2 model itself, an image predictor wraps one. 98 model=getattr(predictor, "model", predictor), decoder=decoder, is_tiled=is_tiled, 99 segmentation_mode=engine, device=model_device, inference_device=requested_device, ndim=ndim, **kwargs, 100 ) 101 return predictor, segmenter 102 103 104def _resolve_tiling(spatial_shape, tile_shape, halo, with_z_axis, embedding_path=None): 105 """Resolve the tiling for the headless entry points, in the axes their segmenter expects. 106 107 Tiling is supported by every engine, so it is applied by default for images whose in-plane size 108 exceeds the cutoff - the model resizes whatever it is given to its encoder patch, so running a 109 large image in one piece shrinks the objects far below the scale the model was trained on. This 110 shares `micro_sam.v2.util.resolve_default_tiling` with the annotation tools, so the CLI, the 111 Python API and the GUI all tile the same image the same way, and all of them reuse the tiling of 112 already cached embeddings rather than recomputing them with different settings. Pass an all-zero 113 `tile_shape` and `halo` to run untiled regardless of the size. 114 115 Args: 116 spatial_shape: The image shape without any channel axis, (y, x) or (z, y, x). 117 tile_shape: The requested tile shape, in the axes described by `with_z_axis`. 118 halo: The requested tile overlap, matching `tile_shape`'s axes. 119 with_z_axis: Whether the segmenter takes the full (z, y, x) rather than just the in-plane 120 (y, x). True for decoder-based inference on a volume, which chunks z as well. 121 embedding_path: Optional filepath of the cached embeddings, whose tiling is reused. 122 123 Returns: 124 The resolved tile shape and halo, None if the run stays untiled. Plus whether the result 125 tiles in-plane, which decides the tiled or non-tiled segmenter. 126 127 Raises: 128 ValueError: If tiling is turned off with an all-zero tile shape but a real halo is given. 129 """ 130 from .util import resolve_default_tiling, DEFAULT_TILE_Z, DEFAULT_HALO_Z 131 132 # Decide on the in-plane axes alone, then put the z entry back for the volumetric decoder. 133 in_plane_tile = None if tile_shape is None else tuple(tile_shape[-2:]) 134 in_plane_halo = None if halo is None else tuple(halo[-2:]) 135 in_plane_tile, in_plane_halo = resolve_default_tiling( 136 spatial_shape, in_plane_tile, in_plane_halo, embedding_path, 137 ) 138 is_tiled = in_plane_tile is not None 139 140 if not with_z_axis: 141 return in_plane_tile, in_plane_halo, is_tiled 142 143 # Without in-plane tiling, keep passing None so z keeps chunking itself (see '_resolve_z_chunk'). 144 if not is_tiled: 145 return None, None, False 146 147 if tile_shape is not None and len(tile_shape) == 3: # The caller set the z chunk itself. 148 z_tile = int(tile_shape[0]) 149 z_halo = 0 if (halo is None or len(halo) != 3) else int(halo[0]) 150 else: # The same z chunk the untiled 3d path picks for itself. 151 n_slices = spatial_shape[0] 152 z_tile = min(DEFAULT_TILE_Z, n_slices) 153 z_halo = DEFAULT_HALO_Z if z_tile < n_slices else 0 154 return (z_tile, *in_plane_tile), (z_halo, *in_plane_halo), True 155 156 157def automatic_instance_segmentation( 158 predictor, 159 segmenter, 160 input_path: Union[str, os.PathLike, np.ndarray], 161 output_path: Optional[Union[str, os.PathLike]] = None, 162 embedding_path: Optional[Union[str, os.PathLike]] = None, 163 model_type: str = DEFAULT_MODEL, 164 checkpoint: Optional[Union[str, os.PathLike]] = None, 165 key: Optional[str] = None, 166 ndim: Optional[int] = None, 167 tile_shape: Optional[tuple] = None, 168 halo: Optional[tuple] = None, 169 mode: str = "sparse", 170 device: Optional[Union[str, torch.device]] = None, 171 verbose: bool = True, 172 batch_size: Optional[int] = 1, 173 devices: Devices = None, 174 num_prefetch_workers: int = 4, 175 num_write_workers: int = 2, 176 norm_bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 177 **generate_kwargs, 178) -> np.ndarray: 179 """Run automatic instance segmentation for a single input and save the result. 180 181 Args: 182 predictor: The SAM2 predictor (see `get_predictor_and_segmenter`). The decoder-based engines 183 use it to precompute the image embeddings. 184 segmenter: The automatic instance segmentation generator (see `get_predictor_and_segmenter`). 185 input_path: The input image, either a filepath (e.g. tif or a container with `key`) or an array. 186 output_path: Optional path to save the segmentation as a tif file. 187 embedding_path: The optional path to cache the image embeddings. The function saves the 188 embeddings there, and it uses them again in a later call. The decoder-based engines always 189 precompute the embeddings. Without this path, they keep the embeddings in memory (untiled 190 2d) or in an ephemeral cache. Without this path, tiled APG encodes each tile / block itself. 191 model_type: Retained for API compatibility; the loaded predictor determines the embedding model. 192 checkpoint: Retained for API compatibility; the loaded predictor already contains its weights. 193 key: The key for opening `input_path` with `elf.io.open_file` (container files or image stacks). 194 ndim: The number of spatial dimensions (2 or 3). By default inferred from the data: a 195 trailing axis of size 2, 3 or 4 is read as channels, anything else as a volume. Pass 2 196 to read a 3d array as a multi-channel image (channels-first or channels-last). 197 tile_shape: Shape of the tiles for tiled prediction, (y, x). For a 3d AIS or APG volume, 198 always the full (z, y, x) instead - it is chunked along z regardless of tiling, so the z 199 entry sets that chunk too (its own default when tile_shape is None). AMG segments a 200 volume slice by slice, so it stays (y, x) even for a 3d volume. By default the tiling of 201 already cached embeddings is reused, else images exceeding the in-plane size threshold 202 are tiled with the default tile shape and smaller ones run untiled. 203 halo: Overlap of the tiles, matching `tile_shape`'s axes. By default the overlap of already 204 cached embeddings is reused, else the default overlap whenever tiling is active. 205 mode: The AIS post-processing mode, 'sparse' (flow) or 'dense' (multicut). Ignored for AMG. 206 device: The device to run inference on. 207 verbose: Whether to print progress. 208 batch_size: The batch size used when running inference for multiple slices and / or tiles. 209 Defaults to one. Pass None to select it per device: from the free VRAM for the encoder, 210 and benchmarked for the (3d) decoder, which needs the headroom to probe. 211 devices: Inference device or devices. None uses all visible GPUs when the model is on CUDA. 212 num_prefetch_workers: Number of input reading and preprocessing threads. 213 num_write_workers: Number of output writing threads. 214 norm_bounds: Volumes only, for the decoder-based engines. Precomputed (lower, upper) percentile 215 bounds that normalize the input of the embeddings (see 216 `batched_inference._volume_normalization_bounds`), computed from the input when not given. 217 Pass the bounds of the whole volume when the input is only one block of it, so that a 218 block of mostly background is not stretched to its own bounds. 219 generate_kwargs: Additional post-processing parameters forwarded to the segmenter's `generate`. 220 221 Returns: 222 The instance segmentation, uint32 array. 223 """ 224 import shutil 225 import warnings 226 227 from ..util import load_image_data, make_temp_embedding_path, prepare_annotation_image 228 from .util import precompute_image_embeddings 229 from .instance_segmentation import amg_3d_segmentation, retile_instance_segmentation_generator 230 231 raw = input_path if isinstance(input_path, np.ndarray) else load_image_data(input_path, key=key) 232 # Normalize the input the same way the annotation tools do: squeeze singleton axes and move a 233 # channel axis to the trailing RGB position, so a channels-first (C, Y, X) array is read as an 234 # image rather than a volume. The spatial shape below is then the real (y, x) / (z, y, x), which 235 # is what the tiling decision and the segmenters need. 'ndim' disambiguates a 3d array; without 236 # it a trailing axis of size 2, 3 or 4 is taken as channels and anything else as a volume. 237 raw, ndim, is_rgb = prepare_annotation_image(raw, ndim=ndim) 238 spatial_shape = raw.shape[:-1] if is_rgb else raw.shape 239 240 # Decoder-based segmenters use this staged path. APG prompts instead of post-processing. 241 # Both tiling variants of an engine share this, so it is safe to read before the swap below. 242 is_decoder_based = getattr(segmenter, "_is_decoder_based", False) 243 244 # Tiling is decided from the image, which the caller has usually not read yet when it builds the 245 # segmenter, so swap in the tiling variant that matches. Only decoder-based inference on a volume 246 # takes the z axis too; AMG segments a volume slice by slice and stays in-plane. 247 requested_tile_shape = tile_shape 248 with_z_axis = ndim == 3 and is_decoder_based 249 tile_shape, halo, is_tiled = _resolve_tiling( 250 spatial_shape, tile_shape, halo, with_z_axis=with_z_axis, embedding_path=embedding_path, 251 ) 252 swapped = retile_instance_segmentation_generator(segmenter, is_tiled=is_tiled) 253 254 # A generator built by hand (not through the factory) records no build config, so it cannot be 255 # swapped. Handing a non-tiled one the tiling we picked ourselves would silently drop it - the 256 # in-plane entries are ignored there - and quietly produce the untiled result the default exists 257 # to avoid. Run untiled instead, and say why, rather than claiming a tiling that never happens. 258 if is_tiled and requested_tile_shape is None and getattr(swapped, "_generator_config", None) is None: 259 warnings.warn( 260 f"The image is {spatial_shape}, which would be tiled by default, but this segmenter was " 261 "built by hand and cannot be swapped for its tiled variant, so the image is segmented in " 262 "one piece. Build it with 'get_predictor_and_segmenter' (or pass 'tile_shape' yourself) " 263 "to tile." 264 ) 265 tile_shape, halo, is_tiled = None, None, False 266 segmenter = swapped 267 268 # Tiled APG encodes every block itself, unless there are cached embeddings to read them from. 269 precompute_embeddings = getattr(segmenter, "_precompute_embeddings_in_frontend", True) 270 takes_mode = getattr(segmenter, "_has_postprocessing_mode", True) 271 272 if is_decoder_based: 273 # One selection for the whole staged workflow; without either the segmenter's intent stands. 274 requested_devices = devices if devices is not None else device 275 inference_devices = segmenter._inference_devices(requested_devices) 276 277 # 3d stages the encoder and the decoder, so the z-halo is encoded once and the peaks do not add up. 278 # Every run decodes from embeddings, so that the result is the same as in the annotation tools. 279 image_embeddings = None 280 temp_embedding_path = None 281 try: 282 if embedding_path is not None or precompute_embeddings: 283 # The tool streams volumes and tiled images from the zarr. Only small 2d stays in memory. 284 is_streamed = ndim == 3 or tile_shape is not None 285 # Owned here, so a multi-input loop does not pile up one store per input. 286 effective_path = embedding_path 287 if effective_path is None and is_streamed: 288 temp_embedding_path = make_temp_embedding_path() 289 effective_path = temp_embedding_path 290 # The underlying SAM2 model, so no second backbone lands on the device. 291 emb_predictor = getattr(predictor, "model", predictor) if ndim == 3 else predictor 292 image_embeddings = precompute_image_embeddings( 293 emb_predictor, 294 raw, 295 save_path=effective_path, 296 ndim=ndim, 297 tile_shape=tile_shape, 298 halo=halo, 299 verbose=verbose, 300 lazy_loading=is_streamed, 301 batch_size=batch_size, 302 devices=inference_devices, 303 num_prefetch_workers=num_prefetch_workers, 304 num_write_workers=num_write_workers, 305 norm_bounds=norm_bounds if ndim == 3 else None, 306 ) 307 if precompute_embeddings: 308 segmenter.initialize( 309 raw, 310 ndim=ndim, 311 image_embeddings=image_embeddings, 312 tile_shape=tile_shape, 313 halo=halo, 314 batch_size=batch_size, 315 devices=inference_devices, 316 num_prefetch_workers=num_prefetch_workers, 317 num_write_workers=num_write_workers, 318 ) 319 else: 320 # The blocks use the tiling of the embeddings, so each block reads its tile. 321 segmenter.initialize( 322 raw, ndim=ndim, tile_shape=tile_shape, halo=halo, verbose=verbose, 323 image_embeddings=image_embeddings, 324 ) 325 if takes_mode: 326 segmentation = segmenter.generate(mode=mode, **generate_kwargs) 327 else: 328 segmentation = segmenter.generate(**generate_kwargs) 329 finally: 330 # Close all handles. Remove only a store created implicitly for this call. 331 if image_embeddings is not None: 332 image_embeddings.close() 333 image_embeddings = None 334 if temp_embedding_path is not None: 335 shutil.rmtree(temp_embedding_path, ignore_errors=True) 336 337 elif ndim == 3: 338 # Grid-based AMG on a volume: segment slice-by-slice and stitch across z. 339 segmentation = amg_3d_segmentation( 340 raw, segmenter, tile_shape=tile_shape, halo=halo, state_save_path=embedding_path, 341 verbose=verbose, **generate_kwargs, 342 ) 343 else: 344 # Grid-based AMG on a single 2d image. The segmenter computes and caches its own embeddings. 345 init_kwargs = {"tile_shape": tile_shape, "halo": halo} if tile_shape is not None else {} 346 segmenter.initialize(raw, save_path=embedding_path, verbose=verbose, **init_kwargs) 347 segmentation = segmenter.generate(**generate_kwargs) 348 349 if output_path is not None: 350 import imageio.v3 as imageio 351 imageio.imwrite(output_path, segmentation, compression="zlib") 352 if verbose: 353 print(f"The automatic segmentation results are stored at '{os.path.abspath(str(output_path))}'.") 354 355 return segmentation 356 357 358def automatic_tracking( 359 predictor, 360 segmenter, 361 input_path: Union[str, os.PathLike, np.ndarray], 362 output_path: Optional[Union[str, os.PathLike]] = None, 363 key: Optional[str] = None, 364 tile_shape: Optional[tuple] = None, 365 halo: Optional[tuple] = None, 366 mode: str = "sparse", 367 device: Optional[Union[str, torch.device]] = None, 368 gap_closing: Optional[int] = None, 369 min_time_extent: Optional[int] = None, 370 verbose: bool = True, 371 **generate_kwargs, 372): 373 """Run automatic tracking for a timeseries. 374 375 Each frame is segmented independently with the segmenter (`automatic_instance_segmentation`), the 376 per-frame results are relabeled to globally-unique ids, and the objects are linked across frames 377 with Trackastra (see `micro_sam.v1.multi_dimensional_segmentation.track_across_frames`). 378 379 Args: 380 predictor: The SAM2 predictor (see `get_predictor_and_segmenter`). 381 segmenter: The automatic instance segmentation generator (see `get_predictor_and_segmenter`). 382 input_path: The input timeseries, a filepath (tif / container with `key`) or a (T, Y, X) array. 383 output_path: Optional folder to save the tracking result in CTC format. 384 key: The key for opening `input_path` with `elf.io.open_file` (container files or image stacks). 385 tile_shape: Shape of the tiles for tiled per-frame prediction, (y, x). By default frames 386 exceeding the in-plane size threshold are tiled with the default tile shape. 387 halo: Overlap of the tiles for tiled per-frame prediction. By default the default overlap 388 is used whenever tiling is active. 389 mode: The AIS post-processing mode, 'sparse' (flow) or 'dense' (multicut). Ignored for AMG. 390 device: The device to run inference on. 391 gap_closing: If given, close gaps in the tracks over this many frames. 392 min_time_extent: If given, require tracks to span at least this many frames. 393 verbose: Whether to print progress. 394 generate_kwargs: Additional post-processing parameters forwarded to the segmenter's `generate`. 395 396 Returns: 397 The tracking result, a (T, Y, X) array where each object is labeled by its track id. 398 The lineages, encoding cell divisions. 399 """ 400 from tqdm import trange 401 402 from ..util import load_image_data 403 from ..v1.multi_dimensional_segmentation import track_across_frames 404 from .instance_segmentation import retile_instance_segmentation_generator 405 406 timeseries = input_path if isinstance(input_path, np.ndarray) else load_image_data(input_path, key=key) 407 if timeseries.ndim != 3: 408 raise ValueError(f"Automatic tracking expects a (T, Y, X) timeseries, got shape {timeseries.shape}.") 409 410 # Every frame has the same shape, so resolve the tiling and swap the segmenter once here rather 411 # than per frame, then pass the resolved settings down. 412 tile_shape, halo, is_tiled = _resolve_tiling(timeseries.shape[1:], tile_shape, halo, with_z_axis=False) 413 segmenter = retile_instance_segmentation_generator(segmenter, is_tiled=is_tiled) 414 # None means "default" to the per-frame call, so keep an untiled run explicit. 415 if not is_tiled: 416 tile_shape, halo = (0, 0), (0, 0) 417 418 # Segment every frame independently and relabel so ids do not overlap across frames. 419 segmentation = np.zeros(timeseries.shape, dtype="uint32") 420 offset = 0 421 for t in trange(timeseries.shape[0], desc="Segment frames", disable=not verbose): 422 frame_seg = automatic_instance_segmentation( 423 predictor=predictor, segmenter=segmenter, input_path=timeseries[t], ndim=2, 424 tile_shape=tile_shape, halo=halo, mode=mode, device=device, verbose=False, **generate_kwargs, 425 ) 426 max_id = int(frame_seg.max()) 427 if max_id == 0: 428 continue 429 frame_seg[frame_seg != 0] += offset 430 offset += max_id 431 segmentation[t] = frame_seg 432 433 segmentation, lineage = track_across_frames( 434 timeseries=timeseries, segmentation=segmentation, gap_closing=gap_closing, 435 min_time_extent=min_time_extent, verbose=verbose, output_folder=output_path, 436 ) 437 return segmentation, lineage
23def get_predictor_and_segmenter( 24 model_type: str = DEFAULT_MODEL, 25 checkpoint: Optional[Union[str, os.PathLike]] = None, 26 device: Optional[Union[str, torch.device]] = None, 27 segmentation_mode: Optional[str] = None, 28 is_tiled: bool = False, 29 ndim: int = 2, 30 **kwargs, 31) -> Tuple[object, object]: 32 """Get the SAM2 predictor and the generator for automatic instance segmentation. 33 34 Automatic segmentation with SAM2 uses one of three engines, selected via `segmentation_mode`: 35 the decoder-based AIS (with a UniSAM2 decoder from a finetuned model, e.g. 'hvit_t_cells', or a 36 `checkpoint`), the grid-based AMG (no decoder), or APG, which derives candidates from the decoder 37 and prompts the interactive branch with them. By default AIS is used when a decoder is available 38 and AMG otherwise. APG costs several forward passes per image, so it is opt-in. 39 40 Args: 41 model_type: The SAM2 model. Either a finetuned model with a registered decoder (see 42 `micro_sam.v2.util.get_model_names`) or a base backbone combined with `checkpoint`. 43 checkpoint: Optional path to a custom checkpoint. It defines the SAM2 model, and the UniSAM2 decoder. 44 The model size is read from the checkpoint. 45 device: The torch device. By default the best available device is selected. 46 segmentation_mode: The segmentation engine, one of 'amg', 'ais' or 'apg'. By default 'ais' is 47 used if a decoder is available, otherwise 'amg'. 48 is_tiled: Whether to return a segmenter for in-plane (xy) tiled segmentation. 49 ndim: The number of spatial dimensions the segmenter is built for. Only APG needs to know: 50 it propagates its prompts through a volume, which needs the video predictor. 51 kwargs: Keyword arguments for the automatic mask generation (AMG) class. 52 53 Returns: 54 The SAM2 predictor (used to precompute embeddings) and the automatic segmentation generator. 55 56 Raises: 57 NoDecoderError: If `checkpoint` has no decoder, because it was trained for interactive segmentation 58 only, and `segmentation_mode` is not 'amg'. 59 """ 60 from ..util import get_device, _get_sam_model 61 from .instance_segmentation import NoDecoderError, get_decoder, get_instance_segmentation_generator 62 63 # Kept apart from the placement below, so 'use all visible GPUs' stays distinct from one device. 64 requested_device = device 65 model_device = get_device(device) 66 67 # Volumetric APG propagates its prompts, so it needs the video predictor, which also encodes. 68 predictor, _ = _get_sam_model( 69 model_type=model_type, ndim=3 if (segmentation_mode == "apg" and ndim == 3) else 2, 70 device=model_device, checkpoint_path=checkpoint, decoder_path=None, use_cli=True, 71 ) 72 # A custom checkpoint can hold another backbone than the name. 73 model_type = predictor.model_type 74 75 # 'ais' and 'apg' require a decoder, 'amg' never uses one, and 'auto' prefers one if it loads. 76 decoder = None 77 if segmentation_mode != "amg": 78 try: 79 # Reuse the predictor's encoder, so no second SAM2 backbone is built. 80 encoder = getattr(getattr(predictor, "model", predictor), "image_encoder", None) 81 decoder = get_decoder(model_type, checkpoint=checkpoint, device=model_device, encoder=encoder) 82 except NoDecoderError: 83 # A custom checkpoint without decoder was trained for interactive segmentation only. 84 raise 85 except Exception as e: 86 if segmentation_mode in ("ais", "apg"): 87 raise 88 print(f"Could not load a UniSAM2 decoder for '{model_type}', falling back to AMG: {e}") 89 90 # An explicit mode is honored; only the automatic choice falls back to what the decoder allows. 91 if segmentation_mode is None: 92 engine = "ais" if decoder is not None else "amg" 93 else: 94 engine = segmentation_mode 95 if engine == "amg": # Tags the cached embeddings, so the AMG state is not reused across models. 96 kwargs.setdefault("model_type", model_type) 97 segmenter = get_instance_segmentation_generator( 98 # The video predictor is the SAM2 model itself, an image predictor wraps one. 99 model=getattr(predictor, "model", predictor), decoder=decoder, is_tiled=is_tiled, 100 segmentation_mode=engine, device=model_device, inference_device=requested_device, ndim=ndim, **kwargs, 101 ) 102 return predictor, segmenter
Get the SAM2 predictor and the generator for automatic instance segmentation.
Automatic segmentation with SAM2 uses one of three engines, selected via segmentation_mode:
the decoder-based AIS (with a UniSAM2 decoder from a finetuned model, e.g. 'hvit_t_cells', or a
checkpoint), the grid-based AMG (no decoder), or APG, which derives candidates from the decoder
and prompts the interactive branch with them. By default AIS is used when a decoder is available
and AMG otherwise. APG costs several forward passes per image, so it is opt-in.
Arguments:
- model_type: The SAM2 model. Either a finetuned model with a registered decoder (see
micro_sam.v2.util.get_model_names) or a base backbone combined withcheckpoint. - checkpoint: Optional path to a custom checkpoint. It defines the SAM2 model, and the UniSAM2 decoder. The model size is read from the checkpoint.
- device: The torch device. By default the best available device is selected.
- segmentation_mode: The segmentation engine, one of 'amg', 'ais' or 'apg'. By default 'ais' is used if a decoder is available, otherwise 'amg'.
- is_tiled: Whether to return a segmenter for in-plane (xy) tiled segmentation.
- ndim: The number of spatial dimensions the segmenter is built for. Only APG needs to know: it propagates its prompts through a volume, which needs the video predictor.
- kwargs: Keyword arguments for the automatic mask generation (AMG) class.
Returns:
The SAM2 predictor (used to precompute embeddings) and the automatic segmentation generator.
Raises:
- NoDecoderError: If
checkpointhas no decoder, because it was trained for interactive segmentation only, andsegmentation_modeis not 'amg'.
158def automatic_instance_segmentation( 159 predictor, 160 segmenter, 161 input_path: Union[str, os.PathLike, np.ndarray], 162 output_path: Optional[Union[str, os.PathLike]] = None, 163 embedding_path: Optional[Union[str, os.PathLike]] = None, 164 model_type: str = DEFAULT_MODEL, 165 checkpoint: Optional[Union[str, os.PathLike]] = None, 166 key: Optional[str] = None, 167 ndim: Optional[int] = None, 168 tile_shape: Optional[tuple] = None, 169 halo: Optional[tuple] = None, 170 mode: str = "sparse", 171 device: Optional[Union[str, torch.device]] = None, 172 verbose: bool = True, 173 batch_size: Optional[int] = 1, 174 devices: Devices = None, 175 num_prefetch_workers: int = 4, 176 num_write_workers: int = 2, 177 norm_bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 178 **generate_kwargs, 179) -> np.ndarray: 180 """Run automatic instance segmentation for a single input and save the result. 181 182 Args: 183 predictor: The SAM2 predictor (see `get_predictor_and_segmenter`). The decoder-based engines 184 use it to precompute the image embeddings. 185 segmenter: The automatic instance segmentation generator (see `get_predictor_and_segmenter`). 186 input_path: The input image, either a filepath (e.g. tif or a container with `key`) or an array. 187 output_path: Optional path to save the segmentation as a tif file. 188 embedding_path: The optional path to cache the image embeddings. The function saves the 189 embeddings there, and it uses them again in a later call. The decoder-based engines always 190 precompute the embeddings. Without this path, they keep the embeddings in memory (untiled 191 2d) or in an ephemeral cache. Without this path, tiled APG encodes each tile / block itself. 192 model_type: Retained for API compatibility; the loaded predictor determines the embedding model. 193 checkpoint: Retained for API compatibility; the loaded predictor already contains its weights. 194 key: The key for opening `input_path` with `elf.io.open_file` (container files or image stacks). 195 ndim: The number of spatial dimensions (2 or 3). By default inferred from the data: a 196 trailing axis of size 2, 3 or 4 is read as channels, anything else as a volume. Pass 2 197 to read a 3d array as a multi-channel image (channels-first or channels-last). 198 tile_shape: Shape of the tiles for tiled prediction, (y, x). For a 3d AIS or APG volume, 199 always the full (z, y, x) instead - it is chunked along z regardless of tiling, so the z 200 entry sets that chunk too (its own default when tile_shape is None). AMG segments a 201 volume slice by slice, so it stays (y, x) even for a 3d volume. By default the tiling of 202 already cached embeddings is reused, else images exceeding the in-plane size threshold 203 are tiled with the default tile shape and smaller ones run untiled. 204 halo: Overlap of the tiles, matching `tile_shape`'s axes. By default the overlap of already 205 cached embeddings is reused, else the default overlap whenever tiling is active. 206 mode: The AIS post-processing mode, 'sparse' (flow) or 'dense' (multicut). Ignored for AMG. 207 device: The device to run inference on. 208 verbose: Whether to print progress. 209 batch_size: The batch size used when running inference for multiple slices and / or tiles. 210 Defaults to one. Pass None to select it per device: from the free VRAM for the encoder, 211 and benchmarked for the (3d) decoder, which needs the headroom to probe. 212 devices: Inference device or devices. None uses all visible GPUs when the model is on CUDA. 213 num_prefetch_workers: Number of input reading and preprocessing threads. 214 num_write_workers: Number of output writing threads. 215 norm_bounds: Volumes only, for the decoder-based engines. Precomputed (lower, upper) percentile 216 bounds that normalize the input of the embeddings (see 217 `batched_inference._volume_normalization_bounds`), computed from the input when not given. 218 Pass the bounds of the whole volume when the input is only one block of it, so that a 219 block of mostly background is not stretched to its own bounds. 220 generate_kwargs: Additional post-processing parameters forwarded to the segmenter's `generate`. 221 222 Returns: 223 The instance segmentation, uint32 array. 224 """ 225 import shutil 226 import warnings 227 228 from ..util import load_image_data, make_temp_embedding_path, prepare_annotation_image 229 from .util import precompute_image_embeddings 230 from .instance_segmentation import amg_3d_segmentation, retile_instance_segmentation_generator 231 232 raw = input_path if isinstance(input_path, np.ndarray) else load_image_data(input_path, key=key) 233 # Normalize the input the same way the annotation tools do: squeeze singleton axes and move a 234 # channel axis to the trailing RGB position, so a channels-first (C, Y, X) array is read as an 235 # image rather than a volume. The spatial shape below is then the real (y, x) / (z, y, x), which 236 # is what the tiling decision and the segmenters need. 'ndim' disambiguates a 3d array; without 237 # it a trailing axis of size 2, 3 or 4 is taken as channels and anything else as a volume. 238 raw, ndim, is_rgb = prepare_annotation_image(raw, ndim=ndim) 239 spatial_shape = raw.shape[:-1] if is_rgb else raw.shape 240 241 # Decoder-based segmenters use this staged path. APG prompts instead of post-processing. 242 # Both tiling variants of an engine share this, so it is safe to read before the swap below. 243 is_decoder_based = getattr(segmenter, "_is_decoder_based", False) 244 245 # Tiling is decided from the image, which the caller has usually not read yet when it builds the 246 # segmenter, so swap in the tiling variant that matches. Only decoder-based inference on a volume 247 # takes the z axis too; AMG segments a volume slice by slice and stays in-plane. 248 requested_tile_shape = tile_shape 249 with_z_axis = ndim == 3 and is_decoder_based 250 tile_shape, halo, is_tiled = _resolve_tiling( 251 spatial_shape, tile_shape, halo, with_z_axis=with_z_axis, embedding_path=embedding_path, 252 ) 253 swapped = retile_instance_segmentation_generator(segmenter, is_tiled=is_tiled) 254 255 # A generator built by hand (not through the factory) records no build config, so it cannot be 256 # swapped. Handing a non-tiled one the tiling we picked ourselves would silently drop it - the 257 # in-plane entries are ignored there - and quietly produce the untiled result the default exists 258 # to avoid. Run untiled instead, and say why, rather than claiming a tiling that never happens. 259 if is_tiled and requested_tile_shape is None and getattr(swapped, "_generator_config", None) is None: 260 warnings.warn( 261 f"The image is {spatial_shape}, which would be tiled by default, but this segmenter was " 262 "built by hand and cannot be swapped for its tiled variant, so the image is segmented in " 263 "one piece. Build it with 'get_predictor_and_segmenter' (or pass 'tile_shape' yourself) " 264 "to tile." 265 ) 266 tile_shape, halo, is_tiled = None, None, False 267 segmenter = swapped 268 269 # Tiled APG encodes every block itself, unless there are cached embeddings to read them from. 270 precompute_embeddings = getattr(segmenter, "_precompute_embeddings_in_frontend", True) 271 takes_mode = getattr(segmenter, "_has_postprocessing_mode", True) 272 273 if is_decoder_based: 274 # One selection for the whole staged workflow; without either the segmenter's intent stands. 275 requested_devices = devices if devices is not None else device 276 inference_devices = segmenter._inference_devices(requested_devices) 277 278 # 3d stages the encoder and the decoder, so the z-halo is encoded once and the peaks do not add up. 279 # Every run decodes from embeddings, so that the result is the same as in the annotation tools. 280 image_embeddings = None 281 temp_embedding_path = None 282 try: 283 if embedding_path is not None or precompute_embeddings: 284 # The tool streams volumes and tiled images from the zarr. Only small 2d stays in memory. 285 is_streamed = ndim == 3 or tile_shape is not None 286 # Owned here, so a multi-input loop does not pile up one store per input. 287 effective_path = embedding_path 288 if effective_path is None and is_streamed: 289 temp_embedding_path = make_temp_embedding_path() 290 effective_path = temp_embedding_path 291 # The underlying SAM2 model, so no second backbone lands on the device. 292 emb_predictor = getattr(predictor, "model", predictor) if ndim == 3 else predictor 293 image_embeddings = precompute_image_embeddings( 294 emb_predictor, 295 raw, 296 save_path=effective_path, 297 ndim=ndim, 298 tile_shape=tile_shape, 299 halo=halo, 300 verbose=verbose, 301 lazy_loading=is_streamed, 302 batch_size=batch_size, 303 devices=inference_devices, 304 num_prefetch_workers=num_prefetch_workers, 305 num_write_workers=num_write_workers, 306 norm_bounds=norm_bounds if ndim == 3 else None, 307 ) 308 if precompute_embeddings: 309 segmenter.initialize( 310 raw, 311 ndim=ndim, 312 image_embeddings=image_embeddings, 313 tile_shape=tile_shape, 314 halo=halo, 315 batch_size=batch_size, 316 devices=inference_devices, 317 num_prefetch_workers=num_prefetch_workers, 318 num_write_workers=num_write_workers, 319 ) 320 else: 321 # The blocks use the tiling of the embeddings, so each block reads its tile. 322 segmenter.initialize( 323 raw, ndim=ndim, tile_shape=tile_shape, halo=halo, verbose=verbose, 324 image_embeddings=image_embeddings, 325 ) 326 if takes_mode: 327 segmentation = segmenter.generate(mode=mode, **generate_kwargs) 328 else: 329 segmentation = segmenter.generate(**generate_kwargs) 330 finally: 331 # Close all handles. Remove only a store created implicitly for this call. 332 if image_embeddings is not None: 333 image_embeddings.close() 334 image_embeddings = None 335 if temp_embedding_path is not None: 336 shutil.rmtree(temp_embedding_path, ignore_errors=True) 337 338 elif ndim == 3: 339 # Grid-based AMG on a volume: segment slice-by-slice and stitch across z. 340 segmentation = amg_3d_segmentation( 341 raw, segmenter, tile_shape=tile_shape, halo=halo, state_save_path=embedding_path, 342 verbose=verbose, **generate_kwargs, 343 ) 344 else: 345 # Grid-based AMG on a single 2d image. The segmenter computes and caches its own embeddings. 346 init_kwargs = {"tile_shape": tile_shape, "halo": halo} if tile_shape is not None else {} 347 segmenter.initialize(raw, save_path=embedding_path, verbose=verbose, **init_kwargs) 348 segmentation = segmenter.generate(**generate_kwargs) 349 350 if output_path is not None: 351 import imageio.v3 as imageio 352 imageio.imwrite(output_path, segmentation, compression="zlib") 353 if verbose: 354 print(f"The automatic segmentation results are stored at '{os.path.abspath(str(output_path))}'.") 355 356 return segmentation
Run automatic instance segmentation for a single input and save the result.
Arguments:
- predictor: The SAM2 predictor (see
get_predictor_and_segmenter). The decoder-based engines use it to precompute the image embeddings. - segmenter: The automatic instance segmentation generator (see
get_predictor_and_segmenter). - input_path: The input image, either a filepath (e.g. tif or a container with
key) or an array. - output_path: Optional path to save the segmentation as a tif file.
- embedding_path: The optional path to cache the image embeddings. The function saves the embeddings there, and it uses them again in a later call. The decoder-based engines always precompute the embeddings. Without this path, they keep the embeddings in memory (untiled 2d) or in an ephemeral cache. Without this path, tiled APG encodes each tile / block itself.
- model_type: Retained for API compatibility; the loaded predictor determines the embedding model.
- checkpoint: Retained for API compatibility; the loaded predictor already contains its weights.
- key: The key for opening
input_pathwithelf.io.open_file(container files or image stacks). - ndim: The number of spatial dimensions (2 or 3). By default inferred from the data: a trailing axis of size 2, 3 or 4 is read as channels, anything else as a volume. Pass 2 to read a 3d array as a multi-channel image (channels-first or channels-last).
- tile_shape: Shape of the tiles for tiled prediction, (y, x). For a 3d AIS or APG volume, always the full (z, y, x) instead - it is chunked along z regardless of tiling, so the z entry sets that chunk too (its own default when tile_shape is None). AMG segments a volume slice by slice, so it stays (y, x) even for a 3d volume. By default the tiling of already cached embeddings is reused, else images exceeding the in-plane size threshold are tiled with the default tile shape and smaller ones run untiled.
- halo: Overlap of the tiles, matching
tile_shape's axes. By default the overlap of already cached embeddings is reused, else the default overlap whenever tiling is active. - mode: The AIS post-processing mode, 'sparse' (flow) or 'dense' (multicut). Ignored for AMG.
- device: The device to run inference on.
- verbose: Whether to print progress.
- batch_size: The batch size used when running inference for multiple slices and / or tiles. Defaults to one. Pass None to select it per device: from the free VRAM for the encoder, and benchmarked for the (3d) decoder, which needs the headroom to probe.
- devices: Inference device or devices. None uses all visible GPUs when the model is on CUDA.
- num_prefetch_workers: Number of input reading and preprocessing threads.
- num_write_workers: Number of output writing threads.
- norm_bounds: Volumes only, for the decoder-based engines. Precomputed (lower, upper) percentile
bounds that normalize the input of the embeddings (see
batched_inference._volume_normalization_bounds), computed from the input when not given. Pass the bounds of the whole volume when the input is only one block of it, so that a block of mostly background is not stretched to its own bounds. - generate_kwargs: Additional post-processing parameters forwarded to the segmenter's
generate.
Returns:
The instance segmentation, uint32 array.
359def automatic_tracking( 360 predictor, 361 segmenter, 362 input_path: Union[str, os.PathLike, np.ndarray], 363 output_path: Optional[Union[str, os.PathLike]] = None, 364 key: Optional[str] = None, 365 tile_shape: Optional[tuple] = None, 366 halo: Optional[tuple] = None, 367 mode: str = "sparse", 368 device: Optional[Union[str, torch.device]] = None, 369 gap_closing: Optional[int] = None, 370 min_time_extent: Optional[int] = None, 371 verbose: bool = True, 372 **generate_kwargs, 373): 374 """Run automatic tracking for a timeseries. 375 376 Each frame is segmented independently with the segmenter (`automatic_instance_segmentation`), the 377 per-frame results are relabeled to globally-unique ids, and the objects are linked across frames 378 with Trackastra (see `micro_sam.v1.multi_dimensional_segmentation.track_across_frames`). 379 380 Args: 381 predictor: The SAM2 predictor (see `get_predictor_and_segmenter`). 382 segmenter: The automatic instance segmentation generator (see `get_predictor_and_segmenter`). 383 input_path: The input timeseries, a filepath (tif / container with `key`) or a (T, Y, X) array. 384 output_path: Optional folder to save the tracking result in CTC format. 385 key: The key for opening `input_path` with `elf.io.open_file` (container files or image stacks). 386 tile_shape: Shape of the tiles for tiled per-frame prediction, (y, x). By default frames 387 exceeding the in-plane size threshold are tiled with the default tile shape. 388 halo: Overlap of the tiles for tiled per-frame prediction. By default the default overlap 389 is used whenever tiling is active. 390 mode: The AIS post-processing mode, 'sparse' (flow) or 'dense' (multicut). Ignored for AMG. 391 device: The device to run inference on. 392 gap_closing: If given, close gaps in the tracks over this many frames. 393 min_time_extent: If given, require tracks to span at least this many frames. 394 verbose: Whether to print progress. 395 generate_kwargs: Additional post-processing parameters forwarded to the segmenter's `generate`. 396 397 Returns: 398 The tracking result, a (T, Y, X) array where each object is labeled by its track id. 399 The lineages, encoding cell divisions. 400 """ 401 from tqdm import trange 402 403 from ..util import load_image_data 404 from ..v1.multi_dimensional_segmentation import track_across_frames 405 from .instance_segmentation import retile_instance_segmentation_generator 406 407 timeseries = input_path if isinstance(input_path, np.ndarray) else load_image_data(input_path, key=key) 408 if timeseries.ndim != 3: 409 raise ValueError(f"Automatic tracking expects a (T, Y, X) timeseries, got shape {timeseries.shape}.") 410 411 # Every frame has the same shape, so resolve the tiling and swap the segmenter once here rather 412 # than per frame, then pass the resolved settings down. 413 tile_shape, halo, is_tiled = _resolve_tiling(timeseries.shape[1:], tile_shape, halo, with_z_axis=False) 414 segmenter = retile_instance_segmentation_generator(segmenter, is_tiled=is_tiled) 415 # None means "default" to the per-frame call, so keep an untiled run explicit. 416 if not is_tiled: 417 tile_shape, halo = (0, 0), (0, 0) 418 419 # Segment every frame independently and relabel so ids do not overlap across frames. 420 segmentation = np.zeros(timeseries.shape, dtype="uint32") 421 offset = 0 422 for t in trange(timeseries.shape[0], desc="Segment frames", disable=not verbose): 423 frame_seg = automatic_instance_segmentation( 424 predictor=predictor, segmenter=segmenter, input_path=timeseries[t], ndim=2, 425 tile_shape=tile_shape, halo=halo, mode=mode, device=device, verbose=False, **generate_kwargs, 426 ) 427 max_id = int(frame_seg.max()) 428 if max_id == 0: 429 continue 430 frame_seg[frame_seg != 0] += offset 431 offset += max_id 432 segmentation[t] = frame_seg 433 434 segmentation, lineage = track_across_frames( 435 timeseries=timeseries, segmentation=segmentation, gap_closing=gap_closing, 436 min_time_extent=min_time_extent, verbose=verbose, output_folder=output_path, 437 ) 438 return segmentation, lineage
Run automatic tracking for a timeseries.
Each frame is segmented independently with the segmenter (automatic_instance_segmentation), the
per-frame results are relabeled to globally-unique ids, and the objects are linked across frames
with Trackastra (see micro_sam.v1.multi_dimensional_segmentation.track_across_frames).
Arguments:
- predictor: The SAM2 predictor (see
get_predictor_and_segmenter). - segmenter: The automatic instance segmentation generator (see
get_predictor_and_segmenter). - input_path: The input timeseries, a filepath (tif / container with
key) or a (T, Y, X) array. - output_path: Optional folder to save the tracking result in CTC format.
- key: The key for opening
input_pathwithelf.io.open_file(container files or image stacks). - tile_shape: Shape of the tiles for tiled per-frame prediction, (y, x). By default frames exceeding the in-plane size threshold are tiled with the default tile shape.
- halo: Overlap of the tiles for tiled per-frame prediction. By default the default overlap is used whenever tiling is active.
- mode: The AIS post-processing mode, 'sparse' (flow) or 'dense' (multicut). Ignored for AMG.
- device: The device to run inference on.
- gap_closing: If given, close gaps in the tracks over this many frames.
- min_time_extent: If given, require tracks to span at least this many frames.
- verbose: Whether to print progress.
- generate_kwargs: Additional post-processing parameters forwarded to the segmenter's
generate.
Returns:
The tracking result, a (T, Y, X) array where each object is labeled by its track id. The lineages, encoding cell divisions.