micro_sam.v2.training.loaders

Data loaders for training micro-sam2 models on your own data.

The images and labels can be regular image files (e.g. tif or png), given as a list of files or as a folder with a glob pattern, or container files (e.g. h5, zarr, ome-zarr or n5), given with the internal keys of the image and label data. default_sam2_loader returns a loader in the format that the trainer of each training mode expects:

  • 'interactive': micro_sam.v2.training.train_sam2, for interactive segmentation.
  • 'automatic': micro_sam.v2.training.train_automatic, for automatic instance segmentation (AIS and APG).
  • 'joint': micro_sam.v2.training.train_joint_sam2, for interactive and automatic segmentation.
  • 'semantic': micro_sam.v2.training.train_semantic, for semantic segmentation.
  1"""Data loaders for training micro-sam2 models on your own data.
  2
  3The images and labels can be regular image files (e.g. tif or png), given as a list of files or as a folder
  4with a glob pattern, or container files (e.g. h5, zarr, ome-zarr or n5), given with the internal keys of the
  5image and label data. `default_sam2_loader` returns a loader in the format that the trainer of each training
  6mode expects:
  7
  8- 'interactive': `micro_sam.v2.training.train_sam2`, for interactive segmentation.
  9- 'automatic': `micro_sam.v2.training.train_automatic`, for automatic instance segmentation (AIS and APG).
 10- 'joint': `micro_sam.v2.training.train_joint_sam2`, for interactive and automatic segmentation.
 11- 'semantic': `micro_sam.v2.training.train_semantic`, for semantic segmentation.
 12"""
 13
 14import os
 15from glob import glob
 16from typing import Callable, List, Optional, Sequence, Tuple, Union
 17
 18import numpy as np
 19import imageio.v3 as imageio
 20
 21import torch
 22from torch.utils.data import DataLoader, Dataset
 23
 24from elf.io import open_file
 25
 26FilePath = Union[str, os.PathLike]
 27
 28TRAINING_MODES = ("interactive", "automatic", "joint", "semantic")
 29# The smallest number of samples per epoch, so that an epoch of a small dataset is not just a few steps.
 30MIN_TRAIN_SAMPLES = 100
 31MIN_VAL_SAMPLES = 5
 32GLOB_CHARACTERS = ("*", "?", "[")
 33
 34
 35def _is_pattern(key: Optional[str]) -> bool:
 36    return key is not None and any(character in key for character in GLOB_CHARACTERS)
 37
 38
 39def _ome_zarr_scale_key(path, key):
 40    """The key of the first (full resolution) scale, if the key points to an ome-zarr image or label group."""
 41    import zarr
 42
 43    if not os.path.isdir(path) or not str(path).rstrip("/").endswith(".zarr"):
 44        return key
 45    try:
 46        node = zarr.open(path, mode="r") if not key else zarr.open(path, mode="r", path=key)
 47    except Exception:
 48        return key
 49    if not isinstance(node, zarr.Group):
 50        return key
 51    attrs = node.attrs.asdict()
 52    multiscales = attrs.get("ome", attrs).get("multiscales")
 53    if not multiscales:
 54        return key
 55    scale = multiscales[0]["datasets"][0]["path"]
 56    return scale if not key else f"{key.rstrip('/')}/{scale}"
 57
 58
 59def resolve_data_paths(
 60    paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]], key: Optional[str],
 61) -> Tuple[list, Optional[str]]:
 62    """Resolve the image or label paths and key that a user passes to a list of inputs and a key.
 63
 64    A folder with a glob pattern as key, e.g. ('images/', '*.tif'), is expanded to the sorted list of matching
 65    files, and the key becomes None. Each file is then one image (2d) or one volume (3d). A container file
 66    (e.g. h5, zarr or n5) keeps its key, which selects the data inside the file. For an ome-zarr file, the
 67    key can also be the image or label group, e.g. None for the image and 'labels/cells' for the labels:
 68    it then selects the full resolution scale of that group.
 69
 70    Args:
 71        paths: A file path, a folder, or a list of either. A list of numpy arrays is returned as it is.
 72        key: The key of the data inside a container file, a glob pattern for a folder, or None for image files.
 73
 74    Returns:
 75        The list of inputs, and the key for them.
 76
 77    Raises:
 78        ValueError: If a folder with a glob pattern contains no matching file.
 79    """
 80    if isinstance(paths, (str, os.PathLike)):
 81        paths = [paths]
 82    paths = list(paths)
 83    if len(paths) > 0 and isinstance(paths[0], (np.ndarray, torch.Tensor)):
 84        return paths, None
 85    if not _is_pattern(key):
 86        paths = [str(path) for path in paths]
 87        return paths, _ome_zarr_scale_key(paths[0], key) if paths else key
 88
 89    files = []
 90    for folder in paths:
 91        matches = sorted(glob(os.path.join(folder, key)))
 92        if len(matches) == 0:
 93            raise ValueError(f"There are no files matching '{key}' in '{folder}'.")
 94        files.extend(matches)
 95    return files, None
 96
 97
 98def _data_shape(path, key):
 99    if isinstance(path, (np.ndarray, torch.Tensor)):
