tiamat-python 0.1.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ from functools import cached_property
2
+ from typing import Any
3
+
4
+ import numpy as np
5
+
6
+ from tiamat.cache import instance_cache
7
+ from tiamat.io import ImageAccessor
8
+
9
+ from .protocol import ImageReader
10
+
11
+
12
+ class NiftiReader(ImageReader):
13
+ """
14
+ Reader for NIfTI image files (.nii / .nii.gz).
15
+
16
+ Uses nibabel to load image data and metadata.
17
+ """
18
+
19
+ def __init__(self, fname: str) -> None:
20
+ """
21
+ Initialize the NiftiReader.
22
+
23
+ Args:
24
+ fname (str): Path to the NIfTI file.
25
+ """
26
+ self.fname = fname
27
+
28
+ @cached_property
29
+ def handle(self) -> Any:
30
+ """
31
+ Initialize the NiftiReader.
32
+
33
+ Args:
34
+ fname (str): Path to the NIfTI file.
35
+ """
36
+ import nibabel as nib
37
+
38
+ return nib.load(self.fname)
39
+
40
+ def read_image(self, accessor: ImageAccessor) -> np.ndarray:
41
+ """
42
+ Read image data from the NIfTI file.
43
+
44
+ Args:
45
+ accessor (ImageAccessor): Provides metadata and access specifications.
46
+
47
+ Returns:
48
+ Any ImageResult with image data and metadata.
49
+ """
50
+ from .processing import access_and_rescale_image
51
+
52
+ data = self.handle.get_fdata()
53
+
54
+ image = access_and_rescale_image(image=data, metadata=self.read_metadata(), accessor=accessor)
55
+
56
+ return image
57
+
58
+ @instance_cache
59
+ def read_metadata(self) -> Any:
60
+ """
61
+ Read metadata from the NIfTI file.
62
+
63
+ Returns:
64
+ Any: ImageMetadata object containing metadata such as dtype, shape, and file path.
65
+ """
66
+ from tiamat import metadata as md
67
+
68
+ dtype = self.handle.get_data_dtype()
69
+ value_range = md.get_dtype_limits(dtype)
70
+
71
+ return md.ImageMetadata(
72
+ image_type=md.IMAGE_TYPE_IMAGE,
73
+ shape=self.handle.shape,
74
+ value_range=value_range,
75
+ dtype=dtype,
76
+ file_path=self.fname,
77
+ )
78
+
79
+ @classmethod
80
+ def check_file(cls, fname: str) -> bool:
81
+ """
82
+ For parity with MemoryReader: declare support for array-like inputs.
83
+
84
+ Args:
85
+ fname: Object to test.
86
+
87
+ Returns:
88
+ True iff `fname` exposes a numpy-compatible array protocol.
89
+
90
+ Note:
91
+ In normal file-based selection this will evaluate to False (strings lack __array__),
92
+ so ConstantReader won't be selected by accident in the file reader factory.
93
+ """
94
+ return fname.endswith(".nii") or fname.endswith(".nii.gz")
@@ -0,0 +1,98 @@
1
+ """
2
+ Reader that delegates image reading to a processing pipeline.
3
+ """
4
+
5
+ from collections.abc import Callable
6
+ from functools import partial
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+ from tiamat.cache import instance_cache
12
+
13
+ from ..io import ImageAccessor
14
+ from ..metadata import ImageMetadata
15
+ from .protocol import ImageReader
16
+
17
+
18
+ class PipelineReader(ImageReader):
19
+ """
20
+ A reader that delegates image reading and metadata access to a given processing pipeline.
21
+
22
+ This allows pipelines to be used as drop-in replacements for standard image readers.
23
+ """
24
+
25
+ def __init__(self, fname: str, pipeline: Callable, **reader_kwargs: Any):
26
+ """
27
+ Initializes a PipelineReader.
28
+
29
+ Args:
30
+ fname (str): Filename of the image.
31
+ pipeline (Callable): A callable representing the image pipeline.
32
+ **reader_kwargs (Any): Additional keyword arguments passed to the pipeline.
33
+ """
34
+ self.fname = fname
35
+ self.pipeline = pipeline
36
+ self.reader_kwargs = reader_kwargs
37
+
38
+ def read_image(self, accessor: ImageAccessor) -> np.ndarray:
39
+ """
40
+ Reads and processes the image using the pipeline.
41
+
42
+ Args:
43
+ accessor (ImageAccessor): Accessor specifying what to read.
44
+
45
+ Returns:
46
+ np.ndarray: The image array after applying the pipeline.
47
+ """
48
+ return self.pipeline(file_name=self.fname, accessor=accessor, **self.reader_kwargs).image
49
+
50
+ @instance_cache
51
+ def read_metadata(self) -> ImageMetadata:
52
+ """
53
+ Reads metadata using the pipeline.
54
+
55
+ Returns:
56
+ ImageMetadata: Metadata read from the pipeline.
57
+ """
58
+ return self.pipeline.read_metadata(file_name=self.fname, **self.reader_kwargs)
59
+
60
+ @classmethod
61
+ def check_file(cls, fname: str) -> bool:
62
+ """
63
+ This implementation always returns False (not implemented).
64
+
65
+ Args:
66
+ fname (str): Path to the file.
67
+
68
+ Returns:
69
+ bool: Always False.
70
+ """
71
+ return False
72
+
73
+ @classmethod
74
+ def from_json(
75
+ cls, args: dict[str, Any], reader_post_creation_hook: Callable | None = None
76
+ ) -> Callable[..., "PipelineReader"]:
77
+ """
78
+ Creates a PipelineReader from a JSON-like configuration.
79
+
80
+ Args:
81
+ args (Dict[str, Any]): Configuration dictionary with 'pipeline' key.
82
+ reader_post_creation_hook (Callable, optional): Optional hook to modify the pipeline.
83
+
84
+ Returns:
85
+ Callable[..., PipelineReader]: A constructor for PipelineReader (partial with fixed pipeline).
86
+
87
+ Note:
88
+ Currently does not support reader_kwargs (TODO).
89
+ """
90
+ from tiamat.serialization import load_pipeline_from_config
91
+
92
+ pipeline = load_pipeline_from_config(args["pipeline"], reader_post_creation_hook=reader_post_creation_hook)
93
+
94
+ # TODO: Handle kwargs
95
+ return partial(
96
+ cls,
97
+ pipeline=pipeline,
98
+ )
@@ -0,0 +1,509 @@
1
+ """
2
+ Processing required by readers.
3
+ """
4
+
5
+ # Try to import OpenCV and use scikit-image as a fallback
6
+ from __future__ import annotations
7
+
8
+ import warnings
9
+ from collections.abc import Sequence
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+
14
+ from tiamat.constants import (
15
+ INTERPOLATION_TYPE_CUBIC,
16
+ INTERPOLATION_TYPE_NEAREST,
17
+ OPENCV_INTERPOLATION_CODES,
18
+ )
19
+ from tiamat.io import ImageAccessor
20
+ from tiamat.metadata.metadata import ImageMetadata
21
+
22
+
23
+ def _expand_to_dimension(value: int | float | Sequence[int | float], image_shape: Sequence[int]) -> list[float]:
24
+ """
25
+ Expand scalar or sequence to match image dimensions.
26
+
27
+ Args:
28
+ value: Scalar or sequence to expand.
29
+ image_shape: Target image shape.
30
+
31
+ Returns:
32
+ Expanded list of floats.
33
+ """
34
+ if not isinstance(value, (list, tuple, np.ndarray)):
35
+ return [value for _ in image_shape]
36
+ elif len(value) == 1:
37
+ return [value[0]] * len(image_shape)
38
+ return value
39
+
40
+
41
+ def expand_to_length(value: Any, length: int) -> list[Any]:
42
+ """
43
+ Expand scalar or sequence to a list of given length.
44
+
45
+ Args:
46
+ value: Input scalar or sequence.
47
+ length: Desired output length.
48
+
49
+ Returns:
50
+ List of length `length`.
51
+ """
52
+ if not isinstance(value, (list, tuple, np.ndarray)):
53
+ return [value] * length
54
+ elif len(value) == 1:
55
+ return [value[0]] * length
56
+ return value
57
+
58
+
59
+ def rescale_shape(shape: Sequence[int], scale: float | Sequence[float]) -> np.ndarray:
60
+ """
61
+ Compute the target shape of an array when scaled.
62
+
63
+ Args:
64
+ shape: Original shape of the array.
65
+ scale: Scaling factor (scalar or sequence) for each dimension.
66
+
67
+ Returns:
68
+ Array of integers representing the scaled shape.
69
+ """
70
+
71
+ # Assume scale is scalar or (x_scale, y_scale)
72
+ scale = _expand_to_dimension(scale, shape)[: len(shape)][::-1]
73
+ assert all(s > 0 for s in scale), f"Scale must be greater than zero, got {scale}."
74
+
75
+ target_shape = np.array([dim * s for dim, s in zip(shape, scale)], dtype=float)
76
+ target_shape = np.maximum(np.round(target_shape).astype(int), 1)
77
+
78
+ return target_shape
79
+
80
+
81
+ def _rescale(
82
+ image: np.ndarray,
83
+ scale: float | tuple[float, ...],
84
+ interpolation: str = INTERPOLATION_TYPE_CUBIC,
85
+ anti_aliasing: bool = False,
86
+ ) -> np.ndarray:
87
+ """
88
+ Rescale a 2D or 3D image according to specified scale factors.
89
+
90
+ Args:
91
+ image: Input image as a numpy array.
92
+ scale: Scaling factor(s) for each spatial dimension.
93
+ interpolation: Interpolation method to use.
94
+ anti_aliasing: Apply Gaussian smoothing before downscaling if True.
95
+
96
+ Returns:
97
+ Rescaled image as a numpy array.
98
+ """
99
+
100
+ # check valid size of image
101
+ if min(image.shape) == 0:
102
+ warnings.warn("Not possible to resize image of shape {}".format(image.shape))
103
+ return image
104
+
105
+ # For simplicity assume spatial information in first ndims dimensions for now
106
+ ndims = len(scale)
107
+ assert ndims == 2 or ndims == 3
108
+
109
+ target_shape = rescale_shape(
110
+ image.shape[:ndims],
111
+ scale,
112
+ )
113
+
114
+ if np.allclose(target_shape, image.shape[:ndims]):
115
+ # Nothing to do
116
+ return image
117
+
118
+ if ndims == 2:
119
+ return resize_2d(
120
+ img=image,
121
+ shape=target_shape,
122
+ interpolation=interpolation,
123
+ anti_aliasing=anti_aliasing,
124
+ )
125
+ if ndims == 3:
126
+ return resize_3d(
127
+ img=image,
128
+ shape=target_shape,
129
+ interpolation=interpolation,
130
+ anti_aliasing=anti_aliasing,
131
+ )
132
+
133
+
134
+ def resize_2d(
135
+ img: np.ndarray, shape: Sequence[int], interpolation: str = INTERPOLATION_TYPE_CUBIC, anti_aliasing: bool = False
136
+ ) -> np.ndarray:
137
+ """
138
+ Resize a 2D image to the specified shape using the given interpolation.
139
+
140
+ Args:
141
+ img: Image to resize (height x width or height x width x channels).
142
+ shape: Target shape (height, width) or (height, width, channels).
143
+ interpolation: Interpolation strategy to use.
144
+ anti_aliasing: If True, apply Gaussian smoothing before downsizing.
145
+
146
+ Returns:
147
+ Resized 2D image as a numpy array.
148
+ """
149
+ import cv2
150
+
151
+ # Scaling factors per dimension
152
+ factors = np.divide(img.shape[:2], shape)
153
+
154
+ # take care of rgb images and 2dim shapes
155
+ if len(img.shape) == 3 and len(shape) == 2:
156
+ shape = (shape[0], shape[1], img.shape[2])
157
+
158
+ if anti_aliasing and np.any(factors > 1):
159
+ sigma = np.maximum(0, (factors - 1) / 2)
160
+ ksize = np.ceil(4.0 * sigma, dtype=int, casting="unsafe")
161
+ ksize = ksize + (1 - ksize % 2)
162
+
163
+ arr = cv2.GaussianBlur(img, ksize[::-1], sigmaX=sigma[1], sigmaY=sigma[0])
164
+ else:
165
+ arr = img
166
+
167
+ res = cv2.resize(
168
+ src=arr,
169
+ dsize=(shape[1], shape[0]),
170
+ interpolation=OPENCV_INTERPOLATION_CODES[interpolation],
171
+ )
172
+
173
+ # Resize tends to loose dimensions with size one, so we need to add them back
174
+ if len(res.shape) < len(arr.shape) and arr.shape[-1] == 1:
175
+ res = res.reshape(*res.shape, 1)
176
+
177
+ return res.astype(img.dtype)
178
+
179
+
180
+ def resize_3d(
181
+ img: np.ndarray, shape: Sequence[int], interpolation: str = INTERPOLATION_TYPE_CUBIC, anti_aliasing: bool = False
182
+ ) -> np.ndarray:
183
+ """
184
+ Resize a 3D image stack to the specified shape using the given interpolation.
185
+
186
+ Args:
187
+ img: 3D image stack to resize.
188
+ shape: Target shape for the stack.
189
+ interpolation: Interpolation strategy to use.
190
+ anti_aliasing: Apply Gaussian smoothing before downsizing if True.
191
+
192
+ Returns:
193
+ Resized 3D image stack as a numpy array.
194
+
195
+ Raises:
196
+ NotImplementedError: Full 3D resizing not implemented if all dimensions need rescaling.
197
+ """
198
+
199
+ # Scaling factors per dimension
200
+ factors = np.divide(img.shape, shape)
201
+
202
+ # Rescale an image stack
203
+ # if at least one factor is one, use resize_2d with loop
204
+ if np.any(np.isclose(factors, 1.0)):
205
+ # pick first dimension with factor 1
206
+ idx = np.where(np.isclose(factors, 1.0))[0][0]
207
+
208
+ img_rescaled = np.empty(shape, dtype=img.dtype)
209
+ shape_2d = (*shape[:idx], *shape[idx + 1 :])
210
+
211
+ for i in range(img.shape[idx]):
212
+ slices = [slice(None)] * len(img.shape)
213
+ slices[idx] = i
214
+ img_rescaled[i] = resize_2d(
215
+ img=img[tuple(slices)],
216
+ shape=shape_2d,
217
+ interpolation=interpolation,
218
+ anti_aliasing=anti_aliasing,
219
+ )
220
+ return img_rescaled
221
+
222
+ raise NotImplementedError("Full 3D resizing not supported yet")
223
+
224
+
225
+ def prepare_coordinate(
226
+ coord: int | Sequence[int] | None, image_scale: float = 1.0, coordinate_scale: float = 1.0
227
+ ) -> tuple[int, int]:
228
+ """
229
+ Prepare coordinates for image access by applying scaling and flooring.
230
+
231
+ Args:
232
+ coord: Single coordinate, sequence, or None for full dimension.
233
+ image_scale: Scale factor of the image.
234
+ coordinate_scale: Scale factor of the coordinates.
235
+
236
+ Returns:
237
+ Tuple of (start, end) indices corresponding to the prepared coordinate.
238
+ """
239
+ import math
240
+
241
+ factor = image_scale / coordinate_scale
242
+
243
+ # Note: We round to the 10 first significant digits here very slightly whenever we multiply the factor,
244
+ # as minimal floating errors can mess the length up quite badly when applying math.ceil or math.floor
245
+ def round_sig(x, sig=10):
246
+ # we need a small eps to avoid infinity
247
+ eps = 1 / (10 ** (sig + 2))
248
+ return np.round(x, sig - int(np.floor(np.log10(abs(x + eps)))) - 1)
249
+
250
+ if hasattr(coord, "__iter__"):
251
+ # Assume the coordinate stores an half-open interval [start, stop)
252
+ assert len(coord) == 2, "prepare_coordinate accepts only coordinate intervals [start, stop] of length 2"
253
+
254
+ # Simply scale the start by the interval by the factor
255
+ start = math.floor(round_sig(coord[0] * factor, 10))
256
+ if coord[1] is None:
257
+ # If the second coordinate is None, use None
258
+ stop = None
259
+ else:
260
+ # Otherwise, estimate the length of the scaled interval
261
+ length = math.ceil(round_sig((coord[1] - coord[0]) * factor, 10))
262
+ # Compute the stop index by the length
263
+ stop = start + length
264
+
265
+ prepared_coord = (start, stop)
266
+ elif coord is None:
267
+ # All elements in the given dimension
268
+ prepared_coord = (0, None)
269
+ else:
270
+ # A single element in the given dimension
271
+ coord = math.floor(round_sig(coord * factor, 10))
272
+ prepared_coord = (coord, coord + 1)
273
+
274
+ return prepared_coord
275
+
276
+
277
+ def _prepare_coordinates(
278
+ image_scale=(1.0, 1.0), coordinate_scale=(1.0, 1.0), **coordinates
279
+ ) -> dict[str, tuple[int, int]]:
280
+ """
281
+ Prepare multiple coordinates for image access.
282
+
283
+ Args:
284
+ image_scale: Scale factors for each image dimension.
285
+ coordinate_scale: Scale factors for each coordinate dimension.
286
+ coordinates: Keyword arguments for coordinates (x, y, z, c, ...).
287
+
288
+ Returns:
289
+ Dictionary mapping coordinate names to (start, end) tuples.
290
+ """
291
+ prepared = {}
292
+ for i, (key, coord) in enumerate(coordinates.items()):
293
+ i_scale = image_scale[i] if i < len(image_scale) else 1.0
294
+ c_scale = coordinate_scale[i] if i < len(coordinate_scale) else 1.0
295
+ prepared[key] = prepare_coordinate(coord, i_scale, c_scale)
296
+
297
+ return prepared
298
+
299
+
300
+ def _zero_clip(values: Sequence[int | None]) -> list[int]:
301
+ """
302
+ Clip values to be zero or positive, preserving None values.
303
+
304
+ Args:
305
+ values: Sequence of values to clip.
306
+
307
+ Returns:
308
+ List of clipped values.
309
+ """
310
+ return [max(value, 0) if value is not None else None for value in values]
311
+
312
+
313
+ def access_image(
314
+ image: np.ndarray,
315
+ metadata: ImageMetadata,
316
+ accessor: ImageAccessor,
317
+ image_scale: float | tuple[float, ...],
318
+ ) -> np.ndarray:
319
+ """
320
+ Extract a subregion of an image, with padding if needed.
321
+
322
+ Args:
323
+ image: Input array (row-major).
324
+ metadata: Metadata describing dimensions.
325
+ accessor: Requested coordinates.
326
+ image_scale: Scaling of each image dimension.
327
+
328
+ Returns:
329
+ The requested subregion as an array (with optional padding).
330
+ """
331
+
332
+ coordinate_scale = _expand_to_dimension(accessor.coordinate_scale, metadata.spatial_shape)
333
+ image_scale = _expand_to_dimension(image_scale, metadata.spatial_shape)
334
+
335
+ access_channels = {
336
+ "x": accessor.x,
337
+ "y": accessor.y,
338
+ "z": accessor.z,
339
+ }
340
+ if isinstance(accessor.c, dict):
341
+ access_channels.update(accessor.c)
342
+ else:
343
+ access_channels["c"] = accessor.c
344
+
345
+ access_channels = _prepare_coordinates(
346
+ image_scale=image_scale,
347
+ coordinate_scale=coordinate_scale,
348
+ **access_channels,
349
+ )
350
+
351
+ def _pad_left(coordinate):
352
+ if coordinate is None:
353
+ return 0
354
+ return max(-int(coordinate), 0)
355
+
356
+ def _pad_right(coordinate, coordinate_max):
357
+ if coordinate is None:
358
+ return 0
359
+ return max(int(coordinate) - int(coordinate_max), 0)
360
+
361
+ def _pad(coordinate, coordinate_max):
362
+ return max(_pad_left(coordinate), _pad_right(coordinate, coordinate_max))
363
+
364
+ def _clip(coordinate, min_coordinate, max_coordinate):
365
+ if coordinate is None:
366
+ return coordinate
367
+ return min(max(int(coordinate), int(min_coordinate)), int(max_coordinate))
368
+
369
+ # Separate image and channel dimensions
370
+ ch_dims = list(metadata.channel_dimensions)
371
+ ch_dims = ch_dims if ch_dims is not None else []
372
+
373
+ image_dims = list(metadata.spatial_dimensions)
374
+ n_image_dims = len(image_dims)
375
+
376
+ assert n_image_dims == 2 or n_image_dims == 3, "Only 2D or 3D images supported"
377
+
378
+ # Loop over all dimensions to create request
379
+ request_slices = [slice(None)] * len(image.shape)
380
+ access_shape = np.ones((len(image.shape)), dtype=np.int64)
381
+ for dim, dimension_name in enumerate(metadata.dimensions):
382
+ max_c = image.shape[dim]
383
+ coord = access_channels.get(dimension_name, (0, None))
384
+ c_from, c_to = coord
385
+
386
+ request_slices[dim] = slice(_clip(c_from, 0, max_c), _clip(c_to, 0, max_c))
387
+ access_shape[dim] = c_to - c_from if c_to is not None else image.shape[dim]
388
+
389
+ # Loop over image dimensions to determine padding
390
+ padding = [(0, 0)] * len(image.shape)
391
+ for dim in image_dims:
392
+ coord = access_channels.get(metadata.dimensions[dim], (0, None))
393
+ max_coord = image.shape[dim]
394
+ coord_from, coord_to = coord
395
+
396
+ if accessor.fill_value is not None and ((coord_to is not None and coord_to < 0) or (coord_from >= max_coord)):
397
+ # The image will be empty, just return an empty array
398
+ return np.full(access_shape, fill_value=accessor.fill_value, dtype=image.dtype)
399
+
400
+ padding[dim] = (_pad(coord_from, max_coord), _pad(coord_to, max_coord))
401
+ request_slices[dim] = slice(_clip(coord_from, 0, max_coord), _clip(coord_to, 0, max_coord))
402
+ access_shape[dim] = coord_to - coord_from if coord_to is not None else image.shape[dim]
403
+
404
+ # Read requested data
405
+ result = image[tuple(request_slices)]
406
+
407
+ # Only do padding if fill_value is set and necessary
408
+ if accessor.fill_value is not None and any(any(p > 0 for p in pad) for pad in padding):
409
+ result = np.pad(result, padding, constant_values=accessor.fill_value)
410
+
411
+ return result
412
+
413
+
414
+ def access_and_rescale_image(
415
+ image: np.ndarray,
416
+ metadata: ImageMetadata,
417
+ accessor: ImageAccessor,
418
+ image_scale: float | tuple[float, ...] = 1.0,
419
+ ):
420
+ """
421
+ Access an image region and rescale it according to accessor.
422
+
423
+ Args:
424
+ image: Input array.
425
+ metadata: Metadata describing dimensions.
426
+ accessor: Requested access details.
427
+ image_scale: Scaling of each image dimension.
428
+
429
+ Returns:
430
+ The requested and rescaled image.
431
+ """
432
+ image_scale = _expand_to_dimension(image_scale, metadata.spatial_dimensions)
433
+ image = access_image(image=image, metadata=metadata, accessor=accessor, image_scale=image_scale)
434
+
435
+ scale = _expand_to_dimension(accessor.scale, metadata.spatial_dimensions)
436
+ assert len(scale) == len(image_scale), f"Scale and image scale do not match: {len(scale)} vs. {len(image_scale)}"
437
+
438
+ interpolation = get_interpolation_for_accessor(accessor, metadata)
439
+ target_scale = tuple(s / s_image for s, s_image in zip(scale, image_scale))
440
+ image = _rescale(
441
+ image,
442
+ scale=target_scale,
443
+ interpolation=interpolation,
444
+ anti_aliasing=accessor.anti_aliasing,
445
+ )
446
+
447
+ return image
448
+
449
+
450
+ def get_value_range_from_dtype(dtype):
451
+ if np.issubdtype(dtype, np.integer):
452
+ info = np.iinfo(dtype)
453
+ value_range = (info.min, info.max)
454
+ elif np.issubdtype(dtype, np.floating):
455
+ info = np.finfo(dtype)
456
+ value_range = (info.min, info.max)
457
+ else:
458
+ raise ValueError(f"Cannot determine value range for unsupported dtype: {dtype}")
459
+
460
+ return value_range
461
+
462
+
463
+ def get_interpolation_for_accessor(accessor: ImageAccessor, metadata: ImageMetadata) -> int:
464
+ """
465
+ Determine interpolation type from accessor or metadata.
466
+
467
+ Args:
468
+ accessor: Image accessor with optional interpolation setting.
469
+ metadata: Metadata including image type.
470
+
471
+ Returns:
472
+ Interpolation identifier string.
473
+ """
474
+ if accessor.interpolation:
475
+ interpolation = accessor.interpolation
476
+ elif metadata and metadata.image_type:
477
+ interpolation = get_interpolation_for_image_type(image_type=metadata.image_type)
478
+ else:
479
+ raise RuntimeError(
480
+ "Could not _rescale image, as neither 'interpolation' nor 'metadata.image_type' was provided."
481
+ )
482
+ return interpolation
483
+
484
+
485
+ def get_interpolation_for_image_type(image_type: str) -> str:
486
+ """
487
+ Get a default interpolation method for a given image type.
488
+
489
+ Args:
490
+ image_type: Type of the image (e.g., IMAGE, SEGMENTATION).
491
+
492
+ Returns:
493
+ Interpolation identifier string.
494
+
495
+ Raises:
496
+ AssertionError: If the image type is unknown.
497
+ """
498
+ from .. import metadata as md
499
+
500
+ image_type_to_interpolation = {
501
+ md.IMAGE_TYPE_IMAGE: INTERPOLATION_TYPE_CUBIC,
502
+ md.IMAGE_TYPE_SEGMENTATION: INTERPOLATION_TYPE_NEAREST,
503
+ }
504
+
505
+ assert (
506
+ image_type in image_type_to_interpolation
507
+ ), f"Encountered unknown image type while determining interpolation: {image_type}"
508
+
509
+ return image_type_to_interpolation[image_type]