micro_sam.v2.semantic_segmentation

Automatic semantic segmentation with a SAM2 based UNETR.

The models predict one class id per voxel. The class layout comes from the label transform that the model was trained with. micro_sam.v2.transforms.labels.semantic_labels() derives the three class layout of background, object boundary and object interior from an instance segmentation.

  1"""Automatic semantic segmentation with a SAM2 based UNETR.
  2
  3The models predict one class id per voxel. The class layout comes from the label transform that the model
  4was trained with. :func:`micro_sam.v2.transforms.labels.semantic_labels` derives the three class layout of
  5background, object boundary and object interior from an instance segmentation.
  6"""
  7
  8import os
  9from typing import Callable, Optional, Tuple, Union
 10
 11import numpy as np
 12
 13import torch
 14
 15from torch_em.util.prediction import predict_with_halo
 16
 17from micro_sam.util import get_device, load_checkpoint
 18from micro_sam.v2.models.util import SemanticSAM2
 19from micro_sam.v2.normalization import normalize_raw
 20from micro_sam.v2.util import autocast_dtype, DEFAULT_TILE_SHAPE, DEFAULT_HALO, DEFAULT_TILE_Z, DEFAULT_HALO_Z
 21
 22
 23def get_semantic_model(
 24    model_type: str,
 25    num_classes: int = 3,
 26    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
 27    device: Optional[Union[str, torch.device]] = None,
 28    initial_features: int = 32,
 29) -> torch.nn.Module:
 30    """Get a SemanticSAM2 model for inference.
 31
 32    Args:
 33        model_type: The SAM2 encoder variant the model was trained with.
 34        num_classes: The number of semantic classes, the background class included.
 35            One selects a binary model with a single foreground channel.
 36        checkpoint_path: The 'best.pt' or 'latest.pt' file of a training run. The model keeps the pretrained
 37            SAM2 encoder and an untrained decoder if this is None.
 38        device: The device to load the model on. Auto-selects if None.
 39        initial_features: Width of the convolutional decoder the model was trained with.
 40
 41    Returns:
 42        The model in evaluation mode.
 43    """
 44    device = get_device(device)
 45    model = SemanticSAM2(
 46        encoder=model_type, num_classes=num_classes, initial_features=initial_features, device=device
 47    )
 48    if checkpoint_path is not None:
 49        state = load_checkpoint(checkpoint_path, map_location=device)
 50        model.load_state_dict(state["model_state"])
 51    model.eval()
 52    return model
 53
 54
 55def semantic_segmentation(
 56    model: torch.nn.Module,
 57    raw: np.ndarray,
 58    tile_shape: Optional[Tuple[int, ...]] = None,
 59    halo: Optional[Tuple[int, ...]] = None,
 60    verbose: bool = True,
 61    normalize: Optional[Callable[[np.ndarray], np.ndarray]] = None,
 62) -> np.ndarray:
 63    """Run semantic segmentation on an image or a volume.
 64
 65    The raw data is normalized once over the whole input and is then predicted in tiles. The model resizes
 66    every tile to its encoder size, so the tile shape plus twice the halo sets the scale at which the model
 67    sees the objects. Keep that sum close to the training patch shape.
 68
 69    Args:
 70        model: The semantic segmentation model, see :func:`get_semantic_model`.
 71        raw: The image of shape (Y, X), or the volume of shape (Z, Y, X).
 72        tile_shape: The inner shape of a prediction tile. Uses the micro-sam tiling defaults if None.
 73        halo: The halo added to every side of a tile. Uses the micro-sam tiling defaults if None.
 74        verbose: Whether to show a progress bar.
 75        normalize: A function that maps the whole input to float values in [0, 1], with the shape of the input.
 76            It replaces the default percentile normalization. The input is normalized once, before the tiling.
 77
 78    Returns:
 79        The class ids, with the shape of the raw data. A binary model returns the foreground mask.
 80    """
 81    if raw.ndim not in (2, 3):
 82        raise ValueError(f"The raw data has {raw.ndim} dimensions. Expected an image (Y, X) or a volume (Z, Y, X).")
 83
 84    is_3d = raw.ndim == 3
 85    if tile_shape is None:
 86        tile_shape = (DEFAULT_TILE_Z,) + DEFAULT_TILE_SHAPE if is_3d else DEFAULT_TILE_SHAPE
 87    if halo is None:
 88        halo = (DEFAULT_HALO_Z,) + DEFAULT_HALO if is_3d else DEFAULT_HALO
 89
 90    # 2d normalizes over the image and 3d over every z slice, which is what the training transforms do.
 91    if normalize is None:
 92        normalized = normalize_raw(raw, axis=(1, 2) if is_3d else (0, 1))
 93    else:
 94        normalized = normalize(raw)
 95        if normalized.shape != raw.shape:
 96            raise ValueError(f"The normalization changed the shape from {raw.shape} to {normalized.shape}.")
 97
 98    device = next(model.parameters()).device
 99    dtype = autocast_dtype(device)