100        return tuple(path.shape)
101    if key is None and str(path).lower().endswith((".tif", ".tiff")):
102        # The image properties of a tif file describe its first page only, not a stack of pages.
103        import tifffile
104        with tifffile.TiffFile(path) as f:
105            return tuple(f.series[0].shape)
106    if key is None:
107        return tuple(imageio.improps(path).shape)
108    with open_file(path, mode="r") as f:
109        return tuple(f[key].shape)
110
111
112def _is_image_with_channels(shape):
113    """Whether the shape is a 2d image with a channel axis, either (C, Y, X) or (Y, X, C)."""
114    return len(shape) == 3 and (shape[-1] <= 4 or shape[0] <= 4)
115
116
117def _label_settings(mode, with_boundaries, num_classes):
118    """The label transform, the label dtype and the default sampler for a training mode."""
119    from torch_em.data.sampler import MinInstanceSampler
120    from ..transforms.labels import _instance_labels, _JointGeodesicLabelTransform, GeodesicHybridDistanceTransform
121
122    if mode == "interactive":
123        # Each connected region becomes one object, for prompting with points, boxes and masks.
124        return _instance_labels, torch.int64, MinInstanceSampler(min_num_instances=2)
125    if mode == "automatic":
126        transform = GeodesicHybridDistanceTransform(with_boundaries=with_boundaries)
127        return transform, torch.float32, MinInstanceSampler(min_num_instances=2)
128    if mode == "joint":
129        # The instance ids for the interactive branch, followed by the targets of the automatic branch.
130        transform = _JointGeodesicLabelTransform(with_boundaries=with_boundaries)
131        return transform, torch.float32, MinInstanceSampler(min_num_instances=2)
132    if num_classes is None:
133        raise ValueError("Pass 'num_classes' for the 'semantic' training mode.")
134    # The labels are the class ids. The sampler rejects patches with the background class only.
135    return None, torch.int64, MinInstanceSampler(min_num_instances=2)
136
137
138def default_sam2_dataset(
139    raw_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
140    raw_key: Optional[str],
141    label_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
142    label_key: Optional[str],
143    patch_shape: Tuple[int, ...],
144    mode: str,
145    ndim: Optional[int] = None,
146    with_boundaries: bool = True,
147    num_classes: Optional[int] = None,
148    n_samples: Optional[int] = None,
149    is_train: bool = True,
150    sampler: Optional[Callable] = None,
151    label_transform: Optional[Callable] = None,
152    rois: Optional[Union[Tuple[slice, ...], List[Tuple[slice, ...]]]] = None,
153    with_channels: Optional[bool] = None,
154    **kwargs,
155) -> Dataset:
156    """Create a dataset for training a micro-sam2 model on images and their labels.
157
158    The images are normalized to [0, 1] with `micro_sam.v2.normalization.normalize_raw`. Grayscale images
159    are copied to three channels. The labels are converted to the targets of the training mode.
160
161    Args:
162        raw_paths: The images. Either a file path, a folder (with a glob pattern in `raw_key`), a list of file
163            paths, or a list of numpy arrays. Supported are regular image files (e.g. tif or png) and container
164            files (e.g. h5, zarr, ome-zarr or n5).
165        raw_key: The key of the images: the internal dataset in a container file, e.g. 'raw', a glob pattern
166            for a folder, e.g. '*.tif', or None for image files. For an ome-zarr file, None selects the full
167            resolution image, and the path of a scale, e.g. 's0', selects that scale.
168        label_paths: The labels, in the same form as `raw_paths`. For 'interactive', 'automatic' and 'joint'
169            training, these are instance segmentations, with 0 for the background. For 'semantic' training,
170            these are the class ids, with 0 for the background.
171        label_key: The key of the labels, in the same form as `raw_key`. For the labels of an ome-zarr file,
172            this is the label group, e.g. 'labels/cells', which selects its full resolution scale.
173        patch_shape: The shape of the training patches. Use (y, x) or (1, y, x) to train on 2d images or on
174            the 2d slices of volumes, and (z, y, x) to train on 3d patches of volumes.
175        mode: The training mode: 'interactive', 'automatic', 'joint' or 'semantic'.
176        ndim: The number of spatial dimensions to train in (2 or 3). By default, it is derived from `patch_shape`.
177        with_boundaries: Whether the targets of the automatic decoder include the object boundaries.
178            The decoders of the micro-sam2 models, e.g. 'hvit_t_cells', have them, so this must be True to
179            finetune them. Only used for the 'automatic' and the 'joint' training mode.
180        num_classes: The number of classes, the background included. Only used for 'semantic' training.
181        n_samples: The number of samples per epoch. By default, the number of images, or of patches that fit
182            into the volumes, and at least 100 for training and 5 for validation.
183        is_train: Whether this dataset is used for training or for validation. Only affects the default `n_samples`.
184        sampler: A sampler that rejects patches, e.g. patches without enough objects. By default, a patch needs
185            one object and background (or one class and background for 'semantic' training).
186        label_transform: An optional transform applied to the labels before the targets of the training mode
187            are computed. For example, `micro_sam.v2.transforms.labels.semantic_labels` converts an instance
188            segmentation into background, boundary and interior classes for 'semantic' training.
189            It must be importable from a module, because the checkpoint stores a reference to it.
190        rois: The region(s) of interest of the data, e.g. to train and validate on different parts of one volume.
191        with_channels: Whether the images of a container file have a channel axis. By default, image files are
192            checked for a channel axis, and container data is expected without one.
193        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`.
194
195    Returns:
196        The dataset. Each sample is a pair of tensors: the image, with shape (3, z, y, x), and the targets,
197        with shape (channels, z, y, x). A 2d image has a single z slice.
198
199    Raises:
200        ValueError: If the training mode, the patch shape or the data is not valid.
201    """
202    import torch_em
203    from ..normalization import normalize_raw
204    from ..datasets.wrapper import UniDataWrapper
205
206    if mode not in TRAINING_MODES:
207        raise ValueError(f"Invalid training mode '{mode}'. Choose one of {TRAINING_MODES}.")
208    patch_shape = tuple(int(size) for size in patch_shape)
209    if len(patch_shape) not in (2, 3):
210        raise ValueError(f"The patch shape must have two or three entries, got {patch_shape}.")
211    if ndim is None:
212        ndim = 3 if len(patch_shape) == 3 and patch_shape[0] > 1 else 2
213    if ndim not in (2, 3):
214        raise ValueError(f"The number of dimensions must be 2 or 3, got {ndim}.")
215    if ndim == 3 and len(patch_shape) != 3:
216        raise ValueError(f"Training in 3d needs a (z, y, x) patch shape, got {patch_shape}.")
217
218    raw_paths, raw_key = resolve_data_paths(raw_paths, raw_key)
219    label_paths, label_key = resolve_data_paths(label_paths, label_key)
220    if len(raw_paths) != len(label_paths):
221        raise ValueError(f"There are {len(raw_paths)} images, but {len(label_paths)} label images.")
222    if len(raw_paths) == 0:
223        raise ValueError("There are no images.")
224
225    # A list of 2d images (e.g. tif or png files, with or without channels) becomes an image collection,
226    # in which the images can have different shapes. Volumes and container data become a segmentation dataset.
227    shape = _data_shape(raw_paths[0], raw_key)
228    if ndim == 3 and len(shape) < 3:
229        raise ValueError(f"Training in 3d needs volumes, but the images have the shape {shape}.")
230    is_image = raw_key is None and (len(shape) == 2 or (ndim == 2 and _is_image_with_channels(shape)))
231
232    if is_image:
233        is_seg_dataset, data_patch_shape = False, patch_shape[-2:]
234        with_channels = len(shape) == 3 if with_channels is None else with_channels
235    else:
236        is_seg_dataset = True
237        with_channels = False if with_channels is None else with_channels
238        spatial_ndim = len(shape) - int(with_channels)
239        if ndim == 3:
240            data_patch_shape = patch_shape
241        elif spatial_ndim == 2:
242            data_patch_shape = patch_shape[-2:]
243        else:  # The 2d slices of a volume.
244            data_patch_shape = (1,) + patch_shape[-2:]
245
246    label_transform2, label_dtype, default_sampler = _label_settings(mode, with_boundaries, num_classes)
247    dataset_kwargs = dict(
248        raw_paths=raw_paths, raw_key=raw_key, label_paths=label_paths, label_key=label_key,
249        patch_shape=data_patch_shape, raw_transform=normalize_raw, label_transform=label_transform,
250        label_transform2=label_transform2, label_dtype=label_dtype, rois=rois,
251        sampler=default_sampler if sampler is None else sampler,
252        ndim=ndim, is_seg_dataset=is_seg_dataset, with_channels=with_channels, **kwargs,
253    )
254    dataset = torch_em.default_segmentation_dataset(n_samples=n_samples, **dataset_kwargs)
255    min_samples = MIN_TRAIN_SAMPLES if is_train else MIN_VAL_SAMPLES
256    if n_samples is None and len(dataset) < min_samples:
257        dataset = torch_em.default_segmentation_dataset(n_samples=min_samples, **dataset_kwargs)
258
259    # The micro-sam2 trainers expect every sample as (channels, z, y, x).
260    return UniDataWrapper(dataset, source_ndim=ndim)
261
262
263def default_sam2_loader(
264    raw_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
265    raw_key: Optional[str],
266    label_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
267    label_key: Optional[str],
268    patch_shape: Tuple[int, ...],
269    mode: str,
270    batch_size: int = 1,
271    num_workers: int = 4,
272    shuffle: Optional[bool] = None,
273    **dataset_kwargs,
274) -> DataLoader:
275    """Create a data loader for training a micro-sam2 model on images and their labels.
276
277    Pass the loader to the trainer of the training mode: `train_sam2` ('interactive'), `train_automatic`
278    ('automatic'), `train_joint_sam2` ('joint') or `train_semantic` ('semantic'), all in `micro_sam.v2.training`.
279
280    Example:
281        >>> train_loader = default_sam2_loader(
282        ...     "data/train.h5", "raw", "data/train.h5", "labels/cells", patch_shape=(512, 512), mode="joint",
283        ... )
284        >>> val_loader = default_sam2_loader(
285        ...     "data/val.h5", "raw", "data/val.h5", "labels/cells", patch_shape=(512, 512), mode="joint",
286        ...     is_train=False,
287        ... )
288        >>> train_joint_sam2("my_model", "hvit_t_cells", train_loader=train_loader, val_loader=val_loader)
289
290    Args:
291        raw_paths: The images, see `default_sam2_dataset`.
292        raw_key: The key of the images, see `default_sam2_dataset`.
293        label_paths: The labels, see `default_sam2_dataset`.
294        label_key: The key of the labels, see `default_sam2_dataset`.
295        patch_shape: The shape of the training patches, see `default_sam2_dataset`.
296        mode: The training mode: 'interactive', 'automatic', 'joint' or 'semantic'.
297        batch_size: The batch size.
298        num_workers: The number of loader workers.
299        shuffle: Whether to shuffle the samples. By default, they are shuffled for training only.
300        dataset_kwargs: Additional keyword arguments for `default_sam2_dataset`.
301
302    Returns:
303        The data loader.
304    """
305    import torch_em
306
307    dataset = default_sam2_dataset(raw_paths, raw_key, label_paths, label_key, patch_shape, mode, **dataset_kwargs)
308    if shuffle is None:
309        shuffle = dataset_kwargs.get("is_train", True)
310    return torch_em.get_data_loader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)
311
312
313def split_train_val_files(
314    paths: List, label_paths: List, val_fraction: float = 0.1, seed: int = 42,
315) -> Tuple[List, List, List, List]:
316    """Split the images and labels at the file level, into a training and a validation set.
317
318    Args:
319        paths: The image files, as returned by `resolve_data_paths`.
320        label_paths: The label files, in the same order.
321        val_fraction: The fraction of the files that are used for validation. At least one file is used.
322        seed: The seed for the random split.
323
324    Returns:
325        The training images, the training labels, the validation images and the validation labels.
326
327    Raises:
328        ValueError: If there are fewer than two files.
329    """
330    if len(paths) < 2:
331        raise ValueError(
332            "The data has only one file, so it cannot be split into a training and a validation set. "
333            "Pass separate validation data."
334        )
335    n_val = max(1, int(round(val_fraction * len(paths))))
336    order = np.random.default_rng(seed).permutation(len(paths))
337    val_ids, train_ids = sorted(order[:n_val]), sorted(order[n_val:])
338    return (
339        [paths[i] for i in train_ids], [label_paths[i] for i in train_ids],
340        [paths[i] for i in val_ids], [label_paths[i] for i in val_ids],
341    )
FilePath = typing.Union[str, os.PathLike]
TRAINING_MODES = ('interactive', 'automatic', 'joint', 'semantic')
MIN_TRAIN_SAMPLES = 100
MIN_VAL_SAMPLES = 5
GLOB_CHARACTERS = ('*', '?', '[')
def resolve_data_paths( paths: Union[str, os.PathLike, Sequence[Union[str, os.PathLike]], Sequence[numpy.ndarray]], key: Optional[str]) -> Tuple[list, Optional[str]]:
60def resolve_data_paths(
61    paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]], key: Optional[str],
62) -> Tuple[list, Optional[str]]:
63    """Resolve the image or label paths and key that a user passes to a list of inputs and a key.
64
65    A folder with a glob pattern as key, e.g. ('images/', '*.tif'), is expanded to the sorted list of matching
66    files, and the key becomes None. Each file is then one image (2d) or one volume (3d). A container file
67    (e.g. h5, zarr or n5) keeps its key, which selects the data inside the file. For an ome-zarr file, the
68    key can also be the image or label group, e.g. None for the image and 'labels/cells' for the labels:
69    it then selects the full resolution scale of that group.
70
71    Args:
72        paths: A file path, a folder, or a list of either. A list of numpy arrays is returned as it is.
73        key: The key of the data inside a container file, a glob pattern for a folder, or None for image files.
74
75    Returns:
76        The list of inputs, and the key for them.
77
78    Raises:
79        ValueError: If a folder with a glob pattern contains no matching file.
80    """
81    if isinstance(paths, (str, os.PathLike)):
82        paths = [paths]
83    paths = list(paths)
84    if len(paths) > 0 and isinstance(paths[0], (np.ndarray, torch.Tensor)):
85        return paths, None
86    if not _is_pattern(key):
87        paths = [str(path) for path in paths]
88        return paths, _ome_zarr_scale_key(paths[0], key) if paths else key
89
90    files = []
91    for folder in paths:
92        matches = sorted(glob(os.path.join(folder, key)))
93        if len(matches) == 0:
94            raise ValueError(f"There are no files matching '{key}' in '{folder}'.")
95        files.extend(matches)
96    return files, None

