torch_em.data.datasets.light_microscopy.dcis_com_nuclei

The DCIS.COM nuclei dataset contains SiR-DNA fluorescence images with instance annotations.

The dataset contains images of DCIS.COM cells acquired with spinning disk confocal microscopy. It is located at https://www.ebi.ac.uk/biostudies/bioimages/studies/S-BIAD895. The original dataset is available at https://doi.org/10.5281/zenodo.3715492 under the CC BY 4.0 license. Please cite the dataset record if you use this dataset in your research.

  1"""The DCIS.COM nuclei dataset contains SiR-DNA fluorescence images with instance annotations.
  2
  3The dataset contains images of DCIS.COM cells acquired with spinning disk confocal microscopy.
  4It is located at https://www.ebi.ac.uk/biostudies/bioimages/studies/S-BIAD895.
  5The original dataset is available at https://doi.org/10.5281/zenodo.3715492 under the CC BY 4.0 license.
  6Please cite the dataset record if you use this dataset in your research.
  7"""
  8
  9import os
 10from glob import glob
 11from shutil import rmtree
 12from typing import List, Literal, Optional, Tuple, Union
 13
 14from torch.utils.data import DataLoader, Dataset
 15
 16import torch_em
 17
 18from .. import util
 19
 20
 21URL = "https://zenodo.org/records/3715492/files/Stardist_v2.zip?download=1"
 22CHECKSUM = "aec767afae76942b7c97e31c500284f8b5862150d8e81b57f513e66d7258c05e"
 23
 24SPLIT_FOLDERS = {
 25    "train": ("Training - Images", "Training - Masks"),
 26    "test": ("Test - Images", "Test - Masks"),
 27}
 28EXPECTED_SAMPLES = {"train": 45, "test": 2}
 29INVALID_TRAIN_IMAGES = {
 30    "cell migration R1 - Position 0_XY1562686096_Z0_T00_C1-1-image7.tif",
 31    "cell migration R1 - Position 0_XY1562686096_Z0_T00_C1-1-image14.tif",
 32}
 33
 34
 35def get_dcis_com_nuclei_data(path: Union[os.PathLike, str], download: bool = False) -> str:
 36    """Download the DCIS.COM nuclei dataset (S-BIAD895).
 37
 38    Args:
 39        path: Filepath to a folder where the downloaded data will be saved.
 40        download: Whether to download the data if it is not present.
 41
 42    Returns:
 43        The filepath to the downloaded data.
 44    """
 45    data_dir = os.path.join(path, "Stardist")
 46    expected_folders = [os.path.join(data_dir, folder) for folders in SPLIT_FOLDERS.values() for folder in folders]
 47    if all(os.path.exists(folder) for folder in expected_folders):
 48        return data_dir
 49
 50    os.makedirs(path, exist_ok=True)
 51    zip_path = os.path.join(path, "Stardist_v2.zip")
 52    util.download_source(zip_path, URL, download, CHECKSUM)
 53    util.unzip(zip_path, path)
 54
 55    macos_dir = os.path.join(path, "__MACOSX")
 56    if os.path.exists(macos_dir):
 57        rmtree(macos_dir)
 58
 59    if not all(os.path.exists(folder) for folder in expected_folders):
 60        raise RuntimeError("The downloaded S-BIAD895 archive has an unexpected structure.")
 61    return data_dir
 62
 63
 64def get_dcis_com_nuclei_paths(
 65    path: Union[os.PathLike, str],
 66    split: Literal["train", "test"] = "train",
 67    download: bool = False,
 68) -> Tuple[List[str], List[str]]:
 69    """Get paths to the DCIS.COM nuclei images and instance labels.
 70
 71    Two training images are excluded because their source masks are exact copies of the mask for
 72    ``image1.tif`` and do not align with the corresponding images.
 73
 74    Args:
 75        path: Filepath to a folder where the downloaded data will be saved.
 76        split: The data split. Either 'train' or 'test'.
 77        download: Whether to download the data if it is not present.
 78
 79    Returns:
 80        The image paths and corresponding label paths.
 81    """
 82    if split not in SPLIT_FOLDERS:
 83        raise ValueError(f"'{split}' is not a valid split. Choose from {list(SPLIT_FOLDERS)}.")
 84
 85    data_dir = get_dcis_com_nuclei_data(path, download)
 86    image_folder, label_folder = SPLIT_FOLDERS[split]
 87    image_paths = sorted(glob(os.path.join(data_dir, image_folder, "*.tif")))
 88
 89    expected_samples = EXPECTED_SAMPLES[split]
 90    if len(image_paths) != expected_samples:
 91        raise RuntimeError(
 92            f"Expected {expected_samples} images for split '{split}', but found {len(image_paths)}."
 93        )
 94
 95    if split == "train":
 96        image_paths = [
 97            image_path for image_path in image_paths if os.path.basename(image_path) not in INVALID_TRAIN_IMAGES
 98        ]
 99