100
101    def prediction_function(net, inp):
102        # The tiles arrive as (B, 1, Z, Y, X) or (B, 1, Y, X), and the encoder expects three channels.
103        x = torch.cat([inp] * 3, dim=1)
104        if not is_3d:
105            x = x.unsqueeze(2)  # the model always expects a z axis
106        if dtype is None:
107            prediction = net(x)
108        else:
109            with torch.autocast(device_type=device.type, dtype=dtype):
110                prediction = net(x)
111        prediction = prediction.float()
112        return prediction if is_3d else prediction.squeeze(2)
113
114    logits = predict_with_halo(
115        input_=normalized,
116        model=model,
117        gpu_ids=[device],
118        block_shape=tile_shape,
119        halo=halo,
120        preprocess=None,
121        prediction_function=prediction_function,
122        disable_tqdm=not verbose,
123        tqdm_desc="Run semantic segmentation",
124    )
125    # A single output channel holds the foreground logits of a binary model.
126    if logits.shape[0] == 1:
127        return (logits[0] > 0).astype("uint8")
128    return np.argmax(logits, axis=0).astype("uint8")
def get_semantic_model( model_type: str, num_classes: int = 3, checkpoint_path: Union[str, os.PathLike, NoneType] = None, device: Union[str, torch.device, NoneType] = None, initial_features: int = 32) -> torch.nn.modules.module.Module:
24def get_semantic_model(
25    model_type: str,
26    num_classes: int = 3,
27    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
28    device: Optional[Union[str, torch.device]] = None,
29    initial_features: int = 32,
30) -> torch.nn.Module:
31    """Get a SemanticSAM2 model for inference.
32
33    Args:
34        model_type: The SAM2 encoder variant the model was trained with.
35        num_classes: The number of semantic classes, the background class included.
36            One selects a binary model with a single foreground channel.
37        checkpoint_path: The 'best.pt' or 'latest.pt' file of a training run. The model keeps the pretrained
38            SAM2 encoder and an untrained decoder if this is None.
39        device: The device to load the model on. Auto-selects if None.
40        initial_features: Width of the convolutional decoder the model was trained with.
41
42    Returns:
43        The model in evaluation mode.
44    """
45    device = get_device(device)
46    model = SemanticSAM2(
47        encoder=model_type, num_classes=num_classes, initial_features=initial_features, device=device
48    )
49    if checkpoint_path is not None:
50        state = load_checkpoint(checkpoint_path, map_location=device)
51        model.load_state_dict(state["model_state"])
52    model.eval()
53    return model

Get a SemanticSAM2 model for inference.

Arguments:
  • model_type: The SAM2 encoder variant the model was trained with.
  • num_classes: The number of semantic classes, the background class included. One selects a binary model with a single foreground channel.
  • checkpoint_path: The 'best.pt' or 'latest.pt' file of a training run. The model keeps the pretrained SAM2 encoder and an untrained decoder if this is None.
  • device: The device to load the model on. Auto-selects if None.
  • initial_features: Width of the convolutional decoder the model was trained with.
Returns:

The model in evaluation mode.