Resolve the image or label paths and key that a user passes to a list of inputs and a key.

A folder with a glob pattern as key, e.g. ('images/', '*.tif'), is expanded to the sorted list of matching files, and the key becomes None. Each file is then one image (2d) or one volume (3d). A container file (e.g. h5, zarr or n5) keeps its key, which selects the data inside the file. For an ome-zarr file, the key can also be the image or label group, e.g. None for the image and 'labels/cells' for the labels: it then selects the full resolution scale of that group.

Arguments:
  • paths: A file path, a folder, or a list of either. A list of numpy arrays is returned as it is.
  • key: The key of the data inside a container file, a glob pattern for a folder, or None for image files.
Returns:

The list of inputs, and the key for them.

Raises:
  • ValueError: If a folder with a glob pattern contains no matching file.
def default_sam2_dataset( raw_paths: Union[str, os.PathLike, Sequence[Union[str, os.PathLike]], Sequence[numpy.ndarray]], raw_key: Optional[str], label_paths: Union[str, os.PathLike, Sequence[Union[str, os.PathLike]], Sequence[numpy.ndarray]], label_key: Optional[str], patch_shape: Tuple[int, ...], mode: str, ndim: Optional[int] = None, with_boundaries: bool = True, num_classes: Optional[int] = None, n_samples: Optional[int] = None, is_train: bool = True, sampler: Optional[Callable] = None, label_transform: Optional[Callable] = None, rois: Union[Tuple[slice, ...], List[Tuple[slice, ...]], NoneType] = None, with_channels: Optional[bool] = None, **kwargs) -> torch.utils.data.dataset.Dataset:
139def default_sam2_dataset(
140    raw_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
141    raw_key: Optional[str],
142    label_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
143    label_key: Optional[str],
144    patch_shape: Tuple[int, ...],
145    mode: str,
146    ndim: Optional[int] = None,
147    with_boundaries: bool = True,
148    num_classes: Optional[int] = None,
149    n_samples: Optional[int] = None,
150    is_train: bool = True,
151    sampler: Optional[Callable] = None,
152    label_transform: Optional[Callable] = None,
153    rois: Optional[Union[Tuple[slice, ...], List[Tuple[slice, ...]]]] = None,
154    with_channels: Optional[bool] = None,
155    **kwargs,
156) -> Dataset:
157    """Create a dataset for training a micro-sam2 model on images and their labels.
158
159    The images are normalized to [0, 1] with `micro_sam.v2.normalization.normalize_raw`. Grayscale images
160    are copied to three channels. The labels are converted to the targets of the training mode.
161
162    Args:
163        raw_paths: The images. Either a file path, a folder (with a glob pattern in `raw_key`), a list of file
164            paths, or a list of numpy arrays. Supported are regular image files (e.g. tif or png) and container
165            files (e.g. h5, zarr, ome-zarr or n5).
166        raw_key: The key of the images: the internal dataset in a container file, e.g. 'raw', a glob pattern
167            for a folder, e.g. '*.tif', or None for image files. For an ome-zarr file, None selects the full
168            resolution image, and the path of a scale, e.g. 's0', selects that scale.
169        label_paths: The labels, in the same form as `raw_paths`. For 'interactive', 'automatic' and 'joint'
170            training, these are instance segmentations, with 0 for the background. For 'semantic' training,
171            these are the class ids, with 0 for the background.
172        label_key: The key of the labels, in the same form as `raw_key`. For the labels of an ome-zarr file,
173            this is the label group, e.g. 'labels/cells', which selects its full resolution scale.
174        patch_shape: The shape of the training patches. Use (y, x) or (1, y, x) to train on 2d images or on
175            the 2d slices of volumes, and (z, y, x) to train on 3d patches of volumes.
176        mode: The training mode: 'interactive', 'automatic', 'joint' or 'semantic'.
177        ndim: The number of spatial dimensions to train in (2 or 3). By default, it is derived from `patch_shape`.
178        with_boundaries: Whether the targets of the automatic decoder include the object boundaries.
179            The decoders of the micro-sam2 models, e.g. 'hvit_t_cells', have them, so this must be True to
180            finetune them. Only used for the 'automatic' and the 'joint' training mode.
181        num_classes: The number of classes, the background included. Only used for 'semantic' training.
182        n_samples: The number of samples per epoch. By default, the number of images, or of patches that fit
183            into the volumes, and at least 100 for training and 5 for validation.
184        is_train: Whether this dataset is used for training or for validation. Only affects the default `n_samples`.
185        sampler: A sampler that rejects patches, e.g. patches without enough objects. By default, a patch needs
186            one object and background (or one class and background for 'semantic' training).
187        label_transform: An optional transform applied to the labels before the targets of the training mode
188            are computed. For example, `micro_sam.v2.transforms.labels.semantic_labels` converts an instance
189            segmentation into background, boundary and interior classes for 'semantic' training.
190            It must be importable from a module, because the checkpoint stores a reference to it.
191        rois: The region(s) of interest of the data, e.g. to train and validate on different parts of one volume.
192        with_channels: Whether the images of a container file have a channel axis. By default, image files are
193            checked for a channel axis, and container data is expected without one.
194        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`.
195
196    Returns:
197        The dataset. Each sample is a pair of tensors: the image, with shape (3, z, y, x), and the targets,
198        with shape (channels, z, y, x). A 2d image has a single z slice.
199
200    Raises:
201        ValueError: If the training mode, the patch shape or the data is not valid.
202    """
203    import torch_em
204    from ..normalization import normalize_raw
205    from ..datasets.wrapper import UniDataWrapper
206
207    if mode not in TRAINING_MODES:
208        raise ValueError(f"Invalid training mode '{mode}'. Choose one of {TRAINING_MODES}.")
209    patch_shape = tuple(int(size) for size in patch_shape)
210    if len(patch_shape) not in (2, 3):
211        raise ValueError(f"The patch shape must have two or three entries, got {patch_shape}.")
212    if ndim is None:
213        ndim = 3 if len(patch_shape) == 3 and patch_shape[0] > 1 else 2
214    if ndim not in (2, 3):
215        raise ValueError(f"The number of dimensions must be 2 or 3, got {ndim}.")
216    if ndim == 3 and len(patch_shape) != 3:
217        raise ValueError(f"Training in 3d needs a (z, y, x) patch shape, got {patch_shape}.")
218
219    raw_paths, raw_key = resolve_data_paths(raw_paths, raw_key)
220    label_paths, label_key = resolve_data_paths(label_paths, label_key)
221    if len(raw_paths) != len(label_paths):
222        raise ValueError(f"There are {len(raw_paths)} images, but {len(label_paths)} label images.")
223    if len(raw_paths) == 0:
224        raise ValueError("There are no images.")
225
226    # A list of 2d images (e.g. tif or png files, with or without channels) becomes an image collection,
227    # in which the images can have different shapes. Volumes and container data become a segmentation dataset.
228    shape = _data_shape(raw_paths[0], raw_key)
229    if ndim == 3 and len(shape) < 3:
230        raise ValueError(f"Training in 3d needs volumes, but the images have the shape {shape}.")
231    is_image = raw_key is None and (len(shape) == 2 or (ndim == 2 and _is_image_with_channels(shape)))
232
233    if is_image:
234        is_seg_dataset, data_patch_shape = False, patch_shape[-2:]
235        with_channels = len(shape) == 3 if with_channels is None else with_channels
236    else:
237        is_seg_dataset = True
238        with_channels = False if with_channels is None else with_channels
239        spatial_ndim = len(shape) - int(with_channels)
240        if ndim == 3:
241            data_patch_shape = patch_shape
242        elif spatial_ndim == 2:
243            data_patch_shape = patch_shape[-2:]
244        else:  # The 2d slices of a volume.
245            data_patch_shape = (1,) + patch_shape[-2:]
246
247    label_transform2, label_dtype, default_sampler = _label_settings(mode, with_boundaries, num_classes)
248    dataset_kwargs = dict(
249        raw_paths=raw_paths, raw_key=raw_key, label_paths=label_paths, label_key=label_key,
250        patch_shape=data_patch_shape, raw_transform=normalize_raw, label_transform=label_transform,
251        label_transform2=label_transform2, label_dtype=label_dtype, rois=rois,
252        sampler=default_sampler if sampler is None else sampler,
253        ndim=ndim, is_seg_dataset=is_seg_dataset, with_channels=with_channels, **kwargs,
254    )
255    dataset = torch_em.default_segmentation_dataset(n_samples=n_samples, **dataset_kwargs)
256    min_samples = MIN_TRAIN_SAMPLES if is_train else MIN_VAL_SAMPLES
257    if n_samples is None and len(dataset) < min_samples:
258        dataset = torch_em.default_segmentation_dataset(n_samples=min_samples, **dataset_kwargs)
259
260    # The micro-sam2 trainers expect every sample as (channels, z, y, x).
261    return UniDataWrapper(dataset, source_ndim=ndim)