100    label_folder = os.path.join(data_dir, label_folder)
101    label_paths = [os.path.join(label_folder, os.path.basename(image_path)) for image_path in image_paths]
102    missing_labels = [label_path for label_path in label_paths if not os.path.exists(label_path)]
103    if missing_labels:
104        raise RuntimeError(f"Could not find labels for {len(missing_labels)} images in '{label_folder}'.")
105
106    return image_paths, label_paths
107
108
109def get_dcis_com_nuclei_dataset(
110    path: Union[os.PathLike, str],
111    patch_shape: Tuple[int, int],
112    split: Literal["train", "test"] = "train",
113    offsets: Optional[List[List[int]]] = None,
114    boundaries: bool = False,
115    binary: bool = False,
116    download: bool = False,
117    **kwargs,
118) -> Dataset:
119    """Get the DCIS.COM nuclei dataset for instance segmentation.
120
121    Args:
122        path: Filepath to a folder where the downloaded data will be saved.
123        patch_shape: The patch shape to use for training.
124        split: The data split. Either 'train' or 'test'.
125        offsets: Offset values for affinity computation used as target.
126        boundaries: Whether to compute boundaries as the target.
127        binary: Whether to use a binary segmentation target.
128        download: Whether to download the data if it is not present.
129        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`.
130
131    Returns:
132        The segmentation dataset.
133    """
134    image_paths, label_paths = get_dcis_com_nuclei_paths(path, split, download)
135
136    kwargs, _ = util.add_instance_label_transform(
137        kwargs, add_binary_target=True, offsets=offsets, boundaries=boundaries, binary=binary,
138    )
139    kwargs = util.update_kwargs(kwargs, "is_seg_dataset", False)
140
141    return torch_em.default_segmentation_dataset(
142        raw_paths=image_paths,
143        raw_key=None,
144        label_paths=label_paths,
145        label_key=None,
146        patch_shape=patch_shape,
147        **kwargs,
148    )
149
150
151def get_dcis_com_nuclei_loader(
152    path: Union[os.PathLike, str],
153    batch_size: int,
154    patch_shape: Tuple[int, int],
155    split: Literal["train", "test"] = "train",
156    offsets: Optional[List[List[int]]] = None,
157    boundaries: bool = False,
158    binary: bool = False,
159    download: bool = False,
160    **kwargs,
161) -> DataLoader:
162    """Get the DCIS.COM nuclei dataloader for instance segmentation.
163
164    Args:
165        path: Filepath to a folder where the downloaded data will be saved.
166        batch_size: The batch size for training.
167        patch_shape: The patch shape to use for training.
168        split: The data split. Either 'train' or 'test'.
169        offsets: Offset values for affinity computation used as target.
170        boundaries: Whether to compute boundaries as the target.
171        binary: Whether to use a binary segmentation target.
172        download: Whether to download the data if it is not present.
173        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset` or for the PyTorch DataLoader.
174
175    Returns:
176        The DataLoader.
177    """
178    ds_kwargs, loader_kwargs = util.split_kwargs(torch_em.default_segmentation_dataset, **kwargs)
179    dataset = get_dcis_com_nuclei_dataset(
180        path=path,
181        patch_shape=patch_shape,
182        split=split,
183        offsets=offsets,
184        boundaries=boundaries,
185        binary=binary,
186        download=download,
187        **ds_kwargs,
188    )
189    return torch_em.get_data_loader(dataset, batch_size=batch_size, **loader_kwargs)
URL = 'https://zenodo.org/records/3715492/files/Stardist_v2.zip?download=1'
CHECKSUM = 'aec767afae76942b7c97e31c500284f8b5862150d8e81b57f513e66d7258c05e'
SPLIT_FOLDERS = {'train': ('Training - Images', 'Training - Masks'), 'test': ('Test - Images', 'Test - Masks')}
EXPECTED_SAMPLES = {'train': 45, 'test': 2}
INVALID_TRAIN_IMAGES = {'cell migration R1 - Position 0_XY1562686096_Z0_T00_C1-1-image7.tif', 'cell migration R1 - Position 0_XY1562686096_Z0_T00_C1-1-image14.tif'}
def get_dcis_com_nuclei_data(path: Union[os.PathLike, str], download: bool = False) -> str:
36def get_dcis_com_nuclei_data(path: Union[os.PathLike, str], download: bool = False) -> str:
37    """Download the DCIS.COM nuclei dataset (S-BIAD895).
38
39    Args:
40        path: Filepath to a folder where the downloaded data will be saved.
41        download: Whether to download the data if it is not present.
42
43    Returns:
44        The filepath to the downloaded data.
45    """
46    data_dir = os.path.join(path, "Stardist")
47    expected_folders = [os.path.join(data_dir, folder) for folders in SPLIT_FOLDERS.values() for folder in folders]
48    if all(os.path.exists(folder) for folder in expected_folders):
49        return data_dir
50
51    os.makedirs(path, exist_ok=True)
52    zip_path = os.path.join(path, "Stardist_v2.zip")
53    util.download_source(zip_path, URL, download, CHECKSUM)
54    util.unzip(zip_path, path)
55
56    macos_dir = os.path.join(path, "__MACOSX")
57    if os.path.exists(macos_dir):
58        rmtree(macos_dir)
59
60    if not all(os.path.exists(folder) for folder in expected_folders):
61        raise RuntimeError("The downloaded S-BIAD895 archive has an unexpected structure.")
62    return data_dir

