micro_sam.util

Helper functions for downloading Segment Anything models and predicting image embeddings.

   1"""Helper functions for downloading Segment Anything models and predicting image embeddings.
   2"""
   3
   4# Must run before segment_anything / torchvision import triton.
   5from . import _triton_guard  # noqa
   6
   7import os
   8import json
   9import uuid
  10import pooch
  11import types
  12import atexit
  13import pickle
  14import shutil
  15import xxhash
  16import hashlib
  17import warnings
  18from pathlib import Path
  19from abc import ABC, abstractmethod
  20from collections import OrderedDict
  21from typing import Any, Dict, List, Optional, Tuple, Union
  22
  23import z5py
  24import zarr
  25import numpy as np
  26import imageio.v3 as imageio
  27import segment_anything.utils.amg as amg_utils
  28
  29from skimage.measure import regionprops
  30from skimage.segmentation import find_boundaries
  31
  32import torch
  33from torchvision.ops.boxes import batched_nms
  34
  35from elf.io import open_file
  36import elf.parallel as parallel_impl
  37
  38from bioimage_cpp.distance import distance_transform
  39from bioimage_cpp.segmentation import label, relabel_sequential
  40
  41from .__version__ import __version__
  42
  43try:
  44    # Avoid import warnigns from mobile_sam
  45    with warnings.catch_warnings():
  46        warnings.simplefilter("ignore")
  47        from mobile_sam import sam_model_registry, SamPredictor  # noqa
  48    VIT_T_SUPPORT = True
  49except ImportError:
  50    from segment_anything import sam_model_registry, SamPredictor  # noqa
  51    VIT_T_SUPPORT = False
  52
  53from tqdm import tqdm as _std_tqdm
  54try:
  55    from napari.utils import progress as tqdm
  56except ImportError:
  57    tqdm = _std_tqdm
  58
  59# This is the default model used in micro_sam
  60# Currently it is set to vit_b_lm
  61DEFAULT_SAM1_MODEL = "vit_b_lm"
  62
  63# The valid model types. Each type corresponds to the architecture of the
  64# vision transformer used within SAM.
  65SAM1_MODEL_TYPES = ("vit_l", "vit_b", "vit_h", "vit_t")
  66
  67
  68ImageEmbeddings = Dict[str, Any]
  69"""@private"""
  70
  71
  72class AutoSegBase(ABC):
  73    """Common interface for automatic-segmentation generators.
  74
  75    Unifies the grid-based mask generators (`micro_sam.v1.instance_segmentation.AMGBase` and its
  76    subclasses) and the decoder-based instance segmentation
  77    (`micro_sam.v1.instance_segmentation.InstanceSegmentationWithDecoder` and its subclasses), for
  78    both SAM1 and SAM2: all of them are initialized on an image, produce an instance segmentation
  79    via `generate`, and cache / restore their expensive intermediate state via
  80    `get_state` / `set_state`. It lives here, next to the other shared types, so that it can be
  81    referenced in annotations without importing an implementation (and with it the training stack).
  82    """
  83
  84    @property
  85    def is_initialized(self) -> bool:
  86        """Whether `initialize` ran and the state is available."""
  87        return self._is_initialized
  88
  89    @abstractmethod
  90    def initialize(self, *args, **kwargs) -> None:
  91        """Compute and store the (expensive) state needed by `generate`."""
  92
  93    @abstractmethod
  94    def generate(self, *args, **kwargs):
  95        """Produce the instance segmentation from the initialized state."""
  96
  97    @abstractmethod
  98    def get_state(self) -> Dict[str, Any]:
  99        """Return the cached state so it can be serialized and later restored."""
 100
 101    @abstractmethod
 102    def set_state(self, state: Dict[str, Any]) -> None:
 103        """Restore a state produced by `get_state`."""
 104
 105    @abstractmethod
 106    def clear_state(self) -> None:
 107        """Clear the cached state."""
 108
 109
 110def get_cache_directory() -> Path:
 111    """Get the micro-sam cache directory location.
 112
 113    This is the top level cache directory for micro-sam models, sample data and temporary embeddings.
 114    Users can set the MICROSAM_CACHEDIR environment variable for a custom cache directory.
 115    The function reads the variable on every call, so updates take effect immediately.
 116
 117    Returns:
 118        The cache directory.
 119    """
 120    cache_directory = os.environ.get("MICROSAM_CACHEDIR") or pooch.os_cache("micro_sam")
 121    return Path(os.path.expanduser(cache_directory))
 122
 123
 124def get_model_cache_directory(name: Optional[str] = None) -> Path:
 125    """Get the directory where micro-sam stores downloaded model weights.
 126
 127    All model downloads go to the 'models' folder of the micro-sam cache directory, so that each
 128    model is stored only once. The SAM, micro-sam, SAM2 and micro-sam2 checkpoints are files
 129    directly in this folder. The weights of third-party models (e.g. 'anyup', 'dino/v2', 'dino/v3',
 130    'uni', 'sam3', 'trackastra') go to a subfolder.
 131
 132    Args:
 133        name: The optional subfolder for a third-party model.
 134
 135    Returns:
 136        The model cache directory.
 137    """
 138    model_directory = get_cache_directory() / "models"
 139    return model_directory if name is None else model_directory / name
 140
 141
 142def make_temp_embedding_path() -> str:
 143    """Create a fresh ephemeral on-disk zarr path for streaming image embeddings.
 144
 145    Used when no explicit embedding save path is given: caching to disk (under the micro-sam cache
 146    directory, honoring MICROSAM_CACHEDIR) instead of holding the whole volume in RAM keeps memory
 147    bounded on large volumes / tiled images. The cache is disk-backed rather than in /tmp, which is
 148    tmpfs (RAM) on many systems. The caller owns eager cleanup; the returned path is also removed on
 149    process exit.
 150    """
 151    parent = get_cache_directory() / "tmp_embeddings"
 152    parent.mkdir(parents=True, exist_ok=True)
 153    path = str(parent / f"{uuid.uuid4().hex}.zarr")
 154    atexit.register(shutil.rmtree, path, ignore_errors=True)
 155    return path
 156
 157
 158#
 159# Functionality for model download and export
 160#
 161
 162
 163def _get_default_device():
 164    # check that we're in CI and use the CPU if we are
 165    # otherwise the tests may run out of memory on MAC if MPS is used.
 166    if os.getenv("GITHUB_ACTIONS") == "true":
 167        return "cpu"
 168    # Use cuda enabled gpu if it's available.
 169    if torch.cuda.is_available():
 170        device = "cuda"
 171    # As second priority use mps.
 172    # See https://pytorch.org/docs/stable/notes/mps.html for details.
 173    # Silent: the GUI resolves the device on every settings change. 'micro_sam info' reports it.
 174    elif torch.backends.mps.is_available() and torch.backends.mps.is_built():
 175        device = "mps"
 176    # Use the CPU as fallback.
 177    else:
 178        device = "cpu"
 179    return device
 180
 181
 182def _has_nvidia_gpu() -> bool:
 183    gpu_dir = "/proc/driver/nvidia/gpus"
 184    if os.path.isdir(gpu_dir):
 185        return len(os.listdir(gpu_dir)) > 0
 186    nvidia_smi = shutil.which("nvidia-smi")
 187    if nvidia_smi is None:
 188        return False
 189    import subprocess
 190    try:
 191        result = subprocess.run([nvidia_smi, "-L"], capture_output=True, text=True, timeout=10)
 192    except (OSError, subprocess.SubprocessError):
 193        return False
 194    return result.returncode == 0 and "GPU" in result.stdout
 195
 196
 197def get_gpu_setup_warning() -> Optional[str]:
 198    """Check if the computer has an NVIDIA GPU that PyTorch cannot use.
 199
 200    Package managers sometimes install a CPU-only PyTorch on computers with an NVIDIA GPU.
 201    micro_sam then runs on the CPU without an error, which is much slower.
 202
 203    Returns:
 204        A warning that explains the problem and the fix, or None if PyTorch can use the GPU or there is no NVIDIA GPU.
 205    """
 206    if torch.cuda.is_available() or not _has_nvidia_gpu():
 207        return None
 208    if torch.version.cuda is None:
 209        return (
 210            "This computer has an NVIDIA GPU, but the installed PyTorch is a CPU-only build, so micro_sam runs on the "
 211            "CPU. To use the GPU, install micro_sam with a CUDA build of PyTorch, e.g. by adding \"pytorch=*=cuda*\" "
 212            "to the conda / mamba command. See https://computational-cell-analytics.github.io/micro-sam for details."
 213        )
 214    return (
 215        f"This computer has an NVIDIA GPU, but PyTorch (built for CUDA {torch.version.cuda}) cannot use it, so "
 216        "micro_sam runs on the CPU. The NVIDIA driver may be too old for this PyTorch build. Update the driver, or "
 217        "install a PyTorch build for an older CUDA version, e.g. by adding \"cuda-version=12\" to the conda / mamba "
 218        "command."
 219    )
 220
 221
 222def device_type(device: Union[str, torch.device]) -> str:
 223    """Get the device type ('cpu', 'cuda' or 'mps'), ignoring any device index.
 224
 225    Torch reports accelerators with an index (e.g. 'mps:0'), so comparing 'str(device)' against
 226    'mps' or 'cuda' silently fails. Compare against this instead.
 227
 228    Args:
 229        device: The device, as a string or torch.device.
 230
 231    Returns:
 232        The device type.
 233    """
 234    return torch.device(device).type
 235
 236
 237def _configure_mps_memory(device: Union[str, torch.device]) -> None:
 238    """Disable the MPS memory watermark so 3d automatic segmentation does not hit a premature OOM.
 239
 240    MPS's default watermark rejects allocations that would still fit in unified memory. '0.0' disables
 241    it. We set it only when unset (so a user-provided value is kept) and it must run before the first
 242    MPS allocation to apply.
 243    """
 244    try:
 245        is_mps = device_type(device) == "mps"
 246    except (RuntimeError, TypeError):
 247        is_mps = False
 248    if is_mps and "PYTORCH_MPS_HIGH_WATERMARK_RATIO" not in os.environ:
 249        os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
 250        print("Lifted the MPS memory limit for large 3d segmentation. This can use swap on low-memory Macs.")
 251
 252
 253def get_device(device: Optional[Union[str, torch.device]] = None) -> Union[str, torch.device]:
 254    """Get the torch device.
 255
 256    If no device is passed the default device for your system is used.
 257    Else it will be checked if the device you have passed is supported.
 258
 259    Args:
 260        device: The input device. By default, selects the best available device supports.
 261
 262    Returns:
 263        The device.
 264    """
 265    if device is None or device == "auto":
 266        device = _get_default_device()
 267    else:
 268        try:
 269            requested_type = device_type(device)
 270        except (RuntimeError, TypeError) as e:
 271            raise RuntimeError(
 272                f"Unsupported device: '{device}'. Please choose from 'cpu', 'cuda', or 'mps'."
 273            ) from e
 274
 275        if requested_type == "cuda":
 276            if not torch.cuda.is_available():
 277                raise RuntimeError("PyTorch CUDA backend is not available.")
 278        elif requested_type == "mps":
 279            if not (torch.backends.mps.is_available() and torch.backends.mps.is_built()):
 280                raise RuntimeError("PyTorch MPS backend is not available or is not built correctly.")
 281        elif requested_type == "cpu":
 282            pass  # cpu is always available
 283        else:
 284            raise RuntimeError(f"Unsupported device: '{device}'. Please choose from 'cpu', 'cuda', or 'mps'.")
 285
 286    _configure_mps_memory(device)
 287    return device
 288
 289
 290# The compute capability that runs bfloat16 natively. Gated on this and not on
 291# 'torch.cuda.is_bf16_supported', whose default counts emulation and reports bf16 on Volta.
 292BF16_MIN_CAPABILITY = (8, 0)
 293
 294
 295def training_autocast_dtype(device: Optional[Union[str, torch.device]] = None) -> Optional[torch.dtype]:
 296    """The dtype that training runs in on a device.
 297
 298    Training runs in bfloat16 or fp32, never float16: float16 needs loss scaling and still overflows
 299    in the decoder convolutions on GPUs that accumulate it in half precision.
 300
 301    Args:
 302        device: The device the forward pass runs on. Defaults to the best available one.
 303
 304    Returns:
 305        bfloat16 where the device runs it natively, or None where training stays in fp32.
 306    """
 307    device = torch.device(get_device() if device is None else device)
 308    if device.type != "cuda" or not torch.cuda.is_available():
 309        return None
 310    return torch.bfloat16 if torch.cuda.get_device_capability(device) >= BF16_MIN_CAPABILITY else None
 311
 312
 313def get_embedding_function(model_type: str) -> callable:
 314    """Get the precompute-embeddings function for the model family of `model_type`.
 315
 316    Dispatches across the three families: VFM (DINO / UNI) encoders, SAM2 ('hvit_*') and SAM1 ('vit_*').
 317    All returned functions share the interface (predictor, input_, save_path, ndim, tile_shape, halo,
 318    verbose, lazy_loading, pbar_init, pbar_update).
 319
 320    Args:
 321        model_type: The model name, e.g. 'vit_b_lm', 'hvit_t' or 'vit_b_dinov2'.
 322
 323    Returns:
 324        The matching `precompute_image_embeddings` / `precompute_vfm_embeddings` function.
 325
 326    Raises:
 327        ValueError: If `model_type` does not belong to any supported model family.
 328    """
 329    from .models.vfm import is_vfm_model, get_vfm_model_names
 330    from .v2.util import SUPPORTED_MODELS as sam2_backbones
 331
 332    if is_vfm_model(model_type):
 333        from .models.vfm import precompute_vfm_embeddings
 334        return precompute_vfm_embeddings
 335
 336    # Finetuned names keep their backbone prefix ('vit_b_lm' -> 'vit_b', 'hvit_t_cells' -> 'hvit_t').
 337    if isinstance(model_type, str) and model_type[:6] in sam2_backbones:
 338        from .v2.util import precompute_image_embeddings
 339        return precompute_image_embeddings
 340    if isinstance(model_type, str) and model_type[:5] in SAM1_MODEL_TYPES:
 341        from .v1.util import precompute_image_embeddings
 342        return precompute_image_embeddings
 343
 344    raise ValueError(
 345        f"Invalid model_type: '{model_type}'. Expected a SAM1 model (backbone one of {list(SAM1_MODEL_TYPES)}), "
 346        f"a SAM2 model (backbone one of {sam2_backbones}) or a VFM encoder (one of {list(get_vfm_model_names())}). "
 347        "Finetuned models keep their backbone prefix, e.g. 'vit_b_lm' or 'hvit_t_cells'. "
 348        "Run 'micro_sam info' to list all available models."
 349    )
 350
 351
 352# TODO: refactor this once we decide which models to support.
 353# (Likely only SAM2 models)
 354def _get_sam_model(model_type, ndim, device, checkpoint_path, decoder_path, use_cli):
 355    """Build the predictor for a model name, dispatching across the VFM, SAM2 and SAM1 families.
 356
 357    This lives here rather than next to the annotator state that first needed it, so that the CLI and
 358    the automatic-segmentation entry points can load a model without importing napari and the Qt
 359    widgets. Every family is imported inside its own branch, so loading a SAM2 model does not pull in
 360    SAM1 or the training stack either.
 361    """
 362    from .models.vfm import is_vfm_model, get_vfm_model
 363    if is_vfm_model(model_type):  # VFM encoders (DINO / UNI) for the classification tools.
 364        encoder = get_vfm_model(model_type, device=device, checkpoint_path=checkpoint_path)
 365        return encoder, {}
 366
 367    if model_type.startswith("hvit"):  # i.e. SAM2 models.
 368        from .v2.util import get_sam2_image_predictor, get_sam2_model
 369
 370        # 'device=None' lets 'get_sam2_model' auto-detect the best device (cuda > mps > cpu);
 371        # an explicit device (e.g. from the '--device' CLI argument) is forwarded and honored.
 372        if ndim == 2:  # Get the SAM2 model and prepare the image predictor.
 373            model = get_sam2_model(
 374                model_type=model_type, input_type="images", device=device, checkpoint_path=checkpoint_path
 375            )
 376            # Use the shared resize-longest predictor, which takes the model type, name and hash of the model.
 377            predictor = get_sam2_image_predictor(model)
 378        elif ndim == 3:  # Get SAM2 video predictor
 379            predictor = get_sam2_model(
 380                model_type=model_type, input_type="videos", device=device, checkpoint_path=checkpoint_path
 381            )
 382        else:
 383            raise ValueError
 384        state = {}
 385
 386    else:
 387        from .v1.util import get_sam_model
 388
 389        def progress_bar_factory(model_type):
 390            pbar = tqdm(desc=f"Downloading '{model_type}'. This may take a while")
 391            return pbar
 392
 393        predictor, state = get_sam_model(
 394            device=device, model_type=model_type,
 395            checkpoint_path=checkpoint_path, decoder_path=decoder_path, return_state=True,
 396            progress_bar_factory=None if use_cli else progress_bar_factory,
 397        )
 398
 399    return predictor, state
 400
 401
 402def _available_devices():
 403    """List the devices that can be selected explicitly, e.g. in the annotator's device dropdown.
 404
 405    Every visible GPU is listed by its index when there is more than one, so that a multi-GPU user can
 406    choose which GPU to run on. Using all of them is what the annotator's 'auto' entry does.
 407    """
 408    available_devices = []
 409    for i in ["cuda", "mps", "cpu"]:
 410        try:
 411            device = get_device(i)
 412        except RuntimeError:
 413            continue
 414
 415        if device == "cuda" and torch.cuda.device_count() > 1:
 416            available_devices.extend(f"cuda:{index}" for index in range(torch.cuda.device_count()))
 417        else:
 418            available_devices.append(device)
 419    return available_devices
 420
 421
 422# We write a custom unpickler that skips objects that cannot be found instead of
 423# throwing an AttributeError or ModueNotFoundError.
 424# NOTE: since we just want to unpickle the model to load its weights these errors don't matter.
 425# See also https://stackoverflow.com/questions/27732354/unable-to-load-files-using-pickle-and-multiple-modules
 426class _MissingObject:
 427    """A placeholder for an object whose class cannot be imported. It takes any arguments and state."""
 428
 429    def __new__(cls, *args, **kwargs):
 430        return super().__new__(cls)
 431
 432    def __init__(self, *args, **kwargs):
 433        pass
 434
 435    def __setstate__(self, state):
 436        pass
 437
 438
 439class _CustomUnpickler(pickle.Unpickler):
 440    def find_class(self, module, name):
 441        try:
 442            return super().find_class(module, name)
 443        except (AttributeError, ModuleNotFoundError) as e:
 444            warnings.warn(f"Did not find {module}:{name} and will skip it, due to error {e}")
 445            return type(name, (_MissingObject,), {"__module__": module})
 446
 447
 448def _compute_hash(path, chunk_size=8192):
 449    hash_obj = xxhash.xxh128()
 450    with open(path, "rb") as f:
 451        chunk = f.read(chunk_size)
 452        while chunk:
 453            hash_obj.update(chunk)
 454            chunk = f.read(chunk_size)
 455    hash_val = hash_obj.hexdigest()
 456    return f"xxh128:{hash_val}"
 457
 458
 459def load_checkpoint(checkpoint_path: Union[str, os.PathLike], map_location: Any = "cpu") -> Any:
 460    """Load a checkpoint, and skip the objects whose class cannot be imported.
 461
 462    A torch_em training checkpoint also holds the settings of the data loaders, for example the
 463    transforms. A transform that the training script defined itself cannot be imported elsewhere.
 464    The weights do not need these objects, so they are skipped with a warning.
 465
 466    Args:
 467        checkpoint_path: The path to the checkpoint.
 468        map_location: Where to map the tensors to. By default the CPU.
 469
 470    Returns:
 471        The content of the checkpoint.
 472    """
 473    # A copy of the pickle module with the tolerant unpickler, so the pickle module itself stays unchanged.
 474    skip_missing_pickle = types.ModuleType("skip_missing_pickle")
 475    skip_missing_pickle.__dict__.update(pickle.__dict__)
 476    skip_missing_pickle.Unpickler = _CustomUnpickler
 477    return torch.load(checkpoint_path, map_location=map_location, pickle_module=skip_missing_pickle, weights_only=False)
 478
 479
 480# Load the state from a checkpoint.
 481# The checkpoint can either contain a sam encoder state
 482# or it can be a checkpoint for model finetuning.
 483def _load_checkpoint(checkpoint_path):
 484    state = load_checkpoint(checkpoint_path)
 485    if "model_state" in state:
 486        # Copy the model weights from torch_em's training format.
 487        model_state = state["model_state"]
 488        sam_prefix = "sam."
 489        model_state = OrderedDict(
 490            [(k[len(sam_prefix):] if k.startswith(sam_prefix) else k, v) for k, v in model_state.items()]
 491        )
 492    else:
 493        model_state = state
 494
 495    return state, model_state
 496
 497
 498#
 499# Functionality for precomputing image embeddings.
 500#
 501
 502
 503def _ensure_rgb(image):
 504    """Map a 2D or channel-last image to a 3-channel (H, W, 3) array without normalizing."""
 505    ndim = image.ndim
 506    n_channels = 1 if ndim == 2 else image.shape[-1]
 507
 508    if ndim == 2:  # Grayscale image -> replicate channels.
 509        image = np.concatenate([image[..., None]] * 3, axis=-1)
 510    elif ndim == 3 and n_channels == 1:  # Grayscale image -> replicate channels.
 511        image = np.concatenate([image] * 3, axis=-1)
 512    elif ndim == 3 and n_channels == 2:  # Two channels -> add a zero channel.
 513        zero_channel = np.zeros(image.shape[:2] + (1,), dtype=image.dtype)
 514        image = np.concatenate([image, zero_channel], axis=-1)
 515    elif ndim == 3 and n_channels == 3:  # RGB input -> do nothing.
 516        pass
 517    elif ndim == 3 and n_channels > 3:  # More than three channels -> select first three.
 518        warnings.warn(f"You provided an input with {n_channels} channels. Only the first three will be used.")
 519        image = image[..., :3]
 520    else:
 521        raise ValueError(
 522            f"Invalid input dimensionality {ndim}. Expect either a 2D input (=grayscale image) "
 523            "or a 3D input (= image with channels)."
 524        )
 525
 526    assert image.ndim == 3 and image.shape[-1] == 3
 527    return image
 528
 529
 530def _to_image(image):
 531    # Map to three channels, then normalize per channel and bring it to uint8.
 532    input_ = _ensure_rgb(image).astype("float32")
 533    input_ -= input_.min(axis=(0, 1))[None, None]
 534    input_ /= (input_.max(axis=(0, 1))[None, None] + 1e-7)
 535    input_ = (input_ * 255).astype("uint8")
 536
 537    # Explicitly return a numpy array for compatibility with torchvision
 538    # because the input_ array could be something like dask array.
 539    return np.array(input_)
 540
 541
 542# The zarr format used when writing new on-disk embedding caches. Reading auto-detects the format,
 543# so existing caches (v2 or v3) still load. This only controls newly created containers.
 544EMBEDDING_ZARR_FORMAT = 3
 545# Compression codec for on-disk embeddings. blosc (byte-shuffle + lz4) is the fastest to read and write
 546# and the smallest for float32 features. It is also z5py's default, so this just pins it explicitly.
 547EMBEDDING_COMPRESSION = "blosc"
 548# Upper bound on how much of the input is materialized at once when hashing it for the data signature.
 549DATA_SIGNATURE_BLOCK_SIZE = 64 * 1024**2
 550
 551
 552def _open_embeddings(save_path, mode="a"):
 553    """Open the container for image embeddings.
 554
 555    On-disk embeddings use z5py, whose C++ core reads and writes zarr much faster than zarr-python.
 556    Reading auto-detects the zarr format, so existing caches (v2 and v3) still load; new caches use
 557    the format given by ``EMBEDDING_ZARR_FORMAT``. In-memory embeddings (``save_path=None``) use an
 558    in-memory zarr group, which z5py does not support.
 559    """
 560    if save_path is None:
 561        return zarr.group()
 562    save_path = str(save_path)
 563    # Unlike zarr-python, z5py cannot open an existing directory that has no zarr metadata
 564    # (e.g. an empty folder left by a previous run). When appending, write the group metadata
 565    # for the pinned format first so the container opens as an empty group, as zarr-python did.
 566    if mode == "a" and os.path.isdir(save_path):
 567        has_metadata = any(
 568            os.path.exists(os.path.join(save_path, name)) for name in (".zgroup", ".zarray", "zarr.json")
 569        )
 570        if not has_metadata:
 571            if EMBEDDING_ZARR_FORMAT == 2:
 572                meta_name, meta = ".zgroup", {"zarr_format": 2}
 573            else:
 574                meta_name, meta = "zarr.json", {"zarr_format": 3, "node_type": "group", "attributes": {}}
 575            with open(os.path.join(save_path, meta_name), "w") as f:
 576                json.dump(meta, f)
 577    return z5py.ZarrFile(save_path, mode=mode, zarr_format=EMBEDDING_ZARR_FORMAT)
 578
 579
 580def _create_dataset_with_data(group, name, data, chunks=None):
 581    if chunks is None:
 582        chunks = data.shape
 583    # z5py exposes the h5py-style create_dataset for both zarr v2 and v3.
 584    if isinstance(group, z5py.Group):
 585        return group.create_dataset(name, data=data, shape=data.shape, chunks=chunks, compression=EMBEDDING_COMPRESSION)
 586    # In-memory zarr group (only used when no save_path is given).
 587    zarr_major_version = int(zarr.__version__.split(".")[0])
 588    if zarr_major_version == 2:
 589        ds = group.create_dataset(name, data=data, shape=data.shape, chunks=chunks)
 590    elif zarr_major_version == 3:
 591        ds = group.create_array(name, shape=data.shape, chunks=chunks, dtype=data.dtype)
 592        ds[:] = data
 593    else:
 594        raise RuntimeError(f"Unsupported zarr version: {zarr_major_version}")
 595    return ds
 596
 597
 598def _create_dataset_without_data(group, name, shape, dtype, chunks):
 599    if isinstance(group, z5py.Group):
 600        return group.create_dataset(
 601            name, shape=shape, dtype=dtype, chunks=chunks, compression=EMBEDDING_COMPRESSION
 602        )
 603    # In-memory zarr group (only used when no save_path is given).
 604    zarr_major_version = int(zarr.__version__.split(".")[0])
 605    if zarr_major_version == 2:
 606        ds = group.create_dataset(name, shape=shape, dtype=dtype, chunks=chunks)
 607    elif zarr_major_version == 3:
 608        ds = group.create_array(name, shape=shape, chunks=chunks, dtype=dtype)
 609    else:
 610        raise RuntimeError(f"Unsupported zarr version: {zarr_major_version}")
 611    return ds
 612
 613
 614def _compute_data_signature(input_):
 615    # Hash the input in blocks along the leading axis, so a lazy input (dask / zarr / h5py) is never
 616    # materialized as a whole. The digest is unchanged: it is the same byte stream, fed in parts.
 617    shape = tuple(getattr(input_, "shape", ()))
 618    itemsize = getattr(getattr(input_, "dtype", None), "itemsize", None)
 619    signature = hashlib.sha1()
 620    if len(shape) == 0 or itemsize is None:
 621        signature.update(np.asarray(input_).tobytes())
 622        return signature.hexdigest()
 623
 624    bytes_per_slice = itemsize * int(np.prod(shape[1:], dtype="int64"))
 625    block = max(1, DATA_SIGNATURE_BLOCK_SIZE // max(bytes_per_slice, 1))
 626    for start in range(0, shape[0], block):
 627        signature.update(np.asarray(input_[start:start + block]).tobytes())
 628    return signature.hexdigest()
 629
 630
 631# Create all metadata that is stored along with the embeddings.
 632def _get_embedding_signature(input_, predictor, tile_shape, halo, data_signature=None):
 633    if data_signature is None:
 634        data_signature = _compute_data_signature(input_)
 635
 636    signature = {
 637        "data_signature": data_signature,
 638        "tile_shape": tile_shape if tile_shape is None else list(tile_shape),
 639        "halo": halo if halo is None else list(halo),
 640        "model_type": predictor.model_type,
 641        "model_name": predictor.model_name,
 642        "micro_sam_version": __version__,
 643        "model_hash": getattr(predictor, "_hash", None),
 644    }
 645    return signature
 646
 647
 648def _channels_to_rgb(image: np.ndarray) -> np.ndarray:
 649    """Map a 2D image's trailing channel axis to exactly 3 channels.
 650
 651    A single channel is replicated, two channels are padded with a zero channel, three channels are
 652    left as-is, and more than three channels are reduced to the first three (with a warning).
 653    """
 654    n_channels = image.shape[-1]
 655    if n_channels == 3:
 656        return image
 657    if n_channels == 1:
 658        return np.concatenate([image] * 3, axis=-1)
 659    if n_channels == 2:
 660        zero_channel = np.zeros(image.shape[:-1] + (1,), dtype=image.dtype)
 661        return np.concatenate([image, zero_channel], axis=-1)
 662    warnings.warn(f"You provided an input with {n_channels} channels. Only the first three will be used.")
 663    return image[..., :3]
 664
 665
 666def match_image_shape(labels: np.ndarray, image_shape: Tuple[int, ...]) -> np.ndarray:
 667    """Bring a label image, such as a segmentation or annotations, to the shape of a prepared image.
 668
 669    `prepare_annotation_image` squeezes singleton axes from the image, so the labels lose the same
 670    singleton axes. Any other difference in shape is an error.
 671
 672    Args:
 673        labels: The label image.
 674        image_shape: The spatial shape of the prepared image.
 675
 676    Returns:
 677        The label image in the shape of the image.
 678
 679    Raises:
 680        ValueError: If the shapes differ in more than singleton axes.
 681    """
 682    labels = np.asarray(labels)
 683    image_shape = tuple(image_shape)
 684    if labels.shape == image_shape:
 685        return labels
 686    if np.squeeze(labels).shape != tuple(size for size in image_shape if size != 1):
 687        raise ValueError(f"The labels of shape {labels.shape} do not match the image of shape {image_shape}.")
 688    return labels.reshape(image_shape)
 689
 690
 691def prepare_annotation_image(image: np.ndarray, ndim: Optional[int] = None) -> Tuple[np.ndarray, int, bool]:
 692    """Normalize an image for annotation: squeeze singletons and map 2D channels to RGB.
 693
 694    Singleton axes (commonly exposed by formats like CZI) are squeezed out across all axes.
 695    For a 2D image, the trailing channel axis is mapped to 3 channels: a 2-channel input is
 696    padded with a zero channel and a 4-channel input is reduced to the first three (with a
 697    warning). A 3D volume with a channel axis (3D+C) gets the same mapping on a trailing channel axis.
 698
 699    Args:
 700        image: The input image data.
 701        ndim: Optional override for the spatial dimensionality (2 or 3). A single-slice ``(1, H, W)``
 702            volume keeps its z axis when ``3`` is passed. With ``None`` (the default)
 703            the dimensionality is auto-detected from the shape (a trailing axis of size 3 -> RGB 2D,
 704            of size 2 or 4 -> channels mapped to RGB 2D, otherwise a 3D volume). With ``2`` a 3D array
 705            is read as a 2D multi-channel image, taking the smallest axis as the channel axis (so a
 706            channels-first ``(C, H, W)`` array also works) and mapping the channels to RGB. With ``3``
 707            a 3D array is read as a ``(Z, H, W)`` volume, and a 4D array as a volume with a channel
 708            axis of size 2 to 4 at position 3, 1 or 0 (checked in that order), moved to the trailing
 709            position. A 4D array with a trailing axis of size 2 to 4 is auto-detected as such a volume.
 710
 711    Returns:
 712        A tuple of the normalized image, its spatial dimensionality (2 or 3), and whether
 713        it has a trailing RGB channel axis.
 714
 715    Raises:
 716        ValueError: If the (overridden) dimensionality cannot be applied to the image shape, or the
 717            squeezed image is neither a 2D image nor a grayscale 3D volume.
 718    """
 719    if ndim not in (None, 2, 3):
 720        raise ValueError(f"Invalid ndim override: {ndim}. Expected None, 2 or 3.")
 721
 722    input_ndim = image.ndim
 723    image = np.squeeze(image)
 724
 725    # Forced 2D: read a 3D array as a 2D multi-channel image. The channel axis is taken to be the
 726    # smallest axis (so both channels-first (C, H, W) and channels-last (H, W, C) work); it is moved
 727    # to the trailing position and mapped to 3 channels.
 728    if ndim == 2:
 729        if image.ndim == 2:
 730            return image, 2, False
 731        if image.ndim == 3:
 732            channel_axis = int(np.argmin(image.shape))
 733            image = np.moveaxis(image, channel_axis, -1)
 734            return _channels_to_rgb(image), 2, True
 735        raise ValueError(f"Cannot interpret shape {image.shape} as a 2D image.")
 736
 737    # Forced 3D: read a 3D array as a (Z, H, W) volume, and a 4D array as a volume with a channel axis.
 738    if ndim == 3:
 739        if image.ndim == 3:
 740            return image, 3, False
 741        # A single-slice volume squeezes down to one plane; put the z axis back rather than reject
 742        # it. A genuinely 2d input still raises: asking for a volume and passing a plane is an error.
 743        if image.ndim == 2 and input_ndim == 3:
 744            return image[None], 3, False
 745        if image.ndim == 4:
 746            # Channels-last (Z, H, W, C), channels-second (Z, C, H, W) or channels-first (C, Z, H, W).
 747            channel_axis = next((axis for axis in (3, 1, 0) if image.shape[axis] in (2, 3, 4)), None)
 748            if channel_axis is not None:
 749                image = np.moveaxis(image, channel_axis, -1)
 750                return _channels_to_rgb(image), 3, True
 751        raise ValueError(f"Cannot interpret shape {image.shape} as a 3D volume.")
 752
 753    # Auto-detect. A 4D array with a trailing axis of size 2, 3 or 4 is a volume with channels
 754    # (Z, H, W, C). Any other 4D array may be a volumetric time series (T, Z, H, W), which is not supported.
 755    if image.ndim == 4:
 756        if image.shape[-1] in (2, 3, 4):
 757            return _channels_to_rgb(image), 3, True
 758        raise ValueError(
 759            f"Invalid image shape: {image.shape}. Expected 2D or 3D image data (3D+t is not supported). "
 760            "Pass ndim=3 for a volume with a non-trailing channel axis."
 761        )
 762
 763    # 2D image with a 2- or 4-channel trailing axis: map it to 3 channels. A trailing axis of any
 764    # other size is left alone, so a size-3 axis stays RGB and anything else is treated as a volume.
 765    if image.ndim == 3 and image.shape[-1] in (2, 4):
 766        image = _channels_to_rgb(image)
 767
 768    # Map the (possibly normalized) shape to a spatial dimensionality and rgb flag.
 769    if image.ndim == 2:
 770        return image, 2, False
 771    elif image.ndim == 3:
 772        if image.shape[-1] == 3:
 773            return image, 2, True
 774        return image, 3, False
 775    raise ValueError(f"Invalid image shape: {image.shape}. Expected 2D or 3D image data.")
 776
 777
 778def read_cached_tiling(embedding_path: Optional[Union[str, os.PathLike]]) -> Optional[Tuple]:
 779    """Read the tiling that cached embeddings were computed with.
 780
 781    The tiling is part of the embedding signature, so embeddings computed with a different tiling
 782    than the one requested are discarded and recomputed. Reading it back lets the annotation tools
 783    reuse an existing cache instead of recomputing it just because their default tiling differs from
 784    the one it was computed with (see `micro_sam.v2.util.resolve_default_tiling`).
 785
 786    Args:
 787        embedding_path: The filepath of the cached embeddings. May also be None or already loaded
 788            embeddings, in which case there is nothing to read.
 789
 790    Returns:
 791        The in-plane (tile_shape, halo) of the cached embeddings, where a tile shape of None means
 792        they were computed without tiling. None if `embedding_path` holds no embeddings (yet).
 793    """
 794    if not isinstance(embedding_path, (str, os.PathLike)) or not os.path.exists(embedding_path):
 795        return None
 796
 797    try:
 798        f = _open_embeddings(embedding_path, mode="r")
 799    except (OSError, RuntimeError):  # Not a readable container, e.g. an empty folder from a failed run.
 800        return None
 801
 802    try:
 803        # 'tile_shape' is only written once the embeddings are complete, so a partial cache (which
 804        # will be recomputed anyway) does not advertise a tiling.
 805        if "tile_shape" not in f.attrs:
 806            return None
 807        tile_shape, halo = f.attrs["tile_shape"], f.attrs.get("halo")
 808    finally:
 809        getattr(f, "file", f).close()
 810
 811    return (
 812        None if tile_shape is None else tuple(tile_shape),
 813        None if halo is None else tuple(halo),
 814    )
 815
 816
 817# Note: the input size and orginal size are different if embeddings are tiled or not.
 818# That's why we do not include them in the main signature that is being checked
 819# (_get_embedding_signature), but just add it for serialization here.
 820def _write_embedding_signature(f, input_, predictor, tile_shape, halo, input_size, original_size):
 821    signature = _get_embedding_signature(input_, predictor, tile_shape, halo)
 822    signature.update({"input_size": input_size, "original_size": original_size})
 823    for key, val in signature.items():
 824        f.attrs[key] = val
 825
 826
 827def _progress_bar(*args, disable=False, **kwargs):
 828    # A disabled napari progress bar is never removed from napari's activity dock: its 'close' returns
 829    # early when the bar is disabled. So we use a plain tqdm progress bar when the bar is disabled.
 830    if disable:
 831        return _std_tqdm(*args, disable=True, **kwargs)
 832    return tqdm(*args, **kwargs)
 833
 834
 835# Helper function for optional external progress bars.
 836def handle_pbar(verbose, pbar_init, pbar_update):
 837    """@private"""
 838
 839    # Noop to provide dummy functions.
 840    def noop(*args):
 841        pass
 842
 843    if verbose and pbar_init is None:  # we are verbose and don't have an external progress bar.
 844        assert pbar_update is None  # avoid inconsistent state of callbacks
 845
 846        # Create our own progress bar and callbacks
 847        pbar = tqdm()
 848
 849        def pbar_init(total, description):
 850            pbar.total = total
 851            pbar.set_description(description)
 852
 853        def pbar_update(update):
 854            pbar.update(update)
 855
 856        def pbar_close():
 857            pbar.close()
 858
 859    elif verbose and pbar_init is not None:  # external pbar -> we don't have to do anything
 860        assert pbar_update is not None
 861        pbar = None
 862        pbar_close = noop
 863
 864    else:  # we are not verbose, do nothing
 865        pbar = None
 866        pbar_init, pbar_update, pbar_close = noop, noop, noop
 867
 868    return pbar, pbar_init, pbar_update, pbar_close
 869
 870
 871#
 872# Misc functionality
 873#
 874
 875
 876def compute_iou(mask1: np.ndarray, mask2: np.ndarray) -> float:
 877    """Compute the intersection over union of two masks.
 878
 879    Args:
 880        mask1: The first mask.
 881        mask2: The second mask.
 882
 883    Returns:
 884        The intersection over union of the two masks.
 885    """
 886    overlap = np.logical_and(mask1 == 1, mask2 == 1).sum()
 887    union = np.logical_or(mask1 == 1, mask2 == 1).sum()
 888    eps = 1e-7
 889    iou = float(overlap) / (float(union) + eps)
 890    return iou
 891
 892
 893def get_centers_and_bounding_boxes(
 894    segmentation: np.ndarray, mode: str = "v"
 895) -> Tuple[Dict[int, np.ndarray], Dict[int, tuple]]:
 896    """Returns the center coordinates of the foreground instances in the ground-truth.
 897
 898    Args:
 899        segmentation: The segmentation.
 900        mode: Determines the functionality used for computing the centers.
 901            If 'v', the point of maximal distance to the object boundary is used as center.
 902            This center is guaranteed to lie inside the object, also for concave shapes.
 903            If 'p' the object's centroids computed by skimage are used.
 904
 905    Returns:
 906        A dictionary that maps object ids to the corresponding centroid.
 907        A dictionary that maps object_ids to the corresponding bounding box.
 908    """
 909    assert mode in ["p", "v"], "Choose either 'p' for regionprops centroids or 'v' for distance-based centers"
 910
 911    properties = regionprops(segmentation)
 912
 913    if mode == "p":
 914        center_coordinates = {prop.label: prop.centroid for prop in properties}
 915    elif mode == "v":
 916        # Use the point of maximal distance to the object boundary as the center.
 917        # In contrast to the centroid, this point is guaranteed to lie inside the object,
 918        # also for concave shapes. This replaces vigra.filters.eccentricityCenters.
 919        # Compute the boundaries and a single distance transform for the whole
 920        # segmentation, instead of one distance transform per object.
 921        ndim = segmentation.ndim
 922        # Pad so objects touching the image border also get a boundary there,
 923        # matching a per-object padded distance transform.
 924        padded = np.pad(segmentation, 1)
 925        boundaries = find_boundaries(padded, mode="inner")
 926        distances = distance_transform(boundaries == 0)
 927
 928        center_coordinates = {}
 929        for prop in properties:
 930            bbox = prop.bbox
 931            # Slice the global distance field to this object's bbox (shifted by the
 932            # pad of 1) and restrict the argmax to the object's own pixels.
 933            region = distances[tuple(slice(b + 1, e + 1) for b, e in zip(bbox[:ndim], bbox[ndim:]))]
 934            masked = np.where(prop.image, region, -1.0)
 935            center_local = np.unravel_index(int(np.argmax(masked)), masked.shape)
 936            center_coordinates[prop.label] = tuple(int(c + o) for c, o in zip(center_local, bbox[:ndim]))
 937
 938    bbox_coordinates = {prop.label: prop.bbox for prop in properties}
 939
 940    assert len(bbox_coordinates) == len(center_coordinates), f"{len(bbox_coordinates)}, {len(center_coordinates)}"
 941    return center_coordinates, bbox_coordinates
 942
 943
 944def load_image_data(path: str, key: Optional[str] = None, lazy_loading: bool = False) -> np.ndarray:
 945    """Helper function to load image data from file.
 946
 947    Args:
 948        path: The filepath to the image data.
 949        key: The internal filepath for complex data formats like hdf5.
 950        lazy_loading: Whether to lazyly load data. Only supported for n5 and zarr data.
 951
 952    Returns:
 953        The image data.
 954    """
 955    if key is None:
 956        image_data = imageio.imread(path)
 957    else:
 958        with open_file(path, mode="r") as f:
 959            image_data = f[key]
 960            if not lazy_loading:
 961                image_data = image_data[:]
 962
 963    return image_data
 964
 965
 966def segmentation_to_one_hot(segmentation: np.ndarray, segmentation_ids: Optional[np.ndarray] = None) -> torch.Tensor:
 967    """Convert the segmentation to one-hot encoded masks.
 968
 969    Args:
 970        segmentation: The segmentation.
 971        segmentation_ids: Optional subset of ids that will be used to subsample the masks.
 972            By default, computes the number of ids from the provided `segmentation` masks.
 973
 974    Returns:
 975        The one-hot encoded masks.
 976    """
 977    masks = segmentation.copy()
 978    if segmentation_ids is None:
 979        n_ids = int(segmentation.max())
 980
 981    else:
 982        msg = "No foreground objects were found."
 983        if len(segmentation_ids) == 0:  # The list should not be completely empty.
 984            raise RuntimeError(msg)
 985
 986        if 0 in segmentation_ids:  # The list should not have 'zero' as a value.
 987            raise RuntimeError(msg)
 988
 989        # the segmentation ids have to be sorted
 990        segmentation_ids = np.sort(segmentation_ids)
 991
 992        # set the non selected objects to zero and relabel sequentially
 993        masks[~np.isin(masks, segmentation_ids)] = 0
 994        masks = relabel_sequential(masks)[0]
 995        n_ids = len(segmentation_ids)
 996
 997    masks = torch.from_numpy(masks)
 998
 999    one_hot_shape = (n_ids + 1,) + masks.shape
1000    masks = masks.unsqueeze(0)  # add dimension to scatter
1001    masks = torch.zeros(one_hot_shape).scatter_(0, masks, 1)[1:]
1002
1003    # add the extra singleton dimension to get shape NUM_OBJECTS x 1 x H x W
1004    masks = masks.unsqueeze(1)
1005    return masks
1006
1007
1008def get_block_shape(shape: Tuple[int]) -> Tuple[int]:
1009    """Get a suitable block shape for chunking a given shape.
1010
1011    The primary use for this is determining chunk sizes for
1012    zarr arrays or block shapes for parallelization.
1013
1014    Args:
1015        shape: The image or volume shape.
1016
1017    Returns:
1018        The block shape.
1019    """
1020    ndim = len(shape)
1021    if ndim == 2:
1022        block_shape = tuple(min(bs, sh) for bs, sh in zip((1024, 1024), shape))
1023    elif ndim == 3:
1024        block_shape = tuple(min(bs, sh) for bs, sh in zip((32, 256, 256), shape))
1025    else:
1026        raise ValueError(f"Only 2 or 3 dimensional shapes are supported, got {ndim}D.")
1027
1028    return block_shape
1029
1030
1031def micro_sam_info(download: Optional[List[str]] = None) -> None:
1032    """Display μSAM information using a rich console.
1033
1034    Args:
1035        download: Optional list of pretrained models to download by name (SAM1, SAM2 or their finetuned
1036            variants). E.g. ['vit_b_lm', 'hvit_t'] downloads the listed models; ['all'] downloads every
1037            available model.
1038    """
1039    import psutil
1040    import platform
1041    from .v1.util import models, _download_sam_model
1042    from .v2.util import SUPPORTED_MODELS, get_model_names, _get_checkpoint, _download_finetuned_sam2_model
1043    from rich import progress
1044    from rich.panel import Panel
1045    from rich.table import Table
1046    from rich.console import Console
1047
1048    import torch
1049    import micro_sam
1050
1051    # Open up a new console.
1052    console = Console()
1053
1054    # The header for information CLI.
1055    console.print("[bold #0072B2]μSAM Information Booth[/bold #0072B2]", justify="center")
1056    console.print("-" * console.width)
1057
1058    # μSAM version panel.
1059    console.print(
1060        Panel(f"[bold #F0E442]Version:[/bold #F0E442] {micro_sam.__version__}", title="μSAM Version", expand=True)
1061    )
1062
1063    # The documentation link panel.
1064    console.print(
1065        Panel(
1066            "[bold #CC79A7]Tools documented at:[/bold #CC79A7]\n"
1067            "https://computational-cell-analytics.github.io/micro-sam", title="Documentation"
1068        )
1069    )
1070
1071    # The publication panel.
1072    console.print(
1073        Panel(
1074            "[bold #E69F00]Published in Nature Methods:[/bold #E69F00]\n"
1075            "https://www.nature.com/articles/s41592-024-02580-4", title="Publication"
1076        )
1077    )
1078
1079    # Creating a cache directory when users' run `micro_sam.info`.
1080    cache_dir = get_cache_directory()
1081    os.makedirs(cache_dir, exist_ok=True)
1082
1083    # The cache directory panel.
1084    console.print(
1085        Panel(f"[bold #009E73]Cache Directory:[/bold #009E73]\n{cache_dir}", title="Cache Directory")
1086    )
1087
1088    # SAM1 models. 'sam1_display' holds the labeled names shown in the panel (the '(v2/v3/v4)' suffixes
1089    # refer to the BioImageIO ModelZoo upload version, not the SAM version); 'sam1_names' holds the bare
1090    # names accepted by the downloader.
1091    sam1_display, sam1_names = [], []
1092    for model_name, model_path in models().urls.items():  # We filter out the decoder models.
1093        if model_name.endswith("decoder"):
1094            continue
1095        sam1_names.append(model_name)
1096
1097        if "https://dl.fbaipublicfiles.com/segment_anything/" in model_path:  # Valid v1 SAM models.
1098            sam1_display.append(model_name)
1099
1100        if "https://owncloud.gwdg.de/" in model_path:  # Our own hosted models (in their v1 mode quite often)
1101            if model_name == "vit_t":  # MobileSAM model.
1102                sam1_display.append(model_name)
1103            else:
1104                sam1_display.append(f"{model_name} (v1)")
1105
1106        # Now for our models, the BioImageIO ModelZoo upload structure is such that:
1107        # '/1/files' corresponds to v2 models.
1108        # '/1.1/files' corresponds to v3 models.
1109        # '/1.2/files' corresponds to v4 models.
1110        if "/1/files" in model_path:
1111            sam1_display.append(f"{model_name} (v2)")
1112        if "/1.1/files" in model_path:
1113            sam1_display.append(f"{model_name} (v3)")
1114        if "/1.2/files" in model_path:
1115            sam1_display.append(f"{model_name} (v4)")
1116
1117    # SAM2 models: the base backbones plus the finetuned micro-sam models (with a registered decoder).
1118    sam2_base = list(SUPPORTED_MODELS)
1119    sam2_finetuned = list(get_model_names())
1120    sam2_names = sam2_base + sam2_finetuned
1121    sam2_display = sam2_base + [f"{name} (DEV)" for name in sam2_finetuned]
1122
1123    # The available models panels (SAM1 and SAM2 shown separately to avoid confusing the BioImageIO
1124    # version suffixes above with the SAM version).
1125    console.print(
1126        Panel(f"[bold #D55E00]{chr(10).join(sam1_display)}[/bold #D55E00]", title="SAM1 Models")
1127    )
1128    console.print(
1129        Panel(f"[bold #D55E00]{chr(10).join(sam2_display)}[/bold #D55E00]", title="SAM2 Models")
1130    )
1131
1132    # The system information table.
1133    total_memory = psutil.virtual_memory().total / (1024 ** 3)
1134    table = Table(title="System Information", show_header=True, header_style="bold #0072B2", expand=True)
1135    table.add_column("Property")
1136    table.add_column("Value", style="bold #56B4E9")
1137    table.add_row("System", platform.system())
1138    table.add_row("Node Name", platform.node())
1139    table.add_row("Release", platform.release())
1140    table.add_row("Version", platform.version())
1141    table.add_row("Machine", platform.machine())
1142    table.add_row("Processor", platform.processor())
1143    table.add_row("Platform", platform.platform())
1144    table.add_row("Python", platform.python_version())
1145    table.add_row("CPU Count", str(psutil.cpu_count(logical=True)))
1146    table.add_row("Total RAM (GB)", f"{total_memory:.2f}")
1147    console.print(table)
1148
1149    # Accelerator / device information. This identifies the exact backend, since PyTorch exposes several
1150    # (NVIDIA CUDA, AMD ROCm - which also reports through the CUDA API but sets 'torch.version.hip' -,
1151    # Apple MPS and Intel XPU) and knowing which one (and the device name / memory) is key for debugging.
1152    device_lines = [f"[bold]PyTorch:[/bold] {torch.__version__}"]
1153    if torch.cuda.is_available():
1154        idx = torch.cuda.current_device()
1155        props = torch.cuda.get_device_properties(idx)
1156        is_rocm = getattr(torch.version, "hip", None) is not None
1157        device_lines.append(f"[bold]Backend:[/bold] {'ROCm (AMD)' if is_rocm else 'CUDA (NVIDIA)'}")
1158        device_lines.append(f"[bold]Device:[/bold] {props.name}")
1159        device_lines.append(f"[bold]Device count:[/bold] {torch.cuda.device_count()}")
1160        device_lines.append(f"[bold]GPU memory (GB):[/bold] {props.total_memory / (1024 ** 3):.2f}")
1161        if is_rocm:
1162            device_lines.append(f"[bold]HIP version:[/bold] {torch.version.hip}")
1163        else:
1164            device_lines.append(f"[bold]CUDA (torch build):[/bold] {torch.version.cuda}")
1165            device_lines.append(f"[bold]cuDNN:[/bold] {torch.backends.cudnn.version()}")
1166    elif torch.backends.mps.is_available():
1167        # On Apple Silicon the GPU is the SoC. Report the exact chip on a best-effort basis.
1168        chip = platform.processor()
1169        if platform.system() == "Darwin":
1170            try:
1171                import subprocess
1172                chip = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"]).decode().strip() or chip
1173            except Exception:
1174                pass
1175        device_lines.append("[bold]Backend:[/bold] MPS (Apple Silicon)")
1176        device_lines.append(f"[bold]Device:[/bold] {chip}")
1177    elif hasattr(torch, "xpu") and torch.xpu.is_available():
1178        idx = torch.xpu.current_device()
1179        device_lines.append("[bold]Backend:[/bold] XPU (Intel)")
1180        device_lines.append(f"[bold]Device:[/bold] {torch.xpu.get_device_name(idx)}")
1181        device_lines.append(f"[bold]Device count:[/bold] {torch.xpu.device_count()}")
1182    else:
1183        device_lines.append("[bold]Backend:[/bold] CPU (no GPU acceleration detected)")
1184        gpu_warning = get_gpu_setup_warning()
1185        if gpu_warning is not None:
1186            device_lines.append(f"[bold red]Warning:[/bold red] {gpu_warning}")
1187    console.print(Panel("\n".join(device_lines), title="Accelerator Information"))
1188
1189    # The section allowing to download models.
1190    # NOTE: In future, can be extended to download sample data.
1191    if download:
1192        all_names = sam1_names + sam2_names
1193        if any(t.lower() == "all" for t in download):  # Download every available model.
1194            download_list = all_names
1195            # Guard the bulk download (all SAM1 + SAM2 models, several GB) behind a confirmation, but
1196            # only when interactive so scripted '--download all' still runs unattended.
1197            import sys
1198            from rich.prompt import Confirm
1199            if sys.stdin.isatty() and not Confirm.ask(
1200                f"[yellow]This downloads all {len(download_list)} models (SAM1 + SAM2), several GB. Continue?[/]",
1201                console=console, default=False,
1202            ):
1203                console.print("[red]Download aborted.[/]")
1204                return
1205        else:
1206            download_list = list(download)
1207            incorrect_models = [m for m in download_list if m not in all_names]
1208            if incorrect_models:
1209                console.print(Panel("[red]Unknown model(s):[/] " + ", ".join(incorrect_models), title="Download Error"))
1210                return
1211
1212        def _download(name):  # Dispatch to the downloader for the model's family.
1213            if name in sam2_finetuned:
1214                _download_finetuned_sam2_model(name)
1215            elif name in sam2_base:
1216                _get_checkpoint(name)
1217            else:
1218                _download_sam_model(model_type=name)
1219
1220        with progress.Progress(
1221            progress.SpinnerColumn(),
1222            progress.TextColumn("[progress.description]{task.description}"),
1223            progress.BarColumn(bar_width=None),
1224            "[progress.percentage]{task.percentage:>3.0f}%",
1225            progress.TimeRemainingColumn(),
1226            console=console,
1227        ) as prog:
1228            task = prog.add_task("[green]Downloading μSAM models…", total=len(download_list))
1229            for model_type in download_list:
1230                prog.update(task, description=f"Downloading [cyan]{model_type}[/]…")
1231                _download(model_type)
1232                prog.advance(task)
1233
1234        console.print(Panel("[bold green] Downloads complete![/]", title="Finished"))
1235
1236
1237#
1238# Functionality to convert mask predictions to an instance segmentation via non-maximum suppression.
1239# The functionality for computing NMS for masks is taken from CellSeg1:
1240# https://github.com/Nuisal/cellseg1/blob/1c027c2568b83494d2662d1fbecec9aafb478ee0/mask_nms.py
1241#
1242
1243
1244def _overlap_matrix(boxes):
1245    x1 = torch.max(boxes[:, None, 0], boxes[:, 0])
1246    y1 = torch.max(boxes[:, None, 1], boxes[:, 1])
1247    x2 = torch.min(boxes[:, None, 2], boxes[:, 2])
1248    y2 = torch.min(boxes[:, None, 3], boxes[:, 3])
1249
1250    w = torch.clamp(x2 - x1, min=0)
1251    h = torch.clamp(y2 - y1, min=0)
1252
1253    return (w * h) > 0
1254
1255
1256def _calculate_ious_between_pred_masks(masks, boxes, diagonal_value=1):
1257    n_points = masks.shape[0]
1258    m = torch.zeros((n_points, n_points))
1259
1260    overlap_m = _overlap_matrix(boxes)
1261
1262    for i in range(n_points):
1263        js = torch.where(overlap_m[i])[0]
1264        js_half = js[js > i].to(masks.device)
1265
1266        if len(js_half) > 0:
1267            intersection = torch.logical_and(masks[i], masks[js_half]).sum(dim=(1, 2))
1268            union = torch.logical_or(masks[i], masks[js_half]).sum(dim=(1, 2))
1269            iou = intersection / union
1270            m[i, js_half] = iou
1271
1272    m = m + m.T
1273    m.fill_diagonal_(diagonal_value)
1274    return m
1275
1276
1277def _calculate_iomin_between_pred_masks(masks, boxes, eps=1e-6):
1278    overlap_m = _overlap_matrix(boxes)
1279
1280    # Flatten spatial dimensions: (N, H*W) or (N, D*H*W)
1281    N = masks.shape[0]
1282    masks_flat = masks.reshape(N, -1).float()
1283
1284    # Per-mask area
1285    areas = masks_flat.sum(dim=1)  # (N,)
1286
1287    # Pairwise intersections via matrix multiplication
1288    # inter[i, j] = sum_k masks_flat[i, k] * masks_flat[j, k]
1289    inter = masks_flat @ masks_flat.t()  # (N, N)
1290
1291    # Denominator: min area of the two masks
1292    min_areas = torch.minimum(areas[:, None], areas[None, :])  # (N, N)
1293
1294    # IoMin = intersection / min(area_i, area_j)
1295    iomin = inter / (min_areas + eps)
1296
1297    # Set elements without any overlap explicitly to zero.
1298    iomin[~overlap_m] = 0
1299    return iomin
1300
1301
1302def _batched_mask_nms(masks, boxes, scores, nms_thresh, intersection_over_min):
1303    boxes = (
1304        boxes.detach() if isinstance(boxes, torch.Tensor) else torch.tensor(boxes)
1305    ).cpu()
1306    scores = (
1307        scores.detach() if isinstance(scores, torch.Tensor) else torch.tensor(scores)
1308    ).cpu()
1309    masks = (
1310        masks.detach() if isinstance(masks, torch.Tensor) else torch.tensor(masks)
1311    ).cpu()
1312
1313    if intersection_over_min:
1314        iou_matrix = _calculate_iomin_between_pred_masks(masks, boxes)
1315    else:
1316        iou_matrix = _calculate_ious_between_pred_masks(masks, boxes)
1317    sorted_indices = torch.argsort(scores, descending=True)
1318
1319    keep = []
1320    while len(sorted_indices) > 0:
1321        i = sorted_indices[0]
1322        keep.append(i)
1323
1324        if len(sorted_indices) == 1:
1325            break
1326
1327        iou_values = iou_matrix[i, sorted_indices[1:]]
1328        mask = iou_values <= nms_thresh
1329        sorted_indices = sorted_indices[1:][mask]
1330
1331    return torch.tensor(keep)
1332
1333
1334def _xywh_to_xyxy(boxes):
1335    boxes = boxes.clone() if isinstance(boxes, torch.Tensor) else torch.tensor(boxes)
1336    boxes = boxes.to(torch.float32)
1337    boxes[:, 2] += boxes[:, 0]
1338    boxes[:, 3] += boxes[:, 1]
1339    return boxes
1340
1341
1342def _infer_tiled_shape(predictions):
1343    shape = [0, 0]
1344    for pred in predictions:
1345        bbox, global_bbox = pred["bbox"], pred["global_bbox"]
1346        offset = (global_bbox[0] - bbox[0], global_bbox[1] - bbox[1])
1347        mask_shape = pred["segmentation"].shape
1348        shape[0] = max(shape[0], offset[1] + mask_shape[0])
1349        shape[1] = max(shape[1], offset[0] + mask_shape[1])
1350    return tuple(shape)
1351
1352
1353def _calculate_tiled_mask_overlap_matrix(masks, boxes, global_boxes, intersection_over_min):
1354    n_masks = len(masks)
1355    overlap_scores = torch.zeros((n_masks, n_masks))
1356    overlap_scores.fill_diagonal_(1)
1357
1358    boxes = (
1359        boxes.detach().cpu().to(dtype=torch.long)
1360        if isinstance(boxes, torch.Tensor) else torch.tensor(boxes, dtype=torch.long)
1361    )
1362    global_boxes = (
1363        global_boxes.detach().cpu().to(dtype=torch.long)
1364        if isinstance(global_boxes, torch.Tensor) else torch.tensor(global_boxes, dtype=torch.long)
1365    )
1366    global_boxes_xyxy = _xywh_to_xyxy(global_boxes).to(torch.long)
1367    overlap_m = _overlap_matrix(global_boxes_xyxy)
1368    masks = [mask.detach().cpu() if isinstance(mask, torch.Tensor) else torch.tensor(mask) for mask in masks]
1369    areas = torch.tensor([mask.sum() for mask in masks], dtype=torch.float32)
1370
1371    for i in range(n_masks):
1372        js = torch.where(overlap_m[i])[0]
1373        js_half = js[js > i]
1374        if len(js_half) == 0:
1375            continue
1376
1377        offset_i = global_boxes[i, :2] - boxes[i, :2]
1378        for j in js_half:
1379            offset_j = global_boxes[j, :2] - boxes[j, :2]
1380            overlap = [
1381                max(global_boxes_xyxy[i, 0], global_boxes_xyxy[j, 0]),
1382                max(global_boxes_xyxy[i, 1], global_boxes_xyxy[j, 1]),
1383                min(global_boxes_xyxy[i, 2], global_boxes_xyxy[j, 2]),
1384                min(global_boxes_xyxy[i, 3], global_boxes_xyxy[j, 3]),
1385            ]
1386
1387            mask_i = masks[i][
1388                overlap[1] - offset_i[1]:overlap[3] - offset_i[1],
1389                overlap[0] - offset_i[0]:overlap[2] - offset_i[0],
1390            ]
1391            mask_j = masks[j][
1392                overlap[1] - offset_j[1]:overlap[3] - offset_j[1],
1393                overlap[0] - offset_j[0]:overlap[2] - offset_j[0],
1394            ]
1395            intersection = torch.logical_and(mask_i, mask_j).sum()
1396            min_area = torch.minimum(areas[i], areas[j])
1397            denominator = min_area if intersection_over_min else areas[i] + areas[j] - intersection
1398            overlap_scores[i, j] = intersection / denominator
1399
1400    overlap_scores = overlap_scores + overlap_scores.T
1401    overlap_scores.fill_diagonal_(1)
1402    return overlap_scores
1403
1404
1405def _batched_tiled_mask_nms(masks, boxes, global_boxes, scores, nms_thresh, intersection_over_min):
1406    scores = (
1407        scores.detach() if isinstance(scores, torch.Tensor) else torch.tensor(scores)
1408    ).cpu()
1409
1410    iou_matrix = _calculate_tiled_mask_overlap_matrix(masks, boxes, global_boxes, intersection_over_min)
1411    sorted_indices = torch.argsort(scores, descending=True)
1412
1413    keep = []
1414    while len(sorted_indices) > 0:
1415        i = sorted_indices[0]
1416        keep.append(i)
1417
1418        if len(sorted_indices) == 1:
1419            break
1420
1421        iou_values = iou_matrix[i, sorted_indices[1:]]
1422        mask = iou_values <= nms_thresh
1423        sorted_indices = sorted_indices[1:][mask]
1424
1425    return torch.tensor(keep)
1426
1427
1428def _largest_component(mask: np.ndarray) -> np.ndarray:
1429    """The largest connected component of a binary mask, with the connectivity 'label_masks' relabels with."""
1430    components = label(mask, connectivity=1)
1431    sizes = np.bincount(components.ravel().astype("int64"))[1:]
1432    if len(sizes) < 2:
1433        return mask
1434    return components == (sizes.argmax() + 1)
1435
1436
1437def mask_data_to_segmentation(
1438    masks: List[Dict[str, Any]],
1439    shape: Optional[Tuple[int, int]] = None,
1440    min_object_size: int = 0,
1441    max_object_size: Optional[int] = None,
1442    label_masks: bool = True,
1443    with_background: bool = False,
1444    merge_exclusively: bool = True,
1445    keep_largest_component: bool = False,
1446    max_overlap: Optional[float] = None,
1447) -> np.ndarray:
1448    """Convert the output of the automatic mask generation to an instance segmentation.
1449
1450    Args:
1451        masks: The outputs generated by `AutomaticMaskGenerator`, other classes from
1452            `micro_sam.v1.instance_segmentation`, or from `micro_sam.v1.inference` functions. Only
1453            supported for output_mode=binary_mask.
1454        shape: The shape of the output segmentation. If None, it will be derived from the mask input.
1455            If the mask where predicted with tiling then the shape must be given.
1456        min_object_size: The minimal size of an object in pixels. By default, set to '0'.
1457        max_object_size: The maximal size of an object in pixels.
1458        label_masks: Whether to apply connected components to the result before removing small objects.
1459            By default, set to 'True'.
1460        with_background: Whether to remove the largest object, which often covers the background for AMG.
1461        merge_exclusively: Whether to exclude previous merged masks from merging.
1462        keep_largest_component: Whether to paint only the largest connected component of the pixels a
1463            mask can still claim. Otherwise the pieces that the masks merged before it cut off become
1464            objects of their own once 'label_masks' runs: the slivers and rings that duplicate masks
1465            of one object leave behind. Only meaningful together with 'merge_exclusively'.
1466        max_overlap: Skip a mask when more than this fraction of it is already claimed, after
1467            'keep_largest_component'. Such a mask is a duplicate of the ones merged before it, which
1468            the NMS let through, and only its leftovers would be painted. None (the default) keeps it.
1469
1470    Returns:
1471        The instance segmentation.
1472    """
1473    masks = sorted(masks, key=(lambda x: x["area"]), reverse=True)
1474    if shape is None:
1475        shape = next(iter(masks))["segmentation"].shape
1476    segmentation = np.zeros(shape, dtype="uint32")
1477
1478    def require_numpy(mask):
1479        return mask.cpu().numpy() if torch.is_tensor(mask) else mask
1480
1481    seg_id = 1
1482    for mask_data in masks:
1483        area = mask_data["area"]
1484        if (area < min_object_size) or (max_object_size is not None and area > max_object_size):
1485            continue
1486
1487        this_mask = require_numpy(mask_data["segmentation"])
1488        this_seg_id = mask_data.get("seg_id", seg_id)
1489        if "global_bbox" in mask_data:
1490            bb = mask_data["bbox"]
1491            bb = np.s_[bb[1]:bb[1] + bb[3], bb[0]:bb[0] + bb[2]]
1492            global_bb = mask_data["global_bbox"]
1493            global_bb = np.s_[global_bb[1]:global_bb[1] + global_bb[3], global_bb[0]:global_bb[0] + global_bb[2]]
1494            # A view, so painting below writes straight into the output.
1495            target = segmentation[global_bb]
1496            this_mask = this_mask[bb]
1497        else:
1498            target = segmentation
1499        if merge_exclusively:
1500            this_mask = np.logical_and(this_mask, target == 0)
1501        if keep_largest_component:
1502            this_mask = _largest_component(this_mask)
1503        if max_overlap is not None and this_mask.sum() < (1 - max_overlap) * area:
1504            continue
1505        target[this_mask] = this_seg_id
1506        seg_id = this_seg_id + 1
1507
1508    block_shape = (512, 512)
1509    if label_masks:
1510        segmentation_cc = np.zeros_like(segmentation, dtype=segmentation.dtype)
1511        segmentation_cc = parallel_impl.label(segmentation, out=segmentation_cc, block_shape=block_shape)
1512        segmentation = segmentation_cc
1513
1514    seg_ids, sizes = parallel_impl.unique(segmentation, return_counts=True, block_shape=block_shape)
1515    filter_ids = seg_ids[sizes < min_object_size]
1516    if with_background:
1517        bg_id = seg_ids[np.argmax(sizes)]
1518        filter_ids = np.concatenate([filter_ids, [bg_id]])
1519
1520    filter_mask = np.zeros(segmentation.shape, dtype="bool")
1521    filter_mask = parallel_impl.isin(segmentation, filter_ids, out=filter_mask, block_shape=block_shape)
1522    segmentation[filter_mask] = 0
1523    parallel_impl.relabel_consecutive(segmentation, block_shape=block_shape)[0]
1524
1525    return segmentation
1526
1527
1528def apply_nms(
1529    predictions: List[Dict[str, Any]],
1530    min_size: int,
1531    shape: Optional[Tuple[int, int]] = None,
1532    perform_box_nms: bool = False,
1533    nms_thresh: float = 0.9,
1534    max_size: Optional[int] = None,
1535    intersection_over_min: bool = False,
1536    keep_largest_component: bool = False,
1537    max_overlap: Optional[float] = None,
1538) -> np.ndarray:
1539    """Apply non-maximum suppression to mask predictions from a segment anything model.
1540
1541    Args:
1542        predictions: The mask predictions from SAM.
1543        min_size: The minimum mask size to keep in the output.
1544        shape: The shape of the output segmentation.
1545            For tiled predictions this is inferred from the tile-local mask shapes if it is not passed.
1546        perform_box_nms: Whether to perform NMS on the box coordinates or on the masks.
1547        nms_thresh: The threshold for filtering out objects in NMS.
1548        max_size: The maximum mask size to keep in the output.
1549        intersection_over_min: Whether to perform intersection over the minimum overlap shape
1550            or to perform intersection over union.
1551        keep_largest_component: Whether to merge only the largest connected component of what each
1552            mask can still claim, see `mask_data_to_segmentation`.
1553        max_overlap: Skip a mask in the merge when more than this fraction of it is already claimed,
1554            see `mask_data_to_segmentation`.
1555
1556    Returns:
1557        The segmentation obtained from merging the masks left after NMS.
1558    """
1559    # Check if the input comes with a 'global_bbox' attribute. If it does, then the predictions are from
1560    # a tiled prediction. In this case, we have to take the coordinates w.r.t. the tiling into account.
1561    is_tiled = "global_bbox" in predictions[0]
1562    if is_tiled and shape is None:
1563        shape = _infer_tiled_shape(predictions)
1564
1565    masks = [pred["segmentation"] for pred in predictions]
1566    nms_masks = None if is_tiled else torch.cat([mask[None] for mask in masks], dim=0)
1567    data = amg_utils.MaskData(masks=masks, iou_preds=torch.tensor([pred["predicted_iou"] for pred in predictions]))
1568    data["boxes"] = torch.tensor(np.array([pred["bbox"] for pred in predictions]))
1569    data["area"] = [int(mask.sum()) for mask in data["masks"]]
1570    data["stability_scores"] = torch.tensor([pred["stability_score"] for pred in predictions])
1571    if is_tiled:
1572        data["global_boxes"] = torch.tensor(np.array([pred["global_bbox"] for pred in predictions]))
1573
1574    if min_size > 0:
1575        keep_by_size = torch.tensor(
1576            [i for i, area in enumerate(data["area"]) if area > min_size], dtype=torch.long,
1577        )
1578        data.filter(keep_by_size)
1579        if nms_masks is not None:
1580            nms_masks = nms_masks[keep_by_size]
1581
1582    if max_size is not None:
1583        keep_by_size = torch.tensor([i for i, area in enumerate(data["area"]) if area < max_size])
1584        data.filter(keep_by_size)
1585        if nms_masks is not None:
1586            nms_masks = nms_masks[keep_by_size]
1587
1588    if len(data["masks"]) == 0:
1589        if shape is None:
1590            shape = predictions[0]["segmentation"].shape
1591        return np.zeros(shape, dtype="uint32")
1592
1593    scores = data["iou_preds"] * data["stability_scores"]
1594    boxes = _xywh_to_xyxy(data["global_boxes"] if is_tiled else data["boxes"])
1595    if perform_box_nms:
1596        assert not intersection_over_min  # not implemented
1597        keep_by_nms = batched_nms(
1598            boxes,
1599            scores,
1600            torch.zeros_like(data["boxes"][:, 0]),  # categories
1601            iou_threshold=nms_thresh,
1602        )
1603    elif is_tiled:
1604        keep_by_nms = _batched_tiled_mask_nms(
1605            masks=data["masks"],
1606            boxes=data["boxes"],
1607            global_boxes=data["global_boxes"],
1608            scores=scores,
1609            nms_thresh=nms_thresh,
1610            intersection_over_min=intersection_over_min,
1611        )
1612    else:
1613        keep_by_nms = _batched_mask_nms(
1614            masks=nms_masks,
1615            boxes=boxes,
1616            scores=scores,
1617            nms_thresh=nms_thresh,
1618            intersection_over_min=intersection_over_min,
1619        )
1620    data.filter(keep_by_nms)
1621
1622    if is_tiled:
1623        mask_data = [
1624            {"segmentation": mask, "area": area, "bbox": box, "global_bbox": global_box}
1625            for mask, area, box, global_box in zip(data["masks"], data["area"], data["boxes"], data["global_boxes"])
1626        ]
1627    else:
1628        mask_data = [
1629            {"segmentation": mask, "area": area, "bbox": box}
1630            for mask, area, box in zip(data["masks"], data["area"], data["boxes"])
1631        ]
1632
1633    if shape is None:
1634        shape = predictions[0]["segmentation"].shape
1635    if mask_data:
1636        segmentation = mask_data_to_segmentation(
1637            mask_data, shape=shape, min_object_size=min_size,
1638            keep_largest_component=keep_largest_component, max_overlap=max_overlap,
1639        )
1640    else:  # In case all objects have been filtered out due to size filtering.
1641        segmentation = np.zeros(shape, dtype="uint32")
1642
1643    return segmentation
DEFAULT_SAM1_MODEL = 'vit_b_lm'
SAM1_MODEL_TYPES = ('vit_l', 'vit_b', 'vit_h', 'vit_t')
class AutoSegBase(abc.ABC):
 73class AutoSegBase(ABC):
 74    """Common interface for automatic-segmentation generators.
 75
 76    Unifies the grid-based mask generators (`micro_sam.v1.instance_segmentation.AMGBase` and its
 77    subclasses) and the decoder-based instance segmentation
 78    (`micro_sam.v1.instance_segmentation.InstanceSegmentationWithDecoder` and its subclasses), for
 79    both SAM1 and SAM2: all of them are initialized on an image, produce an instance segmentation
 80    via `generate`, and cache / restore their expensive intermediate state via
 81    `get_state` / `set_state`. It lives here, next to the other shared types, so that it can be
 82    referenced in annotations without importing an implementation (and with it the training stack).
 83    """
 84
 85    @property
 86    def is_initialized(self) -> bool:
 87        """Whether `initialize` ran and the state is available."""
 88        return self._is_initialized
 89
 90    @abstractmethod
 91    def initialize(self, *args, **kwargs) -> None:
 92        """Compute and store the (expensive) state needed by `generate`."""
 93
 94    @abstractmethod
 95    def generate(self, *args, **kwargs):
 96        """Produce the instance segmentation from the initialized state."""
 97
 98    @abstractmethod
 99    def get_state(self) -> Dict[str, Any]:
100        """Return the cached state so it can be serialized and later restored."""
101
102    @abstractmethod
103    def set_state(self, state: Dict[str, Any]) -> None:
104        """Restore a state produced by `get_state`."""
105
106    @abstractmethod
107    def clear_state(self) -> None:
108        """Clear the cached state."""

Common interface for automatic-segmentation generators.

Unifies the grid-based mask generators (micro_sam.v1.instance_segmentation.AMGBase and its subclasses) and the decoder-based instance segmentation (micro_sam.v1.instance_segmentation.InstanceSegmentationWithDecoder and its subclasses), for both SAM1 and SAM2: all of them are initialized on an image, produce an instance segmentation via generate, and cache / restore their expensive intermediate state via get_state / set_state. It lives here, next to the other shared types, so that it can be referenced in annotations without importing an implementation (and with it the training stack).

is_initialized: bool
85    @property
86    def is_initialized(self) -> bool:
87        """Whether `initialize` ran and the state is available."""
88        return self._is_initialized

Whether initialize ran and the state is available.

@abstractmethod
def initialize(self, *args, **kwargs) -> None:
90    @abstractmethod
91    def initialize(self, *args, **kwargs) -> None:
92        """Compute and store the (expensive) state needed by `generate`."""

Compute and store the (expensive) state needed by generate.

@abstractmethod
def generate(self, *args, **kwargs):
94    @abstractmethod
95    def generate(self, *args, **kwargs):
96        """Produce the instance segmentation from the initialized state."""

Produce the instance segmentation from the initialized state.

@abstractmethod
def get_state(self) -> Dict[str, Any]:
 98    @abstractmethod
 99    def get_state(self) -> Dict[str, Any]:
100        """Return the cached state so it can be serialized and later restored."""

Return the cached state so it can be serialized and later restored.

@abstractmethod
def set_state(self, state: Dict[str, Any]) -> None:
102    @abstractmethod
103    def set_state(self, state: Dict[str, Any]) -> None:
104        """Restore a state produced by `get_state`."""

Restore a state produced by get_state.

@abstractmethod
def clear_state(self) -> None:
106    @abstractmethod
107    def clear_state(self) -> None:
108        """Clear the cached state."""

Clear the cached state.

def get_cache_directory() -> pathlib.Path:
111def get_cache_directory() -> Path:
112    """Get the micro-sam cache directory location.
113
114    This is the top level cache directory for micro-sam models, sample data and temporary embeddings.
115    Users can set the MICROSAM_CACHEDIR environment variable for a custom cache directory.
116    The function reads the variable on every call, so updates take effect immediately.
117
118    Returns:
119        The cache directory.
120    """
121    cache_directory = os.environ.get("MICROSAM_CACHEDIR") or pooch.os_cache("micro_sam")
122    return Path(os.path.expanduser(cache_directory))

Get the micro-sam cache directory location.

This is the top level cache directory for micro-sam models, sample data and temporary embeddings. Users can set the MICROSAM_CACHEDIR environment variable for a custom cache directory. The function reads the variable on every call, so updates take effect immediately.

Returns:

The cache directory.

def get_model_cache_directory(name: Optional[str] = None) -> pathlib.Path:
125def get_model_cache_directory(name: Optional[str] = None) -> Path:
126    """Get the directory where micro-sam stores downloaded model weights.
127
128    All model downloads go to the 'models' folder of the micro-sam cache directory, so that each
129    model is stored only once. The SAM, micro-sam, SAM2 and micro-sam2 checkpoints are files
130    directly in this folder. The weights of third-party models (e.g. 'anyup', 'dino/v2', 'dino/v3',
131    'uni', 'sam3', 'trackastra') go to a subfolder.
132
133    Args:
134        name: The optional subfolder for a third-party model.
135
136    Returns:
137        The model cache directory.
138    """
139    model_directory = get_cache_directory() / "models"
140    return model_directory if name is None else model_directory / name

Get the directory where micro-sam stores downloaded model weights.

All model downloads go to the 'models' folder of the micro-sam cache directory, so that each model is stored only once. The SAM, micro-sam, SAM2 and micro-sam2 checkpoints are files directly in this folder. The weights of third-party models (e.g. 'anyup', 'dino/v2', 'dino/v3', 'uni', 'sam3', 'trackastra') go to a subfolder.

Arguments:
  • name: The optional subfolder for a third-party model.
Returns:

The model cache directory.

def make_temp_embedding_path() -> str:
143def make_temp_embedding_path() -> str:
144    """Create a fresh ephemeral on-disk zarr path for streaming image embeddings.
145
146    Used when no explicit embedding save path is given: caching to disk (under the micro-sam cache
147    directory, honoring MICROSAM_CACHEDIR) instead of holding the whole volume in RAM keeps memory
148    bounded on large volumes / tiled images. The cache is disk-backed rather than in /tmp, which is
149    tmpfs (RAM) on many systems. The caller owns eager cleanup; the returned path is also removed on
150    process exit.
151    """
152    parent = get_cache_directory() / "tmp_embeddings"
153    parent.mkdir(parents=True, exist_ok=True)
154    path = str(parent / f"{uuid.uuid4().hex}.zarr")
155    atexit.register(shutil.rmtree, path, ignore_errors=True)
156    return path

Create a fresh ephemeral on-disk zarr path for streaming image embeddings.

Used when no explicit embedding save path is given: caching to disk (under the micro-sam cache directory, honoring MICROSAM_CACHEDIR) instead of holding the whole volume in RAM keeps memory bounded on large volumes / tiled images. The cache is disk-backed rather than in /tmp, which is tmpfs (RAM) on many systems. The caller owns eager cleanup; the returned path is also removed on process exit.

def get_gpu_setup_warning() -> Optional[str]:
198def get_gpu_setup_warning() -> Optional[str]:
199    """Check if the computer has an NVIDIA GPU that PyTorch cannot use.
200
201    Package managers sometimes install a CPU-only PyTorch on computers with an NVIDIA GPU.
202    micro_sam then runs on the CPU without an error, which is much slower.
203
204    Returns:
205        A warning that explains the problem and the fix, or None if PyTorch can use the GPU or there is no NVIDIA GPU.
206    """
207    if torch.cuda.is_available() or not _has_nvidia_gpu():
208        return None
209    if torch.version.cuda is None:
210        return (
211            "This computer has an NVIDIA GPU, but the installed PyTorch is a CPU-only build, so micro_sam runs on the "
212            "CPU. To use the GPU, install micro_sam with a CUDA build of PyTorch, e.g. by adding \"pytorch=*=cuda*\" "
213            "to the conda / mamba command. See https://computational-cell-analytics.github.io/micro-sam for details."
214        )
215    return (
216        f"This computer has an NVIDIA GPU, but PyTorch (built for CUDA {torch.version.cuda}) cannot use it, so "
217        "micro_sam runs on the CPU. The NVIDIA driver may be too old for this PyTorch build. Update the driver, or "
218        "install a PyTorch build for an older CUDA version, e.g. by adding \"cuda-version=12\" to the conda / mamba "
219        "command."
220    )

Check if the computer has an NVIDIA GPU that PyTorch cannot use.

Package managers sometimes install a CPU-only PyTorch on computers with an NVIDIA GPU. micro_sam then runs on the CPU without an error, which is much slower.

Returns:

A warning that explains the problem and the fix, or None if PyTorch can use the GPU or there is no NVIDIA GPU.

def device_type(device: Union[str, torch.device]) -> str:
223def device_type(device: Union[str, torch.device]) -> str:
224    """Get the device type ('cpu', 'cuda' or 'mps'), ignoring any device index.
225
226    Torch reports accelerators with an index (e.g. 'mps:0'), so comparing 'str(device)' against
227    'mps' or 'cuda' silently fails. Compare against this instead.
228
229    Args:
230        device: The device, as a string or torch.device.
231
232    Returns:
233        The device type.
234    """
235    return torch.device(device).type

Get the device type ('cpu', 'cuda' or 'mps'), ignoring any device index.

Torch reports accelerators with an index (e.g. 'mps:0'), so comparing 'str(device)' against 'mps' or 'cuda' silently fails. Compare against this instead.

Arguments:
  • device: The device, as a string or torch.device.
Returns:

The device type.

def get_device( device: Union[str, torch.device, NoneType] = None) -> Union[str, torch.device]:
254def get_device(device: Optional[Union[str, torch.device]] = None) -> Union[str, torch.device]:
255    """Get the torch device.
256
257    If no device is passed the default device for your system is used.
258    Else it will be checked if the device you have passed is supported.
259
260    Args:
261        device: The input device. By default, selects the best available device supports.
262
263    Returns:
264        The device.
265    """
266    if device is None or device == "auto":
267        device = _get_default_device()
268    else:
269        try:
270            requested_type = device_type(device)
271        except (RuntimeError, TypeError) as e:
272            raise RuntimeError(
273                f"Unsupported device: '{device}'. Please choose from 'cpu', 'cuda', or 'mps'."
274            ) from e
275
276        if requested_type == "cuda":
277            if not torch.cuda.is_available():
278                raise RuntimeError("PyTorch CUDA backend is not available.")
279        elif requested_type == "mps":
280            if not (torch.backends.mps.is_available() and torch.backends.mps.is_built()):
281                raise RuntimeError("PyTorch MPS backend is not available or is not built correctly.")
282        elif requested_type == "cpu":
283            pass  # cpu is always available
284        else:
285            raise RuntimeError(f"Unsupported device: '{device}'. Please choose from 'cpu', 'cuda', or 'mps'.")
286
287    _configure_mps_memory(device)
288    return device

Get the torch device.

If no device is passed the default device for your system is used. Else it will be checked if the device you have passed is supported.

Arguments:
  • device: The input device. By default, selects the best available device supports.
Returns:

The device.

BF16_MIN_CAPABILITY = (8, 0)
def training_autocast_dtype( device: Union[str, torch.device, NoneType] = None) -> Optional[torch.dtype]:
296def training_autocast_dtype(device: Optional[Union[str, torch.device]] = None) -> Optional[torch.dtype]:
297    """The dtype that training runs in on a device.
298
299    Training runs in bfloat16 or fp32, never float16: float16 needs loss scaling and still overflows
300    in the decoder convolutions on GPUs that accumulate it in half precision.
301
302    Args:
303        device: The device the forward pass runs on. Defaults to the best available one.
304
305    Returns:
306        bfloat16 where the device runs it natively, or None where training stays in fp32.
307    """
308    device = torch.device(get_device() if device is None else device)
309    if device.type != "cuda" or not torch.cuda.is_available():
310        return None
311    return torch.bfloat16 if torch.cuda.get_device_capability(device) >= BF16_MIN_CAPABILITY else None

The dtype that training runs in on a device.

Training runs in bfloat16 or fp32, never float16: float16 needs loss scaling and still overflows in the decoder convolutions on GPUs that accumulate it in half precision.

Arguments:
  • device: The device the forward pass runs on. Defaults to the best available one.
Returns:

bfloat16 where the device runs it natively, or None where training stays in fp32.

def get_embedding_function(model_type: str) -> <built-in function callable>:
314def get_embedding_function(model_type: str) -> callable:
315    """Get the precompute-embeddings function for the model family of `model_type`.
316
317    Dispatches across the three families: VFM (DINO / UNI) encoders, SAM2 ('hvit_*') and SAM1 ('vit_*').
318    All returned functions share the interface (predictor, input_, save_path, ndim, tile_shape, halo,
319    verbose, lazy_loading, pbar_init, pbar_update).
320
321    Args:
322        model_type: The model name, e.g. 'vit_b_lm', 'hvit_t' or 'vit_b_dinov2'.
323
324    Returns:
325        The matching `precompute_image_embeddings` / `precompute_vfm_embeddings` function.
326
327    Raises:
328        ValueError: If `model_type` does not belong to any supported model family.
329    """
330    from .models.vfm import is_vfm_model, get_vfm_model_names
331    from .v2.util import SUPPORTED_MODELS as sam2_backbones
332
333    if is_vfm_model(model_type):
334        from .models.vfm import precompute_vfm_embeddings
335        return precompute_vfm_embeddings
336
337    # Finetuned names keep their backbone prefix ('vit_b_lm' -> 'vit_b', 'hvit_t_cells' -> 'hvit_t').
338    if isinstance(model_type, str) and model_type[:6] in sam2_backbones:
339        from .v2.util import precompute_image_embeddings
340        return precompute_image_embeddings
341    if isinstance(model_type, str) and model_type[:5] in SAM1_MODEL_TYPES:
342        from .v1.util import precompute_image_embeddings
343        return precompute_image_embeddings
344
345    raise ValueError(
346        f"Invalid model_type: '{model_type}'. Expected a SAM1 model (backbone one of {list(SAM1_MODEL_TYPES)}), "
347        f"a SAM2 model (backbone one of {sam2_backbones}) or a VFM encoder (one of {list(get_vfm_model_names())}). "
348        "Finetuned models keep their backbone prefix, e.g. 'vit_b_lm' or 'hvit_t_cells'. "
349        "Run 'micro_sam info' to list all available models."
350    )

Get the precompute-embeddings function for the model family of model_type.

Dispatches across the three families: VFM (DINO / UNI) encoders, SAM2 ('hvit_*') and SAM1 ('vit_*'). All returned functions share the interface (predictor, input_, save_path, ndim, tile_shape, halo, verbose, lazy_loading, pbar_init, pbar_update).

Arguments:
  • model_type: The model name, e.g. 'vit_b_lm', 'hvit_t' or 'vit_b_dinov2'.
Returns:

The matching precompute_image_embeddings / precompute_vfm_embeddings function.

Raises:
  • ValueError: If model_type does not belong to any supported model family.
def load_checkpoint( checkpoint_path: Union[str, os.PathLike], map_location: Any = 'cpu') -> Any:
460def load_checkpoint(checkpoint_path: Union[str, os.PathLike], map_location: Any = "cpu") -> Any:
461    """Load a checkpoint, and skip the objects whose class cannot be imported.
462
463    A torch_em training checkpoint also holds the settings of the data loaders, for example the
464    transforms. A transform that the training script defined itself cannot be imported elsewhere.
465    The weights do not need these objects, so they are skipped with a warning.
466
467    Args:
468        checkpoint_path: The path to the checkpoint.
469        map_location: Where to map the tensors to. By default the CPU.
470
471    Returns:
472        The content of the checkpoint.
473    """
474    # A copy of the pickle module with the tolerant unpickler, so the pickle module itself stays unchanged.
475    skip_missing_pickle = types.ModuleType("skip_missing_pickle")
476    skip_missing_pickle.__dict__.update(pickle.__dict__)
477    skip_missing_pickle.Unpickler = _CustomUnpickler
478    return torch.load(checkpoint_path, map_location=map_location, pickle_module=skip_missing_pickle, weights_only=False)

Load a checkpoint, and skip the objects whose class cannot be imported.

A torch_em training checkpoint also holds the settings of the data loaders, for example the transforms. A transform that the training script defined itself cannot be imported elsewhere. The weights do not need these objects, so they are skipped with a warning.

Arguments:
  • checkpoint_path: The path to the checkpoint.
  • map_location: Where to map the tensors to. By default the CPU.
Returns:

The content of the checkpoint.

EMBEDDING_ZARR_FORMAT = 3
EMBEDDING_COMPRESSION = 'blosc'
DATA_SIGNATURE_BLOCK_SIZE = 67108864
def match_image_shape(labels: numpy.ndarray, image_shape: Tuple[int, ...]) -> numpy.ndarray:
667def match_image_shape(labels: np.ndarray, image_shape: Tuple[int, ...]) -> np.ndarray:
668    """Bring a label image, such as a segmentation or annotations, to the shape of a prepared image.
669
670    `prepare_annotation_image` squeezes singleton axes from the image, so the labels lose the same
671    singleton axes. Any other difference in shape is an error.
672
673    Args:
674        labels: The label image.
675        image_shape: The spatial shape of the prepared image.
676
677    Returns:
678        The label image in the shape of the image.
679
680    Raises:
681        ValueError: If the shapes differ in more than singleton axes.
682    """
683    labels = np.asarray(labels)
684    image_shape = tuple(image_shape)
685    if labels.shape == image_shape:
686        return labels
687    if np.squeeze(labels).shape != tuple(size for size in image_shape if size != 1):
688        raise ValueError(f"The labels of shape {labels.shape} do not match the image of shape {image_shape}.")
689    return labels.reshape(image_shape)

Bring a label image, such as a segmentation or annotations, to the shape of a prepared image.

prepare_annotation_image squeezes singleton axes from the image, so the labels lose the same singleton axes. Any other difference in shape is an error.

Arguments:
  • labels: The label image.
  • image_shape: The spatial shape of the prepared image.
Returns:

The label image in the shape of the image.

Raises:
  • ValueError: If the shapes differ in more than singleton axes.
def prepare_annotation_image( image: numpy.ndarray, ndim: Optional[int] = None) -> Tuple[numpy.ndarray, int, bool]:
692def prepare_annotation_image(image: np.ndarray, ndim: Optional[int] = None) -> Tuple[np.ndarray, int, bool]:
693    """Normalize an image for annotation: squeeze singletons and map 2D channels to RGB.
694
695    Singleton axes (commonly exposed by formats like CZI) are squeezed out across all axes.
696    For a 2D image, the trailing channel axis is mapped to 3 channels: a 2-channel input is
697    padded with a zero channel and a 4-channel input is reduced to the first three (with a
698    warning). A 3D volume with a channel axis (3D+C) gets the same mapping on a trailing channel axis.
699
700    Args:
701        image: The input image data.
702        ndim: Optional override for the spatial dimensionality (2 or 3). A single-slice ``(1, H, W)``
703            volume keeps its z axis when ``3`` is passed. With ``None`` (the default)
704            the dimensionality is auto-detected from the shape (a trailing axis of size 3 -> RGB 2D,
705            of size 2 or 4 -> channels mapped to RGB 2D, otherwise a 3D volume). With ``2`` a 3D array
706            is read as a 2D multi-channel image, taking the smallest axis as the channel axis (so a
707            channels-first ``(C, H, W)`` array also works) and mapping the channels to RGB. With ``3``
708            a 3D array is read as a ``(Z, H, W)`` volume, and a 4D array as a volume with a channel
709            axis of size 2 to 4 at position 3, 1 or 0 (checked in that order), moved to the trailing
710            position. A 4D array with a trailing axis of size 2 to 4 is auto-detected as such a volume.
711
712    Returns:
713        A tuple of the normalized image, its spatial dimensionality (2 or 3), and whether
714        it has a trailing RGB channel axis.
715
716    Raises:
717        ValueError: If the (overridden) dimensionality cannot be applied to the image shape, or the
718            squeezed image is neither a 2D image nor a grayscale 3D volume.
719    """
720    if ndim not in (None, 2, 3):
721        raise ValueError(f"Invalid ndim override: {ndim}. Expected None, 2 or 3.")
722
723    input_ndim = image.ndim
724    image = np.squeeze(image)
725
726    # Forced 2D: read a 3D array as a 2D multi-channel image. The channel axis is taken to be the
727    # smallest axis (so both channels-first (C, H, W) and channels-last (H, W, C) work); it is moved
728    # to the trailing position and mapped to 3 channels.
729    if ndim == 2:
730        if image.ndim == 2:
731            return image, 2, False
732        if image.ndim == 3:
733            channel_axis = int(np.argmin(image.shape))
734            image = np.moveaxis(image, channel_axis, -1)
735            return _channels_to_rgb(image), 2, True
736        raise ValueError(f"Cannot interpret shape {image.shape} as a 2D image.")
737
738    # Forced 3D: read a 3D array as a (Z, H, W) volume, and a 4D array as a volume with a channel axis.
739    if ndim == 3:
740        if image.ndim == 3:
741            return image, 3, False
742        # A single-slice volume squeezes down to one plane; put the z axis back rather than reject
743        # it. A genuinely 2d input still raises: asking for a volume and passing a plane is an error.
744        if image.ndim == 2 and input_ndim == 3:
745            return image[None], 3, False
746        if image.ndim == 4:
747            # Channels-last (Z, H, W, C), channels-second (Z, C, H, W) or channels-first (C, Z, H, W).
748            channel_axis = next((axis for axis in (3, 1, 0) if image.shape[axis] in (2, 3, 4)), None)
749            if channel_axis is not None:
750                image = np.moveaxis(image, channel_axis, -1)
751                return _channels_to_rgb(image), 3, True
752        raise ValueError(f"Cannot interpret shape {image.shape} as a 3D volume.")
753
754    # Auto-detect. A 4D array with a trailing axis of size 2, 3 or 4 is a volume with channels
755    # (Z, H, W, C). Any other 4D array may be a volumetric time series (T, Z, H, W), which is not supported.
756    if image.ndim == 4:
757        if image.shape[-1] in (2, 3, 4):
758            return _channels_to_rgb(image), 3, True
759        raise ValueError(
760            f"Invalid image shape: {image.shape}. Expected 2D or 3D image data (3D+t is not supported). "
761            "Pass ndim=3 for a volume with a non-trailing channel axis."
762        )
763
764    # 2D image with a 2- or 4-channel trailing axis: map it to 3 channels. A trailing axis of any
765    # other size is left alone, so a size-3 axis stays RGB and anything else is treated as a volume.
766    if image.ndim == 3 and image.shape[-1] in (2, 4):
767        image = _channels_to_rgb(image)
768
769    # Map the (possibly normalized) shape to a spatial dimensionality and rgb flag.
770    if image.ndim == 2:
771        return image, 2, False
772    elif image.ndim == 3:
773        if image.shape[-1] == 3:
774            return image, 2, True
775        return image, 3, False
776    raise ValueError(f"Invalid image shape: {image.shape}. Expected 2D or 3D image data.")

Normalize an image for annotation: squeeze singletons and map 2D channels to RGB.

Singleton axes (commonly exposed by formats like CZI) are squeezed out across all axes. For a 2D image, the trailing channel axis is mapped to 3 channels: a 2-channel input is padded with a zero channel and a 4-channel input is reduced to the first three (with a warning). A 3D volume with a channel axis (3D+C) gets the same mapping on a trailing channel axis.

Arguments:
  • image: The input image data.
  • ndim: Optional override for the spatial dimensionality (2 or 3). A single-slice (1, H, W) volume keeps its z axis when 3 is passed. With None (the default) the dimensionality is auto-detected from the shape (a trailing axis of size 3 -> RGB 2D, of size 2 or 4 -> channels mapped to RGB 2D, otherwise a 3D volume). With 2 a 3D array is read as a 2D multi-channel image, taking the smallest axis as the channel axis (so a channels-first (C, H, W) array also works) and mapping the channels to RGB. With 3 a 3D array is read as a (Z, H, W) volume, and a 4D array as a volume with a channel axis of size 2 to 4 at position 3, 1 or 0 (checked in that order), moved to the trailing position. A 4D array with a trailing axis of size 2 to 4 is auto-detected as such a volume.
Returns:

A tuple of the normalized image, its spatial dimensionality (2 or 3), and whether it has a trailing RGB channel axis.

Raises:
  • ValueError: If the (overridden) dimensionality cannot be applied to the image shape, or the squeezed image is neither a 2D image nor a grayscale 3D volume.
def read_cached_tiling(embedding_path: Union[str, os.PathLike, NoneType]) -> Optional[Tuple]:
779def read_cached_tiling(embedding_path: Optional[Union[str, os.PathLike]]) -> Optional[Tuple]:
780    """Read the tiling that cached embeddings were computed with.
781
782    The tiling is part of the embedding signature, so embeddings computed with a different tiling
783    than the one requested are discarded and recomputed. Reading it back lets the annotation tools
784    reuse an existing cache instead of recomputing it just because their default tiling differs from
785    the one it was computed with (see `micro_sam.v2.util.resolve_default_tiling`).
786
787    Args:
788        embedding_path: The filepath of the cached embeddings. May also be None or already loaded
789            embeddings, in which case there is nothing to read.
790
791    Returns:
792        The in-plane (tile_shape, halo) of the cached embeddings, where a tile shape of None means
793        they were computed without tiling. None if `embedding_path` holds no embeddings (yet).
794    """
795    if not isinstance(embedding_path, (str, os.PathLike)) or not os.path.exists(embedding_path):
796        return None
797
798    try:
799        f = _open_embeddings(embedding_path, mode="r")
800    except (OSError, RuntimeError):  # Not a readable container, e.g. an empty folder from a failed run.
801        return None
802
803    try:
804        # 'tile_shape' is only written once the embeddings are complete, so a partial cache (which
805        # will be recomputed anyway) does not advertise a tiling.
806        if "tile_shape" not in f.attrs:
807            return None
808        tile_shape, halo = f.attrs["tile_shape"], f.attrs.get("halo")
809    finally:
810        getattr(f, "file", f).close()
811
812    return (
813        None if tile_shape is None else tuple(tile_shape),
814        None if halo is None else tuple(halo),
815    )

Read the tiling that cached embeddings were computed with.

The tiling is part of the embedding signature, so embeddings computed with a different tiling than the one requested are discarded and recomputed. Reading it back lets the annotation tools reuse an existing cache instead of recomputing it just because their default tiling differs from the one it was computed with (see micro_sam.v2.util.resolve_default_tiling).

Arguments:
  • embedding_path: The filepath of the cached embeddings. May also be None or already loaded embeddings, in which case there is nothing to read.
Returns:

The in-plane (tile_shape, halo) of the cached embeddings, where a tile shape of None means they were computed without tiling. None if embedding_path holds no embeddings (yet).

def compute_iou(mask1: numpy.ndarray, mask2: numpy.ndarray) -> float:
877def compute_iou(mask1: np.ndarray, mask2: np.ndarray) -> float:
878    """Compute the intersection over union of two masks.
879
880    Args:
881        mask1: The first mask.
882        mask2: The second mask.
883
884    Returns:
885        The intersection over union of the two masks.
886    """
887    overlap = np.logical_and(mask1 == 1, mask2 == 1).sum()
888    union = np.logical_or(mask1 == 1, mask2 == 1).sum()
889    eps = 1e-7
890    iou = float(overlap) / (float(union) + eps)
891    return iou

Compute the intersection over union of two masks.

Arguments:
  • mask1: The first mask.
  • mask2: The second mask.
Returns:

The intersection over union of the two masks.

def get_centers_and_bounding_boxes( segmentation: numpy.ndarray, mode: str = 'v') -> Tuple[Dict[int, numpy.ndarray], Dict[int, tuple]]:
894def get_centers_and_bounding_boxes(
895    segmentation: np.ndarray, mode: str = "v"
896) -> Tuple[Dict[int, np.ndarray], Dict[int, tuple]]:
897    """Returns the center coordinates of the foreground instances in the ground-truth.
898
899    Args:
900        segmentation: The segmentation.
901        mode: Determines the functionality used for computing the centers.
902            If 'v', the point of maximal distance to the object boundary is used as center.
903            This center is guaranteed to lie inside the object, also for concave shapes.
904            If 'p' the object's centroids computed by skimage are used.
905
906    Returns:
907        A dictionary that maps object ids to the corresponding centroid.
908        A dictionary that maps object_ids to the corresponding bounding box.
909    """
910    assert mode in ["p", "v"], "Choose either 'p' for regionprops centroids or 'v' for distance-based centers"
911
912    properties = regionprops(segmentation)
913
914    if mode == "p":
915        center_coordinates = {prop.label: prop.centroid for prop in properties}
916    elif mode == "v":
917        # Use the point of maximal distance to the object boundary as the center.
918        # In contrast to the centroid, this point is guaranteed to lie inside the object,
919        # also for concave shapes. This replaces vigra.filters.eccentricityCenters.
920        # Compute the boundaries and a single distance transform for the whole
921        # segmentation, instead of one distance transform per object.
922        ndim = segmentation.ndim
923        # Pad so objects touching the image border also get a boundary there,
924        # matching a per-object padded distance transform.
925        padded = np.pad(segmentation, 1)
926        boundaries = find_boundaries(padded, mode="inner")
927        distances = distance_transform(boundaries == 0)
928
929        center_coordinates = {}
930        for prop in properties:
931            bbox = prop.bbox
932            # Slice the global distance field to this object's bbox (shifted by the
933            # pad of 1) and restrict the argmax to the object's own pixels.
934            region = distances[tuple(slice(b + 1, e + 1) for b, e in zip(bbox[:ndim], bbox[ndim:]))]
935            masked = np.where(prop.image, region, -1.0)
936            center_local = np.unravel_index(int(np.argmax(masked)), masked.shape)
937            center_coordinates[prop.label] = tuple(int(c + o) for c, o in zip(center_local, bbox[:ndim]))
938
939    bbox_coordinates = {prop.label: prop.bbox for prop in properties}
940
941    assert len(bbox_coordinates) == len(center_coordinates), f"{len(bbox_coordinates)}, {len(center_coordinates)}"
942    return center_coordinates, bbox_coordinates

Returns the center coordinates of the foreground instances in the ground-truth.

Arguments:
  • segmentation: The segmentation.
  • mode: Determines the functionality used for computing the centers. If 'v', the point of maximal distance to the object boundary is used as center. This center is guaranteed to lie inside the object, also for concave shapes. If 'p' the object's centroids computed by skimage are used.
Returns:

A dictionary that maps object ids to the corresponding centroid. A dictionary that maps object_ids to the corresponding bounding box.

def load_image_data( path: str, key: Optional[str] = None, lazy_loading: bool = False) -> numpy.ndarray:
945def load_image_data(path: str, key: Optional[str] = None, lazy_loading: bool = False) -> np.ndarray:
946    """Helper function to load image data from file.
947
948    Args:
949        path: The filepath to the image data.
950        key: The internal filepath for complex data formats like hdf5.
951        lazy_loading: Whether to lazyly load data. Only supported for n5 and zarr data.
952
953    Returns:
954        The image data.
955    """
956    if key is None:
957        image_data = imageio.imread(path)
958    else:
959        with open_file(path, mode="r") as f:
960            image_data = f[key]
961            if not lazy_loading:
962                image_data = image_data[:]
963
964    return image_data

Helper function to load image data from file.

Arguments:
  • path: The filepath to the image data.
  • key: The internal filepath for complex data formats like hdf5.
  • lazy_loading: Whether to lazyly load data. Only supported for n5 and zarr data.
Returns:

The image data.

def segmentation_to_one_hot( segmentation: numpy.ndarray, segmentation_ids: Optional[numpy.ndarray] = None) -> torch.Tensor:
 967def segmentation_to_one_hot(segmentation: np.ndarray, segmentation_ids: Optional[np.ndarray] = None) -> torch.Tensor:
 968    """Convert the segmentation to one-hot encoded masks.
 969
 970    Args:
 971        segmentation: The segmentation.
 972        segmentation_ids: Optional subset of ids that will be used to subsample the masks.
 973            By default, computes the number of ids from the provided `segmentation` masks.
 974
 975    Returns:
 976        The one-hot encoded masks.
 977    """
 978    masks = segmentation.copy()
 979    if segmentation_ids is None:
 980        n_ids = int(segmentation.max())
 981
 982    else:
 983        msg = "No foreground objects were found."
 984        if len(segmentation_ids) == 0:  # The list should not be completely empty.
 985            raise RuntimeError(msg)
 986
 987        if 0 in segmentation_ids:  # The list should not have 'zero' as a value.
 988            raise RuntimeError(msg)
 989
 990        # the segmentation ids have to be sorted
 991        segmentation_ids = np.sort(segmentation_ids)
 992
 993        # set the non selected objects to zero and relabel sequentially
 994        masks[~np.isin(masks, segmentation_ids)] = 0
 995        masks = relabel_sequential(masks)[0]
 996        n_ids = len(segmentation_ids)
 997
 998    masks = torch.from_numpy(masks)
 999
1000    one_hot_shape = (n_ids + 1,) + masks.shape
1001    masks = masks.unsqueeze(0)  # add dimension to scatter
1002    masks = torch.zeros(one_hot_shape).scatter_(0, masks, 1)[1:]
1003
1004    # add the extra singleton dimension to get shape NUM_OBJECTS x 1 x H x W
1005    masks = masks.unsqueeze(1)
1006    return masks

Convert the segmentation to one-hot encoded masks.

Arguments:
  • segmentation: The segmentation.
  • segmentation_ids: Optional subset of ids that will be used to subsample the masks. By default, computes the number of ids from the provided segmentation masks.
Returns:

The one-hot encoded masks.

def get_block_shape(shape: Tuple[int]) -> Tuple[int]:
1009def get_block_shape(shape: Tuple[int]) -> Tuple[int]:
1010    """Get a suitable block shape for chunking a given shape.
1011
1012    The primary use for this is determining chunk sizes for
1013    zarr arrays or block shapes for parallelization.
1014
1015    Args:
1016        shape: The image or volume shape.
1017
1018    Returns:
1019        The block shape.
1020    """
1021    ndim = len(shape)
1022    if ndim == 2:
1023        block_shape = tuple(min(bs, sh) for bs, sh in zip((1024, 1024), shape))
1024    elif ndim == 3:
1025        block_shape = tuple(min(bs, sh) for bs, sh in zip((32, 256, 256), shape))
1026    else:
1027        raise ValueError(f"Only 2 or 3 dimensional shapes are supported, got {ndim}D.")
1028
1029    return block_shape

Get a suitable block shape for chunking a given shape.

The primary use for this is determining chunk sizes for zarr arrays or block shapes for parallelization.

Arguments:
  • shape: The image or volume shape.
Returns:

The block shape.

def micro_sam_info(download: Optional[List[str]] = None) -> None:
1032def micro_sam_info(download: Optional[List[str]] = None) -> None:
1033    """Display μSAM information using a rich console.
1034
1035    Args:
1036        download: Optional list of pretrained models to download by name (SAM1, SAM2 or their finetuned
1037            variants). E.g. ['vit_b_lm', 'hvit_t'] downloads the listed models; ['all'] downloads every
1038            available model.
1039    """
1040    import psutil
1041    import platform
1042    from .v1.util import models, _download_sam_model
1043    from .v2.util import SUPPORTED_MODELS, get_model_names, _get_checkpoint, _download_finetuned_sam2_model
1044    from rich import progress
1045    from rich.panel import Panel
1046    from rich.table import Table
1047    from rich.console import Console
1048
1049    import torch
1050    import micro_sam
1051
1052    # Open up a new console.
1053    console = Console()
1054
1055    # The header for information CLI.
1056    console.print("[bold #0072B2]μSAM Information Booth[/bold #0072B2]", justify="center")
1057    console.print("-" * console.width)
1058
1059    # μSAM version panel.
1060    console.print(
1061        Panel(f"[bold #F0E442]Version:[/bold #F0E442] {micro_sam.__version__}", title="μSAM Version", expand=True)
1062    )
1063
1064    # The documentation link panel.
1065    console.print(
1066        Panel(
1067            "[bold #CC79A7]Tools documented at:[/bold #CC79A7]\n"
1068            "https://computational-cell-analytics.github.io/micro-sam", title="Documentation"
1069        )
1070    )
1071
1072    # The publication panel.
1073    console.print(
1074        Panel(
1075            "[bold #E69F00]Published in Nature Methods:[/bold #E69F00]\n"
1076            "https://www.nature.com/articles/s41592-024-02580-4", title="Publication"
1077        )
1078    )
1079
1080    # Creating a cache directory when users' run `micro_sam.info`.
1081    cache_dir = get_cache_directory()
1082    os.makedirs(cache_dir, exist_ok=True)
1083
1084    # The cache directory panel.
1085    console.print(
1086        Panel(f"[bold #009E73]Cache Directory:[/bold #009E73]\n{cache_dir}", title="Cache Directory")
1087    )
1088
1089    # SAM1 models. 'sam1_display' holds the labeled names shown in the panel (the '(v2/v3/v4)' suffixes
1090    # refer to the BioImageIO ModelZoo upload version, not the SAM version); 'sam1_names' holds the bare
1091    # names accepted by the downloader.
1092    sam1_display, sam1_names = [], []
1093    for model_name, model_path in models().urls.items():  # We filter out the decoder models.
1094        if model_name.endswith("decoder"):
1095            continue
1096        sam1_names.append(model_name)
1097
1098        if "https://dl.fbaipublicfiles.com/segment_anything/" in model_path:  # Valid v1 SAM models.
1099            sam1_display.append(model_name)
1100
1101        if "https://owncloud.gwdg.de/" in model_path:  # Our own hosted models (in their v1 mode quite often)
1102            if model_name == "vit_t":  # MobileSAM model.
1103                sam1_display.append(model_name)
1104            else:
1105                sam1_display.append(f"{model_name} (v1)")
1106
1107        # Now for our models, the BioImageIO ModelZoo upload structure is such that:
1108        # '/1/files' corresponds to v2 models.
1109        # '/1.1/files' corresponds to v3 models.
1110        # '/1.2/files' corresponds to v4 models.
1111        if "/1/files" in model_path:
1112            sam1_display.append(f"{model_name} (v2)")
1113        if "/1.1/files" in model_path:
1114            sam1_display.append(f"{model_name} (v3)")
1115        if "/1.2/files" in model_path:
1116            sam1_display.append(f"{model_name} (v4)")
1117
1118    # SAM2 models: the base backbones plus the finetuned micro-sam models (with a registered decoder).
1119    sam2_base = list(SUPPORTED_MODELS)
1120    sam2_finetuned = list(get_model_names())
1121    sam2_names = sam2_base + sam2_finetuned
1122    sam2_display = sam2_base + [f"{name} (DEV)" for name in sam2_finetuned]
1123
1124    # The available models panels (SAM1 and SAM2 shown separately to avoid confusing the BioImageIO
1125    # version suffixes above with the SAM version).
1126    console.print(
1127        Panel(f"[bold #D55E00]{chr(10).join(sam1_display)}[/bold #D55E00]", title="SAM1 Models")
1128    )
1129    console.print(
1130        Panel(f"[bold #D55E00]{chr(10).join(sam2_display)}[/bold #D55E00]", title="SAM2 Models")
1131    )
1132
1133    # The system information table.
1134    total_memory = psutil.virtual_memory().total / (1024 ** 3)
1135    table = Table(title="System Information", show_header=True, header_style="bold #0072B2", expand=True)
1136    table.add_column("Property")
1137    table.add_column("Value", style="bold #56B4E9")
1138    table.add_row("System", platform.system())
1139    table.add_row("Node Name", platform.node())
1140    table.add_row("Release", platform.release())
1141    table.add_row("Version", platform.version())
1142    table.add_row("Machine", platform.machine())
1143    table.add_row("Processor", platform.processor())
1144    table.add_row("Platform", platform.platform())
1145    table.add_row("Python", platform.python_version())
1146    table.add_row("CPU Count", str(psutil.cpu_count(logical=True)))
1147    table.add_row("Total RAM (GB)", f"{total_memory:.2f}")
1148    console.print(table)
1149
1150    # Accelerator / device information. This identifies the exact backend, since PyTorch exposes several
1151    # (NVIDIA CUDA, AMD ROCm - which also reports through the CUDA API but sets 'torch.version.hip' -,
1152    # Apple MPS and Intel XPU) and knowing which one (and the device name / memory) is key for debugging.
1153    device_lines = [f"[bold]PyTorch:[/bold] {torch.__version__}"]
1154    if torch.cuda.is_available():
1155        idx = torch.cuda.current_device()
1156        props = torch.cuda.get_device_properties(idx)
1157        is_rocm = getattr(torch.version, "hip", None) is not None
1158        device_lines.append(f"[bold]Backend:[/bold] {'ROCm (AMD)' if is_rocm else 'CUDA (NVIDIA)'}")
1159        device_lines.append(f"[bold]Device:[/bold] {props.name}")
1160        device_lines.append(f"[bold]Device count:[/bold] {torch.cuda.device_count()}")
1161        device_lines.append(f"[bold]GPU memory (GB):[/bold] {props.total_memory / (1024 ** 3):.2f}")
1162        if is_rocm:
1163            device_lines.append(f"[bold]HIP version:[/bold] {torch.version.hip}")
1164        else:
1165            device_lines.append(f"[bold]CUDA (torch build):[/bold] {torch.version.cuda}")
1166            device_lines.append(f"[bold]cuDNN:[/bold] {torch.backends.cudnn.version()}")
1167    elif torch.backends.mps.is_available():
1168        # On Apple Silicon the GPU is the SoC. Report the exact chip on a best-effort basis.
1169        chip = platform.processor()
1170        if platform.system() == "Darwin":
1171            try:
1172                import subprocess
1173                chip = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"]).decode().strip() or chip
1174            except Exception:
1175                pass
1176        device_lines.append("[bold]Backend:[/bold] MPS (Apple Silicon)")
1177        device_lines.append(f"[bold]Device:[/bold] {chip}")
1178    elif hasattr(torch, "xpu") and torch.xpu.is_available():
1179        idx = torch.xpu.current_device()
1180        device_lines.append("[bold]Backend:[/bold] XPU (Intel)")
1181        device_lines.append(f"[bold]Device:[/bold] {torch.xpu.get_device_name(idx)}")
1182        device_lines.append(f"[bold]Device count:[/bold] {torch.xpu.device_count()}")
1183    else:
1184        device_lines.append("[bold]Backend:[/bold] CPU (no GPU acceleration detected)")
1185        gpu_warning = get_gpu_setup_warning()
1186        if gpu_warning is not None:
1187            device_lines.append(f"[bold red]Warning:[/bold red] {gpu_warning}")
1188    console.print(Panel("\n".join(device_lines), title="Accelerator Information"))
1189
1190    # The section allowing to download models.
1191    # NOTE: In future, can be extended to download sample data.
1192    if download:
1193        all_names = sam1_names + sam2_names
1194        if any(t.lower() == "all" for t in download):  # Download every available model.
1195            download_list = all_names
1196            # Guard the bulk download (all SAM1 + SAM2 models, several GB) behind a confirmation, but
1197            # only when interactive so scripted '--download all' still runs unattended.
1198            import sys
1199            from rich.prompt import Confirm
1200            if sys.stdin.isatty() and not Confirm.ask(
1201                f"[yellow]This downloads all {len(download_list)} models (SAM1 + SAM2), several GB. Continue?[/]",
1202                console=console, default=False,
1203            ):
1204                console.print("[red]Download aborted.[/]")
1205                return
1206        else:
1207            download_list = list(download)
1208            incorrect_models = [m for m in download_list if m not in all_names]
1209            if incorrect_models:
1210                console.print(Panel("[red]Unknown model(s):[/] " + ", ".join(incorrect_models), title="Download Error"))
1211                return
1212
1213        def _download(name):  # Dispatch to the downloader for the model's family.
1214            if name in sam2_finetuned:
1215                _download_finetuned_sam2_model(name)
1216            elif name in sam2_base:
1217                _get_checkpoint(name)
1218            else:
1219                _download_sam_model(model_type=name)
1220
1221        with progress.Progress(
1222            progress.SpinnerColumn(),
1223            progress.TextColumn("[progress.description]{task.description}"),
1224            progress.BarColumn(bar_width=None),
1225            "[progress.percentage]{task.percentage:>3.0f}%",
1226            progress.TimeRemainingColumn(),
1227            console=console,
1228        ) as prog:
1229            task = prog.add_task("[green]Downloading μSAM models…", total=len(download_list))
1230            for model_type in download_list:
1231                prog.update(task, description=f"Downloading [cyan]{model_type}[/]…")
1232                _download(model_type)
1233                prog.advance(task)
1234
1235        console.print(Panel("[bold green] Downloads complete![/]", title="Finished"))

Display μSAM information using a rich console.

Arguments:
  • download: Optional list of pretrained models to download by name (SAM1, SAM2 or their finetuned variants). E.g. ['vit_b_lm', 'hvit_t'] downloads the listed models; ['all'] downloads every available model.
def mask_data_to_segmentation( masks: List[Dict[str, Any]], shape: Optional[Tuple[int, int]] = None, min_object_size: int = 0, max_object_size: Optional[int] = None, label_masks: bool = True, with_background: bool = False, merge_exclusively: bool = True, keep_largest_component: bool = False, max_overlap: Optional[float] = None) -> numpy.ndarray:
1438def mask_data_to_segmentation(
1439    masks: List[Dict[str, Any]],
1440    shape: Optional[Tuple[int, int]] = None,
1441    min_object_size: int = 0,
1442    max_object_size: Optional[int] = None,
1443    label_masks: bool = True,
1444    with_background: bool = False,
1445    merge_exclusively: bool = True,
1446    keep_largest_component: bool = False,
1447    max_overlap: Optional[float] = None,
1448) -> np.ndarray:
1449    """Convert the output of the automatic mask generation to an instance segmentation.
1450
1451    Args:
1452        masks: The outputs generated by `AutomaticMaskGenerator`, other classes from
1453            `micro_sam.v1.instance_segmentation`, or from `micro_sam.v1.inference` functions. Only
1454            supported for output_mode=binary_mask.
1455        shape: The shape of the output segmentation. If None, it will be derived from the mask input.
1456            If the mask where predicted with tiling then the shape must be given.
1457        min_object_size: The minimal size of an object in pixels. By default, set to '0'.
1458        max_object_size: The maximal size of an object in pixels.
1459        label_masks: Whether to apply connected components to the result before removing small objects.
1460            By default, set to 'True'.
1461        with_background: Whether to remove the largest object, which often covers the background for AMG.
1462        merge_exclusively: Whether to exclude previous merged masks from merging.
1463        keep_largest_component: Whether to paint only the largest connected component of the pixels a
1464            mask can still claim. Otherwise the pieces that the masks merged before it cut off become
1465            objects of their own once 'label_masks' runs: the slivers and rings that duplicate masks
1466            of one object leave behind. Only meaningful together with 'merge_exclusively'.
1467        max_overlap: Skip a mask when more than this fraction of it is already claimed, after
1468            'keep_largest_component'. Such a mask is a duplicate of the ones merged before it, which
1469            the NMS let through, and only its leftovers would be painted. None (the default) keeps it.
1470
1471    Returns:
1472        The instance segmentation.
1473    """
1474    masks = sorted(masks, key=(lambda x: x["area"]), reverse=True)
1475    if shape is None:
1476        shape = next(iter(masks))["segmentation"].shape
1477    segmentation = np.zeros(shape, dtype="uint32")
1478
1479    def require_numpy(mask):
1480        return mask.cpu().numpy() if torch.is_tensor(mask) else mask
1481
1482    seg_id = 1
1483    for mask_data in masks:
1484        area = mask_data["area"]
1485        if (area < min_object_size) or (max_object_size is not None and area > max_object_size):
1486            continue
1487
1488        this_mask = require_numpy(mask_data["segmentation"])
1489        this_seg_id = mask_data.get("seg_id", seg_id)
1490        if "global_bbox" in mask_data:
1491            bb = mask_data["bbox"]
1492            bb = np.s_[bb[1]:bb[1] + bb[3], bb[0]:bb[0] + bb[2]]
1493            global_bb = mask_data["global_bbox"]
1494            global_bb = np.s_[global_bb[1]:global_bb[1] + global_bb[3], global_bb[0]:global_bb[0] + global_bb[2]]
1495            # A view, so painting below writes straight into the output.
1496            target = segmentation[global_bb]
1497            this_mask = this_mask[bb]
1498        else:
1499            target = segmentation
1500        if merge_exclusively:
1501            this_mask = np.logical_and(this_mask, target == 0)
1502        if keep_largest_component:
1503            this_mask = _largest_component(this_mask)
1504        if max_overlap is not None and this_mask.sum() < (1 - max_overlap) * area:
1505            continue
1506        target[this_mask] = this_seg_id
1507        seg_id = this_seg_id + 1
1508
1509    block_shape = (512, 512)
1510    if label_masks:
1511        segmentation_cc = np.zeros_like(segmentation, dtype=segmentation.dtype)
1512        segmentation_cc = parallel_impl.label(segmentation, out=segmentation_cc, block_shape=block_shape)
1513        segmentation = segmentation_cc
1514
1515    seg_ids, sizes = parallel_impl.unique(segmentation, return_counts=True, block_shape=block_shape)
1516    filter_ids = seg_ids[sizes < min_object_size]
1517    if with_background:
1518        bg_id = seg_ids[np.argmax(sizes)]
1519        filter_ids = np.concatenate([filter_ids, [bg_id]])
1520
1521    filter_mask = np.zeros(segmentation.shape, dtype="bool")
1522    filter_mask = parallel_impl.isin(segmentation, filter_ids, out=filter_mask, block_shape=block_shape)
1523    segmentation[filter_mask] = 0
1524    parallel_impl.relabel_consecutive(segmentation, block_shape=block_shape)[0]
1525
1526    return segmentation

Convert the output of the automatic mask generation to an instance segmentation.

Arguments:
  • masks: The outputs generated by AutomaticMaskGenerator, other classes from micro_sam.v1.instance_segmentation, or from micro_sam.v1.inference functions. Only supported for output_mode=binary_mask.
  • shape: The shape of the output segmentation. If None, it will be derived from the mask input. If the mask where predicted with tiling then the shape must be given.
  • min_object_size: The minimal size of an object in pixels. By default, set to '0'.
  • max_object_size: The maximal size of an object in pixels.
  • label_masks: Whether to apply connected components to the result before removing small objects. By default, set to 'True'.
  • with_background: Whether to remove the largest object, which often covers the background for AMG.
  • merge_exclusively: Whether to exclude previous merged masks from merging.
  • keep_largest_component: Whether to paint only the largest connected component of the pixels a mask can still claim. Otherwise the pieces that the masks merged before it cut off become objects of their own once 'label_masks' runs: the slivers and rings that duplicate masks of one object leave behind. Only meaningful together with 'merge_exclusively'.
  • max_overlap: Skip a mask when more than this fraction of it is already claimed, after 'keep_largest_component'. Such a mask is a duplicate of the ones merged before it, which the NMS let through, and only its leftovers would be painted. None (the default) keeps it.
Returns:

The instance segmentation.

def apply_nms( predictions: List[Dict[str, Any]], min_size: int, shape: Optional[Tuple[int, int]] = None, perform_box_nms: bool = False, nms_thresh: float = 0.9, max_size: Optional[int] = None, intersection_over_min: bool = False, keep_largest_component: bool = False, max_overlap: Optional[float] = None) -> numpy.ndarray:
1529def apply_nms(
1530    predictions: List[Dict[str, Any]],
1531    min_size: int,
1532    shape: Optional[Tuple[int, int]] = None,
1533    perform_box_nms: bool = False,
1534    nms_thresh: float = 0.9,
1535    max_size: Optional[int] = None,
1536    intersection_over_min: bool = False,
1537    keep_largest_component: bool = False,
1538    max_overlap: Optional[float] = None,
1539) -> np.ndarray:
1540    """Apply non-maximum suppression to mask predictions from a segment anything model.
1541
1542    Args:
1543        predictions: The mask predictions from SAM.
1544        min_size: The minimum mask size to keep in the output.
1545        shape: The shape of the output segmentation.
1546            For tiled predictions this is inferred from the tile-local mask shapes if it is not passed.
1547        perform_box_nms: Whether to perform NMS on the box coordinates or on the masks.
1548        nms_thresh: The threshold for filtering out objects in NMS.
1549        max_size: The maximum mask size to keep in the output.
1550        intersection_over_min: Whether to perform intersection over the minimum overlap shape
1551            or to perform intersection over union.
1552        keep_largest_component: Whether to merge only the largest connected component of what each
1553            mask can still claim, see `mask_data_to_segmentation`.
1554        max_overlap: Skip a mask in the merge when more than this fraction of it is already claimed,
1555            see `mask_data_to_segmentation`.
1556
1557    Returns:
1558        The segmentation obtained from merging the masks left after NMS.
1559    """
1560    # Check if the input comes with a 'global_bbox' attribute. If it does, then the predictions are from
1561    # a tiled prediction. In this case, we have to take the coordinates w.r.t. the tiling into account.
1562    is_tiled = "global_bbox" in predictions[0]
1563    if is_tiled and shape is None:
1564        shape = _infer_tiled_shape(predictions)
1565
1566    masks = [pred["segmentation"] for pred in predictions]
1567    nms_masks = None if is_tiled else torch.cat([mask[None] for mask in masks], dim=0)
1568    data = amg_utils.MaskData(masks=masks, iou_preds=torch.tensor([pred["predicted_iou"] for pred in predictions]))
1569    data["boxes"] = torch.tensor(np.array([pred["bbox"] for pred in predictions]))
1570    data["area"] = [int(mask.sum()) for mask in data["masks"]]
1571    data["stability_scores"] = torch.tensor([pred["stability_score"] for pred in predictions])
1572    if is_tiled:
1573        data["global_boxes"] = torch.tensor(np.array([pred["global_bbox"] for pred in predictions]))
1574
1575    if min_size > 0:
1576        keep_by_size = torch.tensor(
1577            [i for i, area in enumerate(data["area"]) if area > min_size], dtype=torch.long,
1578        )
1579        data.filter(keep_by_size)
1580        if nms_masks is not None:
1581            nms_masks = nms_masks[keep_by_size]
1582
1583    if max_size is not None:
1584        keep_by_size = torch.tensor([i for i, area in enumerate(data["area"]) if area < max_size])
1585        data.filter(keep_by_size)
1586        if nms_masks is not None:
1587            nms_masks = nms_masks[keep_by_size]
1588
1589    if len(data["masks"]) == 0:
1590        if shape is None:
1591            shape = predictions[0]["segmentation"].shape
1592        return np.zeros(shape, dtype="uint32")
1593
1594    scores = data["iou_preds"] * data["stability_scores"]
1595    boxes = _xywh_to_xyxy(data["global_boxes"] if is_tiled else data["boxes"])
1596    if perform_box_nms:
1597        assert not intersection_over_min  # not implemented
1598        keep_by_nms = batched_nms(
1599            boxes,
1600            scores,
1601            torch.zeros_like(data["boxes"][:, 0]),  # categories
1602            iou_threshold=nms_thresh,
1603        )
1604    elif is_tiled:
1605        keep_by_nms = _batched_tiled_mask_nms(
1606            masks=data["masks"],
1607            boxes=data["boxes"],
1608            global_boxes=data["global_boxes"],
1609            scores=scores,
1610            nms_thresh=nms_thresh,
1611            intersection_over_min=intersection_over_min,
1612        )
1613    else:
1614        keep_by_nms = _batched_mask_nms(
1615            masks=nms_masks,
1616            boxes=boxes,
1617            scores=scores,
1618            nms_thresh=nms_thresh,
1619            intersection_over_min=intersection_over_min,
1620        )
1621    data.filter(keep_by_nms)
1622
1623    if is_tiled:
1624        mask_data = [
1625            {"segmentation": mask, "area": area, "bbox": box, "global_bbox": global_box}
1626            for mask, area, box, global_box in zip(data["masks"], data["area"], data["boxes"], data["global_boxes"])
1627        ]
1628    else:
1629        mask_data = [
1630            {"segmentation": mask, "area": area, "bbox": box}
1631            for mask, area, box in zip(data["masks"], data["area"], data["boxes"])
1632        ]
1633
1634    if shape is None:
1635        shape = predictions[0]["segmentation"].shape
1636    if mask_data:
1637        segmentation = mask_data_to_segmentation(
1638            mask_data, shape=shape, min_object_size=min_size,
1639            keep_largest_component=keep_largest_component, max_overlap=max_overlap,
1640        )
1641    else:  # In case all objects have been filtered out due to size filtering.
1642        segmentation = np.zeros(shape, dtype="uint32")
1643
1644    return segmentation

Apply non-maximum suppression to mask predictions from a segment anything model.

Arguments:
  • predictions: The mask predictions from SAM.
  • min_size: The minimum mask size to keep in the output.
  • shape: The shape of the output segmentation. For tiled predictions this is inferred from the tile-local mask shapes if it is not passed.
  • perform_box_nms: Whether to perform NMS on the box coordinates or on the masks.
  • nms_thresh: The threshold for filtering out objects in NMS.
  • max_size: The maximum mask size to keep in the output.
  • intersection_over_min: Whether to perform intersection over the minimum overlap shape or to perform intersection over union.
  • keep_largest_component: Whether to merge only the largest connected component of what each mask can still claim, see mask_data_to_segmentation.
  • max_overlap: Skip a mask in the merge when more than this fraction of it is already claimed, see mask_data_to_segmentation.
Returns:

The segmentation obtained from merging the masks left after NMS.