Create a dataset for training a micro-sam2 model on images and their labels.

The images are normalized to [0, 1] with micro_sam.v2.normalization.normalize_raw. Grayscale images are copied to three channels. The labels are converted to the targets of the training mode.

Arguments:
  • raw_paths: The images. Either a file path, a folder (with a glob pattern in raw_key), a list of file paths, or a list of numpy arrays. Supported are regular image files (e.g. tif or png) and container files (e.g. h5, zarr, ome-zarr or n5).
  • raw_key: The key of the images: the internal dataset in a container file, e.g. 'raw', a glob pattern for a folder, e.g. '*.tif', or None for image files. For an ome-zarr file, None selects the full resolution image, and the path of a scale, e.g. 's0', selects that scale.
  • label_paths: The labels, in the same form as raw_paths. For 'interactive', 'automatic' and 'joint' training, these are instance segmentations, with 0 for the background. For 'semantic' training, these are the class ids, with 0 for the background.
  • label_key: The key of the labels, in the same form as raw_key. For the labels of an ome-zarr file, this is the label group, e.g. 'labels/cells', which selects its full resolution scale.
  • patch_shape: The shape of the training patches. Use (y, x) or (1, y, x) to train on 2d images or on the 2d slices of volumes, and (z, y, x) to train on 3d patches of volumes.
  • mode: The training mode: 'interactive', 'automatic', 'joint' or 'semantic'.
  • ndim: The number of spatial dimensions to train in (2 or 3). By default, it is derived from patch_shape.
  • with_boundaries: Whether the targets of the automatic decoder include the object boundaries. The decoders of the micro-sam2 models, e.g. 'hvit_t_cells', have them, so this must be True to finetune them. Only used for the 'automatic' and the 'joint' training mode.
  • num_classes: The number of classes, the background included. Only used for 'semantic' training.
  • n_samples: The number of samples per epoch. By default, the number of images, or of patches that fit into the volumes, and at least 100 for training and 5 for validation.
  • is_train: Whether this dataset is used for training or for validation. Only affects the default n_samples.
  • sampler: A sampler that rejects patches, e.g. patches without enough objects. By default, a patch needs one object and background (or one class and background for 'semantic' training).
  • label_transform: An optional transform applied to the labels before the targets of the training mode are computed. For example, micro_sam.v2.transforms.labels.semantic_labels converts an instance segmentation into background, boundary and interior classes for 'semantic' training. It must be importable from a module, because the checkpoint stores a reference to it.
  • rois: The region(s) of interest of the data, e.g. to train and validate on different parts of one volume.
  • with_channels: Whether the images of a container file have a channel axis. By default, image files are checked for a channel axis, and container data is expected without one.
  • kwargs: Additional keyword arguments for torch_em.default_segmentation_dataset.