Download the DCIS.COM nuclei dataset (S-BIAD895).

Arguments:
  • path: Filepath to a folder where the downloaded data will be saved.
  • download: Whether to download the data if it is not present.
Returns:

The filepath to the downloaded data.

def get_dcis_com_nuclei_paths( path: Union[os.PathLike, str], split: Literal['train', 'test'] = 'train', download: bool = False) -> Tuple[List[str], List[str]]:
 65def get_dcis_com_nuclei_paths(
 66    path: Union[os.PathLike, str],
 67    split: Literal["train", "test"] = "train",
 68    download: bool = False,
 69) -> Tuple[List[str], List[str]]:
 70    """Get paths to the DCIS.COM nuclei images and instance labels.
 71
 72    Two training images are excluded because their source masks are exact copies of the mask for
 73    ``image1.tif`` and do not align with the corresponding images.
 74
 75    Args:
 76        path: Filepath to a folder where the downloaded data will be saved.
 77        split: The data split. Either 'train' or 'test'.
 78        download: Whether to download the data if it is not present.
 79
 80    Returns:
 81        The image paths and corresponding label paths.
 82    """
 83    if split not in SPLIT_FOLDERS:
 84        raise ValueError(f"'{split}' is not a valid split. Choose from {list(SPLIT_FOLDERS)}.")
 85
 86    data_dir = get_dcis_com_nuclei_data(path, download)
 87    image_folder, label_folder = SPLIT_FOLDERS[split]
 88    image_paths = sorted(glob(os.path.join(data_dir, image_folder, "*.tif")))
 89
 90    expected_samples = EXPECTED_SAMPLES[split]
 91    if len(image_paths) != expected_samples:
 92        raise RuntimeError(
 93            f"Expected {expected_samples} images for split '{split}', but found {len(image_paths)}."
 94        )
 95
 96    if split == "train":
 97        image_paths = [
 98            image_path for image_path in image_paths if os.path.basename(image_path) not in INVALID_TRAIN_IMAGES
 99        ]
100
101    label_folder = os.path.join(data_dir, label_folder)
102    label_paths = [os.path.join(label_folder, os.path.basename(image_path)) for image_path in image_paths]
103    missing_labels = [label_path for label_path in label_paths if not os.path.exists(label_path)]
104    if missing_labels:
105        raise RuntimeError(f"Could not find labels for {len(missing_labels)} images in '{label_folder}'.")
106
107    return image_paths, label_paths

Get paths to the DCIS.COM nuclei images and instance labels.

Two training images are excluded because their source masks are exact copies of the mask for image1.tif and do not align with the corresponding images.

Arguments:
  • path: Filepath to a folder where the downloaded data will be saved.
  • split: The data split. Either 'train' or 'test'.
  • download: Whether to download the data if it is not present.
Returns:

The image paths and corresponding label paths.