def semantic_segmentation( model: torch.nn.modules.module.Module, raw: numpy.ndarray, tile_shape: Optional[Tuple[int, ...]] = None, halo: Optional[Tuple[int, ...]] = None, verbose: bool = True, normalize: Optional[Callable[[numpy.ndarray], numpy.ndarray]] = None) -> numpy.ndarray:
 56def semantic_segmentation(
 57    model: torch.nn.Module,
 58    raw: np.ndarray,
 59    tile_shape: Optional[Tuple[int, ...]] = None,
 60    halo: Optional[Tuple[int, ...]] = None,
 61    verbose: bool = True,
 62    normalize: Optional[Callable[[np.ndarray], np.ndarray]] = None,
 63) -> np.ndarray:
 64    """Run semantic segmentation on an image or a volume.
 65
 66    The raw data is normalized once over the whole input and is then predicted in tiles. The model resizes
 67    every tile to its encoder size, so the tile shape plus twice the halo sets the scale at which the model
 68    sees the objects. Keep that sum close to the training patch shape.
 69
 70    Args:
 71        model: The semantic segmentation model, see :func:`get_semantic_model`.
 72        raw: The image of shape (Y, X), or the volume of shape (Z, Y, X).
 73        tile_shape: The inner shape of a prediction tile. Uses the micro-sam tiling defaults if None.
 74        halo: The halo added to every side of a tile. Uses the micro-sam tiling defaults if None.
 75        verbose: Whether to show a progress bar.
 76        normalize: A function that maps the whole input to float values in [0, 1], with the shape of the input.
 77            It replaces the default percentile normalization. The input is normalized once, before the tiling.
 78
 79    Returns:
 80        The class ids, with the shape of the raw data. A binary model returns the foreground mask.
 81    """
 82    if raw.ndim not in (2, 3):
 83        raise ValueError(f"The raw data has {raw.ndim} dimensions. Expected an image (Y, X) or a volume (Z, Y, X).")
 84
 85    is_3d = raw.ndim == 3
 86    if tile_shape is None:
 87        tile_shape = (DEFAULT_TILE_Z,) + DEFAULT_TILE_SHAPE if is_3d else DEFAULT_TILE_SHAPE
 88    if halo is None:
 89        halo = (DEFAULT_HALO_Z,) + DEFAULT_HALO if is_3d else DEFAULT_HALO
 90
 91    # 2d normalizes over the image and 3d over every z slice, which is what the training transforms do.
 92    if normalize is None:
 93        normalized = normalize_raw(raw, axis=(1, 2) if is_3d else (0, 1))
 94    else:
 95        normalized = normalize(raw)
 96        if normalized.shape != raw.shape:
 97            raise ValueError(f"The normalization changed the shape from {raw.shape} to {normalized.shape}.")
 98
 99    device = next(model.parameters()).device
100    dtype = autocast_dtype(device)
101
102    def prediction_function(net, inp):
103        # The tiles arrive as (B, 1, Z, Y, X) or (B, 1, Y, X), and the encoder expects three channels.
104        x = torch.cat([inp] * 3, dim=1)
105        if not is_3d:
106            x = x.unsqueeze(2)  # the model always expects a z axis
107        if dtype is None:
108            prediction = net(x)
109        else:
110            with torch.autocast(device_type=device.type, dtype=dtype):
111                prediction = net(x)
112        prediction = prediction.float()
113        return prediction if is_3d else prediction.squeeze(2)
114
115    logits = predict_with_halo(
116        input_=normalized,
117        model=model,
118        gpu_ids=[device],
119        block_shape=tile_shape,
120        halo=halo,
121        preprocess=None,
122        prediction_function=prediction_function,
123        disable_tqdm=not verbose,
124        tqdm_desc="Run semantic segmentation",
125    )
126    # A single output channel holds the foreground logits of a binary model.
127    if logits.shape[0] == 1:
128        return (logits[0] > 0).astype("uint8")
129    return np.argmax(logits, axis=0).astype("uint8")

Run semantic segmentation on an image or a volume.

The raw data is normalized once over the whole input and is then predicted in tiles. The model resizes every tile to its encoder size, so the tile shape plus twice the halo sets the scale at which the model sees the objects. Keep that sum close to the training patch shape.

Arguments:
  • model: The semantic segmentation model, see get_semantic_model().
  • raw: The image of shape (Y, X), or the volume of shape (Z, Y, X).
  • tile_shape: The inner shape of a prediction tile. Uses the micro-sam tiling defaults if None.
  • halo: The halo added to every side of a tile. Uses the micro-sam tiling defaults if None.
  • verbose: Whether to show a progress bar.
  • normalize: A function that maps the whole input to float values in [0, 1], with the shape of the input. It replaces the default percentile normalization. The input is normalized once, before the tiling.
Returns:

The class ids, with the shape of the raw data. A binary model returns the foreground mask.