Returns:

The dataset. Each sample is a pair of tensors: the image, with shape (3, z, y, x), and the targets, with shape (channels, z, y, x). A 2d image has a single z slice.

Raises:
  • ValueError: If the training mode, the patch shape or the data is not valid.
def default_sam2_loader( raw_paths: Union[str, os.PathLike, Sequence[Union[str, os.PathLike]], Sequence[numpy.ndarray]], raw_key: Optional[str], label_paths: Union[str, os.PathLike, Sequence[Union[str, os.PathLike]], Sequence[numpy.ndarray]], label_key: Optional[str], patch_shape: Tuple[int, ...], mode: str, batch_size: int = 1, num_workers: int = 4, shuffle: Optional[bool] = None, **dataset_kwargs) -> torch.utils.data.dataloader.DataLoader:
264def default_sam2_loader(
265    raw_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
266    raw_key: Optional[str],
267    label_paths: Union[FilePath, Sequence[FilePath], Sequence[np.ndarray]],
268    label_key: Optional[str],
269    patch_shape: Tuple[int, ...],
270    mode: str,
271    batch_size: int = 1,
272    num_workers: int = 4,
273    shuffle: Optional[bool] = None,
274    **dataset_kwargs,
275) -> DataLoader:
276    """Create a data loader for training a micro-sam2 model on images and their labels.
277
278    Pass the loader to the trainer of the training mode: `train_sam2` ('interactive'), `train_automatic`
279    ('automatic'), `train_joint_sam2` ('joint') or `train_semantic` ('semantic'), all in `micro_sam.v2.training`.
280
281    Example:
282        >>> train_loader = default_sam2_loader(
283        ...     "data/train.h5", "raw", "data/train.h5", "labels/cells", patch_shape=(512, 512), mode="joint",
284        ... )
285        >>> val_loader = default_sam2_loader(
286        ...     "data/val.h5", "raw", "data/val.h5", "labels/cells", patch_shape=(512, 512), mode="joint",
287        ...     is_train=False,
288        ... )
289        >>> train_joint_sam2("my_model", "hvit_t_cells", train_loader=train_loader, val_loader=val_loader)
290
291    Args:
292        raw_paths: The images, see `default_sam2_dataset`.
293        raw_key: The key of the images, see `default_sam2_dataset`.
294        label_paths: The labels, see `default_sam2_dataset`.
295        label_key: The key of the labels, see `default_sam2_dataset`.
296        patch_shape: The shape of the training patches, see `default_sam2_dataset`.
297        mode: The training mode: 'interactive', 'automatic', 'joint' or 'semantic'.
298        batch_size: The batch size.
299        num_workers: The number of loader workers.
300        shuffle: Whether to shuffle the samples. By default, they are shuffled for training only.
301        dataset_kwargs: Additional keyword arguments for `default_sam2_dataset`.
302
303    Returns:
304        The data loader.
305    """
306    import torch_em
307
308    dataset = default_sam2_dataset(raw_paths, raw_key, label_paths, label_key, patch_shape, mode, **dataset_kwargs)
309    if shuffle is None:
310        shuffle = dataset_kwargs.get("is_train", True)
311    return torch_em.get_data_loader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)

