micro_sam.v2.datasets.cochleanet_data
CochleaNet holds annotations for 3d instance segmentation in light-sheet volumes of the mouse cochlea: inner hair cells (IHC, Vglut3 stain) and spiral ganglion neurons (SGN, PV stain).
This is an internal dataset of the CochleaNet project. It is not public and cannot be downloaded; the functions
expect the project's export folder, which holds the 'IHC_v11_2026-07' and 'SGN_v3_2026-07' subfolders, each split
into 'train' and 'val', with every volume a tif next to a '
1"""CochleaNet holds annotations for 3d instance segmentation in light-sheet volumes of the mouse cochlea: 2inner hair cells (IHC, Vglut3 stain) and spiral ganglion neurons (SGN, PV stain). 3 4This is an internal dataset of the CochleaNet project. It is not public and cannot be downloaded; the functions 5expect the project's export folder, which holds the 'IHC_v11_2026-07' and 'SGN_v3_2026-07' subfolders, each split 6into 'train' and 'val', with every volume a tif next to a '<name>_annotations.tif' instance segmentation. The 7volumes are converted once to h5 files under 'preprocessed'. 8""" 9 10import os 11from glob import glob 12from typing import List, Tuple, Union, Literal 13 14import h5py 15import tifffile 16import numpy as np 17from natsort import natsorted 18 19from torch.utils.data import Dataset, DataLoader 20 21import torch_em 22from torch_em.data.datasets import util 23 24SOURCES = {"sgn": "SGN_v3_2026-07", "ihc": "IHC_v11_2026-07"} 25 26# The 'empty' volumes hold no object. The SGN volumes named 'resized' were interpolated from a coarser acquisition 27# and are only partly annotated. The IHC 'G-LR' crops label a few inner hair cells next to unlabelled rows of cells. 28EXCLUDED = {"sgn": ("_empty", "resized"), "ihc": ("_empty", "G-LR")} 29 30# These IHC blocks are near-isotropic crops stored with their shortest axis last; that axis serves as z. 31Z_LAST_SHAPE = (512, 512, 256) 32 33 34def _preprocess_split(source_dir, data_dir, excluded): 35 os.makedirs(data_dir, exist_ok=True) 36 for raw_path in natsorted(glob(os.path.join(source_dir, "*.tif"))): 37 name = os.path.basename(raw_path)[:-len(".tif")] 38 if name.endswith("_annotations") or any(token in name for token in excluded): 39 continue 40 h5_path = os.path.join(data_dir, f"{name}.h5") 41 if os.path.exists(h5_path): 42 continue 43 labels = tifffile.imread(os.path.join(source_dir, f"{name}_annotations.tif")) 44 if labels.max() == 0: 45 continue 46 raw = tifffile.imread(raw_path) 47 assert raw.shape == labels.shape, f"Shape mismatch for {name}: raw={raw.shape}, labels={labels.shape}" 48 if raw.shape == Z_LAST_SHAPE: 49 raw, labels = np.moveaxis(raw, 2, 0), np.moveaxis(labels, 2, 0) 50 # Some blocks number their objects with 64 bit ids; relabel to 1..n. 51 labels = np.unique(labels, return_inverse=True)[1].reshape(labels.shape).astype("uint32") 52 chunks = (1, min(512, raw.shape[1]), min(512, raw.shape[2])) 53 # Several ranks may convert at once: each writes its own file and the rename is atomic. 54 tmp_path = f"{h5_path}.tmp{os.getpid()}" 55 with h5py.File(tmp_path, "w") as f: 56 f.create_dataset("raw", data=np.ascontiguousarray(raw), chunks=chunks, compression="gzip") 57 f.create_dataset("labels", data=np.ascontiguousarray(labels), chunks=chunks, compression="gzip") 58 os.replace(tmp_path, h5_path) 59 60 61def get_cochleanet_data( 62 path: Union[os.PathLike, str], name: Literal["sgn", "ihc"], split: Literal["train", "val"] 63) -> str: 64 """Convert one split of a CochleaNet subset to h5 volumes with 'raw' and 'labels' datasets. 65 66 Args: 67 path: The project's export folder. 68 name: The subset, 'sgn' or 'ihc'. 69 split: The data split, 'train' or 'val'. 70 71 Returns: 72 The folder with the converted volumes. 73 """ 74 if name not in SOURCES: 75 raise ValueError(f"'{name}' is not a valid subset. Choose one of {list(SOURCES)}.") 76 if split not in ("train", "val"): 77 raise ValueError(f"'{split}' is not a valid split. Choose 'train' or 'val'.") 78 data_dir = os.path.join(path, "preprocessed", name, split) 79 _preprocess_split(os.path.join(path, SOURCES[name], split), data_dir, EXCLUDED[name]) 80 return data_dir 81 82 83def get_cochleanet_sgn_data(path: Union[os.PathLike, str], split: Literal["train", "val"]) -> str: 84 """Convert one split of the spiral ganglion neuron volumes, see `get_cochleanet_data`.""" 85 return get_cochleanet_data(path, "sgn", split) 86 87 88def get_cochleanet_ihc_data(path: Union[os.PathLike, str], split: Literal["train", "val"]) -> str: 89 """Convert one split of the inner hair cell volumes, see `get_cochleanet_data`.""" 90 return get_cochleanet_data(path, "ihc", split) 91 92 93def get_cochleanet_paths( 94 path: Union[os.PathLike, str], name: Literal["sgn", "ihc"], split: Literal["train", "val"] 95) -> List[str]: 96 """Get the paths to the CochleaNet volumes of one subset and split. 97 98 Args: 99 path: The project's export folder. 100 name: The subset, 'sgn' or 'ihc'. 101 split: The data split, 'train' or 'val'. 102 103 Returns: 104 The filepaths of the h5 volumes, which hold the 'raw' and 'labels' datasets. 105 """ 106 data_dir = get_cochleanet_data(path, name, split) 107 paths = natsorted(glob(os.path.join(data_dir, "*.h5"))) 108 assert len(paths) > 0 109 return paths 110 111 112def get_cochleanet_dataset( 113 path: Union[os.PathLike, str], 114 patch_shape: Tuple[int, int, int], 115 name: Literal["sgn", "ihc"], 116 split: Literal["train", "val"], 117 **kwargs 118) -> Dataset: 119 """Get the CochleaNet dataset for 3d instance segmentation of inner hair cells or spiral ganglion neurons. 120 121 Args: 122 path: The project's export folder. 123 patch_shape: The patch shape to use for training. 124 name: The subset, 'sgn' or 'ihc'. 125 split: The data split, 'train' or 'val'. 126 kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`. 127 128 Returns: 129 The segmentation dataset. 130 """ 131 paths = get_cochleanet_paths(path, name, split) 132 kwargs = util.ensure_transforms(ndim=3, **kwargs) 133 return torch_em.default_segmentation_dataset( 134 raw_paths=paths, raw_key="raw", label_paths=paths, label_key="labels", patch_shape=patch_shape, ndim=3, **kwargs 135 ) 136 137 138def get_cochleanet_loader( 139 path: Union[os.PathLike, str], 140 batch_size: int, 141 patch_shape: Tuple[int, int, int], 142 name: Literal["sgn", "ihc"], 143 split: Literal["train", "val"], 144 **kwargs 145) -> DataLoader: 146 """Get the CochleaNet dataloader for 3d instance segmentation of inner hair cells or spiral ganglion neurons. 147 148 Args: 149 path: The project's export folder. 150 batch_size: The batch size for training. 151 patch_shape: The patch shape to use for training. 152 name: The subset, 'sgn' or 'ihc'. 153 split: The data split, 'train' or 'val'. 154 kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset` or for the PyTorch DataLoader. 155 156 Returns: 157 The DataLoader. 158 """ 159 ds_kwargs, loader_kwargs = util.split_kwargs(torch_em.default_segmentation_dataset, **kwargs) 160 dataset = get_cochleanet_dataset(path, patch_shape, name, split, **ds_kwargs) 161 return torch_em.get_data_loader(dataset=dataset, batch_size=batch_size, **loader_kwargs)
62def get_cochleanet_data( 63 path: Union[os.PathLike, str], name: Literal["sgn", "ihc"], split: Literal["train", "val"] 64) -> str: 65 """Convert one split of a CochleaNet subset to h5 volumes with 'raw' and 'labels' datasets. 66 67 Args: 68 path: The project's export folder. 69 name: The subset, 'sgn' or 'ihc'. 70 split: The data split, 'train' or 'val'. 71 72 Returns: 73 The folder with the converted volumes. 74 """ 75 if name not in SOURCES: 76 raise ValueError(f"'{name}' is not a valid subset. Choose one of {list(SOURCES)}.") 77 if split not in ("train", "val"): 78 raise ValueError(f"'{split}' is not a valid split. Choose 'train' or 'val'.") 79 data_dir = os.path.join(path, "preprocessed", name, split) 80 _preprocess_split(os.path.join(path, SOURCES[name], split), data_dir, EXCLUDED[name]) 81 return data_dir
Convert one split of a CochleaNet subset to h5 volumes with 'raw' and 'labels' datasets.
Arguments:
- path: The project's export folder.
- name: The subset, 'sgn' or 'ihc'.
- split: The data split, 'train' or 'val'.
Returns:
The folder with the converted volumes.
84def get_cochleanet_sgn_data(path: Union[os.PathLike, str], split: Literal["train", "val"]) -> str: 85 """Convert one split of the spiral ganglion neuron volumes, see `get_cochleanet_data`.""" 86 return get_cochleanet_data(path, "sgn", split)
Convert one split of the spiral ganglion neuron volumes, see get_cochleanet_data.
89def get_cochleanet_ihc_data(path: Union[os.PathLike, str], split: Literal["train", "val"]) -> str: 90 """Convert one split of the inner hair cell volumes, see `get_cochleanet_data`.""" 91 return get_cochleanet_data(path, "ihc", split)
Convert one split of the inner hair cell volumes, see get_cochleanet_data.
94def get_cochleanet_paths( 95 path: Union[os.PathLike, str], name: Literal["sgn", "ihc"], split: Literal["train", "val"] 96) -> List[str]: 97 """Get the paths to the CochleaNet volumes of one subset and split. 98 99 Args: 100 path: The project's export folder. 101 name: The subset, 'sgn' or 'ihc'. 102 split: The data split, 'train' or 'val'. 103 104 Returns: 105 The filepaths of the h5 volumes, which hold the 'raw' and 'labels' datasets. 106 """ 107 data_dir = get_cochleanet_data(path, name, split) 108 paths = natsorted(glob(os.path.join(data_dir, "*.h5"))) 109 assert len(paths) > 0 110 return paths
Get the paths to the CochleaNet volumes of one subset and split.
Arguments:
- path: The project's export folder.
- name: The subset, 'sgn' or 'ihc'.
- split: The data split, 'train' or 'val'.
Returns:
The filepaths of the h5 volumes, which hold the 'raw' and 'labels' datasets.
113def get_cochleanet_dataset( 114 path: Union[os.PathLike, str], 115 patch_shape: Tuple[int, int, int], 116 name: Literal["sgn", "ihc"], 117 split: Literal["train", "val"], 118 **kwargs 119) -> Dataset: 120 """Get the CochleaNet dataset for 3d instance segmentation of inner hair cells or spiral ganglion neurons. 121 122 Args: 123 path: The project's export folder. 124 patch_shape: The patch shape to use for training. 125 name: The subset, 'sgn' or 'ihc'. 126 split: The data split, 'train' or 'val'. 127 kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset`. 128 129 Returns: 130 The segmentation dataset. 131 """ 132 paths = get_cochleanet_paths(path, name, split) 133 kwargs = util.ensure_transforms(ndim=3, **kwargs) 134 return torch_em.default_segmentation_dataset( 135 raw_paths=paths, raw_key="raw", label_paths=paths, label_key="labels", patch_shape=patch_shape, ndim=3, **kwargs 136 )
Get the CochleaNet dataset for 3d instance segmentation of inner hair cells or spiral ganglion neurons.
Arguments:
- path: The project's export folder.
- patch_shape: The patch shape to use for training.
- name: The subset, 'sgn' or 'ihc'.
- split: The data split, 'train' or 'val'.
- kwargs: Additional keyword arguments for
torch_em.default_segmentation_dataset.
Returns:
The segmentation dataset.
139def get_cochleanet_loader( 140 path: Union[os.PathLike, str], 141 batch_size: int, 142 patch_shape: Tuple[int, int, int], 143 name: Literal["sgn", "ihc"], 144 split: Literal["train", "val"], 145 **kwargs 146) -> DataLoader: 147 """Get the CochleaNet dataloader for 3d instance segmentation of inner hair cells or spiral ganglion neurons. 148 149 Args: 150 path: The project's export folder. 151 batch_size: The batch size for training. 152 patch_shape: The patch shape to use for training. 153 name: The subset, 'sgn' or 'ihc'. 154 split: The data split, 'train' or 'val'. 155 kwargs: Additional keyword arguments for `torch_em.default_segmentation_dataset` or for the PyTorch DataLoader. 156 157 Returns: 158 The DataLoader. 159 """ 160 ds_kwargs, loader_kwargs = util.split_kwargs(torch_em.default_segmentation_dataset, **kwargs) 161 dataset = get_cochleanet_dataset(path, patch_shape, name, split, **ds_kwargs) 162 return torch_em.get_data_loader(dataset=dataset, batch_size=batch_size, **loader_kwargs)
Get the CochleaNet dataloader for 3d instance segmentation of inner hair cells or spiral ganglion neurons.
Arguments:
- path: The project's export folder.
- batch_size: The batch size for training.
- patch_shape: The patch shape to use for training.
- name: The subset, 'sgn' or 'ihc'.
- split: The data split, 'train' or 'val'.
- kwargs: Additional keyword arguments for
torch_em.default_segmentation_datasetor for the PyTorch DataLoader.
Returns:
The DataLoader.