def get_dcis_com_nuclei_dataset( path: Union[os.PathLike, str], patch_shape: Tuple[int, int], split: Literal['train', 'test'] = 'train', offsets: Optional[List[List[int]]] = None, boundaries: bool = False, binary: bool = False, download: bool = False, **kwargs) -> torch.utils.data.dataset.Dataset:
110def get_dcis_com_nuclei_dataset(
111    path: Union[os.PathLike, str],
112    patch_shape: Tuple[int, int],
113    split: Literal["train", "test"] = "train",
114    offsets: Optional[List[List[int]]] = None,
115    boundaries: bool = False,
116    binary: bool = False,
117    download: bool = False,
118    **kwargs,
119) -> Dataset:
120    """Get the DCIS.COM nuclei dataset for instance segmentation.
121
122    Args:
123        path: Filepath to a folder where the downloaded data will be saved.
124        patch_shape: The patch shape to use for training.
125        split: The data split. Either 'train' or 'test'.
126        offsets: Offset values for affinity computation used as target.
127        boundaries: Whether to compute boundaries as the target.
128        binary: Whether to use a binary segmentation target.
129        download: Whether to download the data if it is not present.
130        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`.
131
132    Returns:
133        The segmentation dataset.
134    """
135    image_paths, label_paths = get_dcis_com_nuclei_paths(path, split, download)
136
137    kwargs, _ = util.add_instance_label_transform(
138        kwargs, add_binary_target=True, offsets=offsets, boundaries=boundaries, binary=binary,
139    )
140    kwargs = util.update_kwargs(kwargs, "is_seg_dataset", False)
141
142    return torch_em.default_segmentation_dataset(
143        raw_paths=image_paths,
144        raw_key=None,
145        label_paths=label_paths,
146        label_key=None,
147        patch_shape=patch_shape,
148        **kwargs,
149    )

Get the DCIS.COM nuclei dataset for instance segmentation.

Arguments:
  • path: Filepath to a folder where the downloaded data will be saved.
  • patch_shape: The patch shape to use for training.
  • split: The data split. Either 'train' or 'test'.
  • offsets: Offset values for affinity computation used as target.
  • boundaries: Whether to compute boundaries as the target.
  • binary: Whether to use a binary segmentation target.
  • download: Whether to download the data if it is not present.
  • kwargs: Additional keyword arguments for torch_em.default_segmentation_dataset.
Returns:

The segmentation dataset.

def get_dcis_com_nuclei_loader( path: Union[os.PathLike, str], batch_size: int, patch_shape: Tuple[int, int], split: Literal['train', 'test'] = 'train', offsets: Optional[List[List[int]]] = None, boundaries: bool = False, binary: bool = False, download: bool = False, **kwargs) -> torch.utils.data.dataloader.DataLoader:
152def get_dcis_com_nuclei_loader(
153    path: Union[os.PathLike, str],
154    batch_size: int,
155    patch_shape: Tuple[int, int],
156    split: Literal["train", "test"] = "train",
157    offsets: Optional[List[List[int]]] = None,
158    boundaries: bool = False,
159    binary: bool = False,
160    download: bool = False,
161    **kwargs,
162) -> DataLoader:
163    """Get the DCIS.COM nuclei dataloader for instance segmentation.
164
165    Args:
166        path: Filepath to a folder where the downloaded data will be saved.
167        batch_size: The batch size for training.
168        patch_shape: The patch shape to use for training.
169        split: The data split. Either 'train' or 'test'.
170        offsets: Offset values for affinity computation used as target.
171        boundaries: Whether to compute boundaries as the target.
172        binary: Whether to use a binary segmentation target.
173        download: Whether to download the data if it is not present.
174        kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset` or for the PyTorch DataLoader.
175
176    Returns:
177        The DataLoader.
178    """
179    ds_kwargs, loader_kwargs = util.split_kwargs(torch_em.default_segmentation_dataset, **kwargs)
180    dataset = get_dcis_com_nuclei_dataset(
181        path=path,
182        patch_shape=patch_shape,
183        split=split,
184        offsets=offsets,
185        boundaries=boundaries,
186        binary=binary,
187        download=download,
188        **ds_kwargs,
189    )
190    return torch_em.get_data_loader(dataset, batch_size=batch_size, **loader_kwargs)

Get the DCIS.COM nuclei dataloader for instance segmentation.

Arguments:
  • path: Filepath to a folder where the downloaded data will be saved.
  • batch_size: The batch size for training.
  • patch_shape: The patch shape to use for training.
  • split: The data split. Either 'train' or 'test'.
  • offsets: Offset values for affinity computation used as target.
  • boundaries: Whether to compute boundaries as the target.
  • binary: Whether to use a binary segmentation target.
  • download: Whether to download the data if it is not present.
  • kwargs: Additional keyword arguments for torch_em.default_segmentation_dataset or for the PyTorch DataLoader.
Returns:

The DataLoader.