Create a data loader for training a micro-sam2 model on images and their labels.

Pass the loader to the trainer of the training mode: train_sam2 ('interactive'), train_automatic ('automatic'), train_joint_sam2 ('joint') or train_semantic ('semantic'), all in micro_sam.v2.training.

Example:
>>> train_loader = default_sam2_loader(
...     "data/train.h5", "raw", "data/train.h5", "labels/cells", patch_shape=(512, 512), mode="joint",
... )
>>> val_loader = default_sam2_loader(
...     "data/val.h5", "raw", "data/val.h5", "labels/cells", patch_shape=(512, 512), mode="joint",
...     is_train=False,
... )
>>> train_joint_sam2("my_model", "hvit_t_cells", train_loader=train_loader, val_loader=val_loader)
Arguments:
  • raw_paths: The images, see default_sam2_dataset.
  • raw_key: The key of the images, see default_sam2_dataset.
  • label_paths: The labels, see default_sam2_dataset.
  • label_key: The key of the labels, see default_sam2_dataset.
  • patch_shape: The shape of the training patches, see default_sam2_dataset.
  • mode: The training mode: 'interactive', 'automatic', 'joint' or 'semantic'.
  • batch_size: The batch size.
  • num_workers: The number of loader workers.
  • shuffle: Whether to shuffle the samples. By default, they are shuffled for training only.
  • dataset_kwargs: Additional keyword arguments for default_sam2_dataset.
