File size: 10,916 Bytes
e4b9a7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | # Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A collection of dictionary-based wrappers around the "vanilla" transforms for IO functions
defined in :py:class:`monai.transforms.io.array`.
Class names are ended with 'd' to denote dictionary-based transforms.
"""
from typing import Callable, Optional
import numpy as np
from monai.config import KeysCollection
from monai.data.image_reader import ImageReader
from monai.transforms.compose import MapTransform
from monai.transforms.io.array import LoadImage, LoadNifti, LoadNumpy, LoadPNG
class LoadImaged(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.LoadImage`,
must load image and metadata together. If loading a list of files in one key,
stack them together and add a new dimension as the first dimension, and use the
meta data of the first image to represent the stacked result. Note that the affine
transform of all the stacked images should be same. The output metadata field will
be created as ``key_{meta_key_postfix}``.
"""
def __init__(
self,
keys: KeysCollection,
reader: Optional[ImageReader] = None,
dtype: Optional[np.dtype] = np.float32,
meta_key_postfix: str = "meta_dict",
overwriting: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dtype: if not None convert the loaded image data to this data type.
meta_key_postfix: use `key_{postfix}` to store the metadata of the nifti image,
default is `meta_dict`. The meta data is a dictionary object.
For example, load nifti file for `image`, store the metadata into `image_meta_dict`.
overwriting: whether allow to overwrite existing meta data of same key.
default is False, which will raise exception if encountering existing key.
"""
super().__init__(keys)
self._loader = LoadImage(reader, False, dtype)
if not isinstance(meta_key_postfix, str):
raise TypeError(f"meta_key_postfix must be a str but is {type(meta_key_postfix).__name__}.")
self.meta_key_postfix = meta_key_postfix
self.overwriting = overwriting
def register(self, reader: ImageReader):
self._loader.register(reader)
def __call__(self, data, reader: Optional[ImageReader] = None):
"""
Raises:
KeyError: When not ``self.overwriting`` and key already exists in ``data``.
"""
d = dict(data)
for key in self.keys:
data = self._loader(d[key], reader)
assert isinstance(data, (tuple, list)), "loader must return a tuple or list."
d[key] = data[0]
assert isinstance(data[1], dict), "metadata must be a dict."
key_to_add = f"{key}_{self.meta_key_postfix}"
if key_to_add in d and not self.overwriting:
raise KeyError(f"Meta data with key {key_to_add} already exists and overwriting=False.")
d[key_to_add] = data[1]
return d
class LoadDatad(MapTransform):
"""
Base class for dictionary-based wrapper of IO loader transforms.
It must load image and metadata together. If loading a list of files in one key,
stack them together and add a new dimension as the first dimension, and use the
meta data of the first image to represent the stacked result. Note that the affine
transform of all the stacked images should be same. The output metadata field will
be created as ``key_{meta_key_postfix}``.
"""
def __init__(
self,
keys: KeysCollection,
loader: Callable,
meta_key_postfix: str = "meta_dict",
overwriting: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
loader: callable function to load data from expected source.
typically, it's array level transform, for example: `LoadNifti`,
`LoadPNG` and `LoadNumpy`, etc.
meta_key_postfix: use `key_{postfix}` to store the metadata of the loaded data,
default is `meta_dict`. The meta data is a dictionary object.
For example, load Nifti file for `image`, store the metadata into `image_meta_dict`.
overwriting: whether allow to overwrite existing meta data of same key.
default is False, which will raise exception if encountering existing key.
Raises:
TypeError: When ``loader`` is not ``callable``.
TypeError: When ``meta_key_postfix`` is not a ``str``.
"""
super().__init__(keys)
if not callable(loader):
raise TypeError(f"loader must be callable but is {type(loader).__name__}.")
self.loader = loader
if not isinstance(meta_key_postfix, str):
raise TypeError(f"meta_key_postfix must be a str but is {type(meta_key_postfix).__name__}.")
self.meta_key_postfix = meta_key_postfix
self.overwriting = overwriting
def __call__(self, data):
"""
Raises:
KeyError: When not ``self.overwriting`` and key already exists in ``data``.
"""
d = dict(data)
for key in self.keys:
data = self.loader(d[key])
assert isinstance(data, (tuple, list)), "loader must return a tuple or list."
d[key] = data[0]
assert isinstance(data[1], dict), "metadata must be a dict."
key_to_add = f"{key}_{self.meta_key_postfix}"
if key_to_add in d and not self.overwriting:
raise KeyError(f"Meta data with key {key_to_add} already exists and overwriting=False.")
d[key_to_add] = data[1]
return d
class LoadNiftid(LoadDatad):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.LoadNifti`,
must load image and metadata together. If loading a list of files in one key,
stack them together and add a new dimension as the first dimension, and use the
meta data of the first image to represent the stacked result. Note that the affine
transform of all the stacked images should be same. The output metadata field will
be created as ``key_{meta_key_postfix}``.
"""
def __init__(
self,
keys: KeysCollection,
as_closest_canonical: bool = False,
dtype: Optional[np.dtype] = np.float32,
meta_key_postfix: str = "meta_dict",
overwriting: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
as_closest_canonical: if True, load the image as closest to canonical axis format.
dtype: if not None convert the loaded image data to this data type.
meta_key_postfix: use `key_{postfix}` to store the metadata of the nifti image,
default is `meta_dict`. The meta data is a dictionary object.
For example, load nifti file for `image`, store the metadata into `image_meta_dict`.
overwriting: whether allow to overwrite existing meta data of same key.
default is False, which will raise exception if encountering existing key.
"""
loader = LoadNifti(as_closest_canonical, False, dtype)
super().__init__(keys, loader, meta_key_postfix, overwriting)
class LoadPNGd(LoadDatad):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.LoadPNG`.
"""
def __init__(
self,
keys: KeysCollection,
dtype: Optional[np.dtype] = np.float32,
meta_key_postfix: str = "meta_dict",
overwriting: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dtype: if not None convert the loaded image data to this data type.
meta_key_postfix: use `key_{postfix}` to store the metadata of the PNG image,
default is `meta_dict`. The meta data is a dictionary object.
For example, load PNG file for `image`, store the metadata into `image_meta_dict`.
overwriting: whether allow to overwrite existing meta data of same key.
default is False, which will raise exception if encountering existing key.
"""
loader = LoadPNG(False, dtype)
super().__init__(keys, loader, meta_key_postfix, overwriting)
class LoadNumpyd(LoadDatad):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.LoadNumpy`.
"""
def __init__(
self,
keys: KeysCollection,
dtype: Optional[np.dtype] = np.float32,
npz_keys: Optional[KeysCollection] = None,
meta_key_postfix: str = "meta_dict",
overwriting: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
dtype: if not None convert the loaded data to this data type.
npz_keys: if loading npz file, only load the specified keys, if None, load all the items.
stack the loaded items together to construct a new first dimension.
meta_key_postfix: use `key_{postfix}` to store the metadata of the Numpy data,
default is `meta_dict`. The meta data is a dictionary object.
For example, load Numpy file for `mask`, store the metadata into `mask_meta_dict`.
overwriting: whether allow to overwrite existing meta data of same key.
default is False, which will raise exception if encountering existing key.
"""
loader = LoadNumpy(data_only=False, dtype=dtype, npz_keys=npz_keys)
super().__init__(keys, loader, meta_key_postfix, overwriting)
LoadImageD = LoadImageDict = LoadImaged
LoadNiftiD = LoadNiftiDict = LoadNiftid
LoadPNGD = LoadPNGDict = LoadPNGd
LoadNumpyD = LoadNumpyDict = LoadNumpyd
|