Returns:

The data loader.

def split_train_val_files( paths: List, label_paths: List, val_fraction: float = 0.1, seed: int = 42) -> Tuple[List, List, List, List]:
314def split_train_val_files(
315    paths: List, label_paths: List, val_fraction: float = 0.1, seed: int = 42,
316) -> Tuple[List, List, List, List]:
317    """Split the images and labels at the file level, into a training and a validation set.
318
319    Args:
320        paths: The image files, as returned by `resolve_data_paths`.
321        label_paths: The label files, in the same order.
322        val_fraction: The fraction of the files that are used for validation. At least one file is used.
323        seed: The seed for the random split.
324
325    Returns:
326        The training images, the training labels, the validation images and the validation labels.
327
328    Raises:
329        ValueError: If there are fewer than two files.
330    """
331    if len(paths) < 2:
332        raise ValueError(
333            "The data has only one file, so it cannot be split into a training and a validation set. "
334            "Pass separate validation data."
335        )
336    n_val = max(1, int(round(val_fraction * len(paths))))
337    order = np.random.default_rng(seed).permutation(len(paths))
338    val_ids, train_ids = sorted(order[:n_val]), sorted(order[n_val:])
339    return (
340        [paths[i] for i in train_ids], [label_paths[i] for i in train_ids],
341        [paths[i] for i in val_ids], [label_paths[i] for i in val_ids],
342    )

Split the images and labels at the file level, into a training and a validation set.

Arguments:
  • paths: The image files, as returned by resolve_data_paths.
  • label_paths: The label files, in the same order.
  • val_fraction: The fraction of the files that are used for validation. At least one file is used.
  • seed: The seed for the random split.
Returns:

The training images, the training labels, the validation images and the validation labels.

Raises:
  • ValueError: If there are fewer than two files.