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.
- tiamat/__init__.py +5 -0
- tiamat/array.py +221 -0
- tiamat/cache.py +138 -0
- tiamat/cli.py +15 -0
- tiamat/constants.py +34 -0
- tiamat/errors.py +27 -0
- tiamat/io.py +85 -0
- tiamat/metadata/__init__.py +2 -0
- tiamat/metadata/dimensions.py +18 -0
- tiamat/metadata/metadata.py +118 -0
- tiamat/pipeline.py +144 -0
- tiamat/readers/__init__.py +31 -0
- tiamat/readers/factory.py +106 -0
- tiamat/readers/generic.py +150 -0
- tiamat/readers/memory.py +223 -0
- tiamat/readers/nifti.py +94 -0
- tiamat/readers/pipeline.py +98 -0
- tiamat/readers/processing.py +509 -0
- tiamat/readers/protocol.py +59 -0
- tiamat/readers/stack.py +851 -0
- tiamat/readers/zarr.py +353 -0
- tiamat/serialization.py +153 -0
- tiamat/transformers/__init__.py +0 -0
- tiamat/transformers/access.py +216 -0
- tiamat/transformers/affine.py +341 -0
- tiamat/transformers/axes.py +418 -0
- tiamat/transformers/color.py +304 -0
- tiamat/transformers/coordinates.py +54 -0
- tiamat/transformers/dfield.py +432 -0
- tiamat/transformers/metadata.py +88 -0
- tiamat/transformers/normalization.py +77 -0
- tiamat/transformers/protocol.py +84 -0
- tiamat/transformers/view.py +197 -0
- tiamat_python-0.1.8.dist-info/METADATA +382 -0
- tiamat_python-0.1.8.dist-info/RECORD +39 -0
- tiamat_python-0.1.8.dist-info/WHEEL +5 -0
- tiamat_python-0.1.8.dist-info/entry_points.txt +2 -0
- tiamat_python-0.1.8.dist-info/licenses/LICENSE +202 -0
- tiamat_python-0.1.8.dist-info/top_level.txt +1 -0
tiamat/__init__.py
ADDED
tiamat/array.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from functools import cached_property
|
|
5
|
+
|
|
6
|
+
from .io import ImageAccessor
|
|
7
|
+
from .metadata import ImageMetadata, dimensions
|
|
8
|
+
from .pipeline import Pipeline
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def slice_to_interval(
|
|
12
|
+
array_slice: int | slice | tuple[int | slice | Ellipsis, ...] | None,
|
|
13
|
+
shape: tuple[int, ...],
|
|
14
|
+
) -> tuple[list[tuple[int, int]], list[int]]:
|
|
15
|
+
"""
|
|
16
|
+
Convert a given slice or index into intervals usable for image access.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
array_slice: Slice, integer, ellipsis or tuple of them. Can also be None to expand to full slice.
|
|
20
|
+
shape: The shape of the array to index into.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
A tuple containing:
|
|
24
|
+
- A list of (start, stop) intervals for each dimension.
|
|
25
|
+
- A list of dimensions to be squeezed after slicing.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
IndexError: If the number of slice dimensions exceeds the array's dimensions.
|
|
29
|
+
"""
|
|
30
|
+
if array_slice is None:
|
|
31
|
+
# expand None slice
|
|
32
|
+
array_slice = tuple([slice(None) for _ in range(len(shape))])
|
|
33
|
+
elif not isinstance(array_slice, tuple):
|
|
34
|
+
# expand single integer slice
|
|
35
|
+
array_slice = (array_slice,)
|
|
36
|
+
|
|
37
|
+
if len(array_slice) > len(shape):
|
|
38
|
+
raise IndexError(
|
|
39
|
+
f"Encountered invalid slice with {len(array_slice)} dimensions, but array has dimension {len(shape)}"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# expand ellipsis (array[...])
|
|
43
|
+
array_slice = list(array_slice)
|
|
44
|
+
for i, sl in enumerate(array_slice):
|
|
45
|
+
if sl is Ellipsis:
|
|
46
|
+
diff = len(shape) - len(array_slice) + 1
|
|
47
|
+
array_slice.remove(sl)
|
|
48
|
+
for _ in range(diff):
|
|
49
|
+
array_slice.insert(i, slice(None))
|
|
50
|
+
break
|
|
51
|
+
|
|
52
|
+
# handle special indices
|
|
53
|
+
array_intervals = []
|
|
54
|
+
squeeze_dims = []
|
|
55
|
+
for i, sl in enumerate(array_slice):
|
|
56
|
+
if isinstance(sl, int):
|
|
57
|
+
if sl < 0:
|
|
58
|
+
sl = slice(shape[i] + sl, shape[i] + sl + 1)
|
|
59
|
+
else:
|
|
60
|
+
sl = slice(sl, sl + 1)
|
|
61
|
+
squeeze_dims.append(i)
|
|
62
|
+
start, stop = sl.start, sl.stop
|
|
63
|
+
if not start:
|
|
64
|
+
start = 0
|
|
65
|
+
if not stop:
|
|
66
|
+
stop = shape[i]
|
|
67
|
+
if start and start < 0:
|
|
68
|
+
start = shape[i] + start
|
|
69
|
+
if stop and stop < 0:
|
|
70
|
+
stop = shape[i] + stop
|
|
71
|
+
array_intervals.append((start, stop))
|
|
72
|
+
|
|
73
|
+
return array_intervals, squeeze_dims
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Array(object):
|
|
77
|
+
"""
|
|
78
|
+
Array interface for any tiamat pipeline, providing compatibility with code that uses numpy-style arrays.
|
|
79
|
+
By creating together, we bind together:
|
|
80
|
+
1. a pipeline
|
|
81
|
+
2. A file
|
|
82
|
+
3. A scale
|
|
83
|
+
|
|
84
|
+
Things to keep in mind:
|
|
85
|
+
- When accessing an array, all operations (e.g., slice, shape) opereate at the given scale.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
file_name,
|
|
91
|
+
pipeline: Pipeline,
|
|
92
|
+
scale: float | int | Iterable[float | int],
|
|
93
|
+
reader_kwargs: dict | None = None,
|
|
94
|
+
shape_round_mode: str = "round",
|
|
95
|
+
) -> None:
|
|
96
|
+
"""
|
|
97
|
+
Initialize an Array instance.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
file_name: Path to the image file.
|
|
101
|
+
pipeline: Pipeline used to read/process the image.
|
|
102
|
+
scale: Scale factor(s) to apply to the image.
|
|
103
|
+
reader_kwargs: Additional kwargs to pass to the pipeline when reading.
|
|
104
|
+
shape_round_mode: Determines how shape values are rounded.
|
|
105
|
+
Valid options: "round", "ceil", "floor".
|
|
106
|
+
"""
|
|
107
|
+
self.file_name = file_name
|
|
108
|
+
self.pipeline = pipeline
|
|
109
|
+
self.scale = scale
|
|
110
|
+
self.reader_kwargs = reader_kwargs or {}
|
|
111
|
+
self.shape_round_mode = shape_round_mode
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def create_arrays_for_scales(
|
|
115
|
+
cls,
|
|
116
|
+
file_name: str,
|
|
117
|
+
pipeline: Pipeline,
|
|
118
|
+
reader_kwargs: dict | None = None,
|
|
119
|
+
) -> tuple:
|
|
120
|
+
"""
|
|
121
|
+
Factory method to create `Array` instances for all scales of an image.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
file_name: Path to the image file.
|
|
125
|
+
pipeline: Pipeline used to read/process the image.
|
|
126
|
+
reader_kwargs: Additional kwargs for the pipeline.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
Tuple of Array instances for each available scale.
|
|
130
|
+
"""
|
|
131
|
+
reader_kwargs = reader_kwargs or {}
|
|
132
|
+
metadata = pipeline.read_metadata(file_name=file_name, **reader_kwargs)
|
|
133
|
+
scales = metadata.scales or [
|
|
134
|
+
1.0,
|
|
135
|
+
]
|
|
136
|
+
if not isinstance(scales, Iterable):
|
|
137
|
+
scales = [
|
|
138
|
+
scales,
|
|
139
|
+
]
|
|
140
|
+
return tuple(cls(file_name=file_name, pipeline=pipeline, scale=scale, **reader_kwargs) for scale in scales)
|
|
141
|
+
|
|
142
|
+
@cached_property
|
|
143
|
+
def metadata(self) -> ImageMetadata:
|
|
144
|
+
"""Read and cache image metadata."""
|
|
145
|
+
return self.pipeline.read_metadata(file_name=self.file_name, **self.reader_kwargs)
|
|
146
|
+
|
|
147
|
+
@cached_property
|
|
148
|
+
def shape(self) -> tuple[int, ...]:
|
|
149
|
+
"""Shape of the image."""
|
|
150
|
+
import numpy as np
|
|
151
|
+
|
|
152
|
+
shape_round_functions = {
|
|
153
|
+
"round": np.round,
|
|
154
|
+
"ceil": np.ceil,
|
|
155
|
+
"floor": np.floor,
|
|
156
|
+
}
|
|
157
|
+
shape_fn = shape_round_functions.get(self.shape_round_mode)
|
|
158
|
+
if shape_fn is None:
|
|
159
|
+
valid = ",".join(list(shape_round_functions.keys()))
|
|
160
|
+
raise RuntimeError(f"Invalid shape_round_mode {self.shape_round_mode}. Valid: {valid}")
|
|
161
|
+
|
|
162
|
+
return tuple(shape_fn(np.array(self.metadata.shape) * self.scale).astype(int).tolist())
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def ndim(self) -> int:
|
|
166
|
+
"""Number of dimensions."""
|
|
167
|
+
return len(self.shape)
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def size(self) -> int:
|
|
171
|
+
"""Total number of elements in the array."""
|
|
172
|
+
import math
|
|
173
|
+
|
|
174
|
+
return math.prod(self.shape)
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def dtype(self) -> str:
|
|
178
|
+
""" "Dtype of the image."""
|
|
179
|
+
return self.metadata.dtype
|
|
180
|
+
|
|
181
|
+
def __getitem__(self, array_slice: slice | tuple[slice] | None):
|
|
182
|
+
"""
|
|
183
|
+
Retrieve image data using numpy-like slicing.
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
array_slice: Slice object(s), integer index, ellipsis, or None.
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
The image data as returned by the pipeline.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
array_intervals, squeeze_dims = slice_to_interval(array_slice, self.shape)
|
|
193
|
+
|
|
194
|
+
# matching from slice to dimension names. We assume fixed (z, y, x) indexing
|
|
195
|
+
dim_names = self.metadata.dimensions
|
|
196
|
+
|
|
197
|
+
accessor_kwargs = {dim: ai for ai, dim in zip(array_intervals, dim_names)}
|
|
198
|
+
|
|
199
|
+
# consolidate channel access into a named dictionary
|
|
200
|
+
spatial_accessor_kwargs = {
|
|
201
|
+
key: value for key, value in accessor_kwargs.items() if key in dimensions.SPATIAL_DIMENSIONS
|
|
202
|
+
}
|
|
203
|
+
channel_accessor_kwargs = {
|
|
204
|
+
key: value for key, value in accessor_kwargs.items() if key not in spatial_accessor_kwargs
|
|
205
|
+
}
|
|
206
|
+
if len(channel_accessor_kwargs) == 0:
|
|
207
|
+
channel_accessor_kwargs = None
|
|
208
|
+
|
|
209
|
+
accessor = ImageAccessor(
|
|
210
|
+
**spatial_accessor_kwargs,
|
|
211
|
+
c=channel_accessor_kwargs,
|
|
212
|
+
scale=self.scale,
|
|
213
|
+
coordinate_scale=self.scale,
|
|
214
|
+
)
|
|
215
|
+
result = self.pipeline(file_name=self.file_name, accessor=accessor, **self.reader_kwargs)
|
|
216
|
+
image = result.image
|
|
217
|
+
|
|
218
|
+
squeeze_dims = [dim for dim in squeeze_dims if image.shape[dim] == 1]
|
|
219
|
+
if squeeze_dims:
|
|
220
|
+
image = image.squeeze(axis=tuple(squeeze_dims))
|
|
221
|
+
return image
|
tiamat/cache.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import weakref
|
|
2
|
+
from functools import wraps
|
|
3
|
+
from typing import Any, Callable, Generic, TypeVar
|
|
4
|
+
|
|
5
|
+
T = TypeVar("T")
|
|
6
|
+
R = TypeVar("R")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def make_hashable(obj: object):
|
|
10
|
+
"""
|
|
11
|
+
Function to make lists, dictionary, sets or nested variants of these hashable.
|
|
12
|
+
|
|
13
|
+
This works by transforming each collection into a fixed size tuple.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
obj : object
|
|
18
|
+
Any python object to return a hashable version of.
|
|
19
|
+
|
|
20
|
+
Returns
|
|
21
|
+
-------
|
|
22
|
+
_type_
|
|
23
|
+
_description_
|
|
24
|
+
"""
|
|
25
|
+
if isinstance(obj, list):
|
|
26
|
+
return tuple(make_hashable(x) for x in obj)
|
|
27
|
+
elif isinstance(obj, dict):
|
|
28
|
+
return tuple(sorted((make_hashable(k), make_hashable(v)) for k, v in obj.items()))
|
|
29
|
+
elif isinstance(obj, set):
|
|
30
|
+
return frozenset(make_hashable(x) for x in obj)
|
|
31
|
+
return obj
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class instance_cache(Generic[T, R]):
|
|
35
|
+
"""
|
|
36
|
+
Decorator to cache method results per instance and argument set.
|
|
37
|
+
|
|
38
|
+
Uses a weak reference dictionary to avoid memory leaks by not preventing
|
|
39
|
+
garbage collection of instances.
|
|
40
|
+
|
|
41
|
+
Example:
|
|
42
|
+
@instance_cache
|
|
43
|
+
def expensive_method(self, x, y):
|
|
44
|
+
# expensive computation
|
|
45
|
+
return result
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, func: Callable[..., R]):
|
|
49
|
+
"""
|
|
50
|
+
Initialize the instance_cache decorator.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
func: The method to decorate. The results of this method
|
|
54
|
+
will be cached per instance and per argument set.
|
|
55
|
+
"""
|
|
56
|
+
self.func = func
|
|
57
|
+
self._caches = weakref.WeakKeyDictionary()
|
|
58
|
+
|
|
59
|
+
def __get__(self, instance: T, owner) -> Callable[..., R]:
|
|
60
|
+
"""
|
|
61
|
+
Return a wrapper that caches results for the given instance.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
instance: The instance of the class calling the method.
|
|
65
|
+
owner: The owner class of the method.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
Callable: The wrapped method with caching enabled.
|
|
69
|
+
"""
|
|
70
|
+
if instance is None:
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
@wraps(self.func)
|
|
74
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
75
|
+
cache = self._caches.setdefault(instance, {})
|
|
76
|
+
key = (make_hashable(args), make_hashable(kwargs))
|
|
77
|
+
if key not in cache:
|
|
78
|
+
cache[key] = self.func(instance, *args, **kwargs)
|
|
79
|
+
return cache[key]
|
|
80
|
+
|
|
81
|
+
return wrapper
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class instance_cached_property(property, Generic[T, R]):
|
|
85
|
+
"""
|
|
86
|
+
Descriptor to cache a computed property per instance.
|
|
87
|
+
|
|
88
|
+
The cached value is stored in a weak reference dictionary to avoid memory leaks.
|
|
89
|
+
Supports getting, setting, and deleting the cached value.
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
class MyClass:
|
|
93
|
+
@instance_cached_property
|
|
94
|
+
def expensive_property(self):
|
|
95
|
+
# compute expensive value
|
|
96
|
+
return value
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(self, func: Callable[[T], R]):
|
|
100
|
+
super().__init__(func)
|
|
101
|
+
self.func = func
|
|
102
|
+
self._values = weakref.WeakKeyDictionary()
|
|
103
|
+
|
|
104
|
+
def __get__(self, instance: T, owner) -> R:
|
|
105
|
+
"""
|
|
106
|
+
Get the cached property value, computing it if necessary.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
instance: The instance accessing the property.
|
|
110
|
+
owner: The owner class of the property.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
The cached property value.
|
|
114
|
+
"""
|
|
115
|
+
if instance is None:
|
|
116
|
+
return self
|
|
117
|
+
if instance not in self._values:
|
|
118
|
+
self._values[instance] = self.func(instance)
|
|
119
|
+
return self._values[instance]
|
|
120
|
+
|
|
121
|
+
def __set__(self, instance: T, value: R):
|
|
122
|
+
"""
|
|
123
|
+
Set or override the cached property value.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
instance: The instance for which to set the value.
|
|
127
|
+
value: The value to store.
|
|
128
|
+
"""
|
|
129
|
+
self._values[instance] = value
|
|
130
|
+
|
|
131
|
+
def __delete__(self, instance: T):
|
|
132
|
+
"""
|
|
133
|
+
Delete the cached property value for the instance.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
instance: The instance for which to delete the value.
|
|
137
|
+
"""
|
|
138
|
+
self._values.pop(instance, None)
|
tiamat/cli.py
ADDED
tiamat/constants.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Constant values.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import cv2
|
|
6
|
+
|
|
7
|
+
FILE_TYPES_GENERIC = ("png", "jpg", "jpeg")
|
|
8
|
+
FILE_TYPES_BIGTIFF = ("tif", "tiff")
|
|
9
|
+
FILE_TYPES_BIGTIFF_ZSTACK = ("zstack",)
|
|
10
|
+
FILE_TYPES_HDF5 = ("hdf5", "h5")
|
|
11
|
+
FILE_TYPES_NIFTI = ("nii", "nii.gz")
|
|
12
|
+
|
|
13
|
+
# Supported intepolartion strategies in accessors
|
|
14
|
+
INTERPOLATION_TYPE_NEAREST = "nearest"
|
|
15
|
+
INTERPOLATION_TYPE_LINEAR = "linear"
|
|
16
|
+
INTERPOLATION_TYPE_CUBIC = "cubic"
|
|
17
|
+
INTERPOLATION_TYPE_AREA = "area"
|
|
18
|
+
INTERPOLATION_TYPE_LANCZOS4 = "lanczos4"
|
|
19
|
+
|
|
20
|
+
# Resolve interpolation strategis to scipy codes
|
|
21
|
+
SCIPY_INTERPOLATION_CODES = {
|
|
22
|
+
INTERPOLATION_TYPE_NEAREST: 0,
|
|
23
|
+
INTERPOLATION_TYPE_LINEAR: 1,
|
|
24
|
+
INTERPOLATION_TYPE_CUBIC: 3,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
# Resolve interpolation strategis to CV2 codes
|
|
28
|
+
OPENCV_INTERPOLATION_CODES = {
|
|
29
|
+
INTERPOLATION_TYPE_NEAREST: cv2.INTER_NEAREST,
|
|
30
|
+
INTERPOLATION_TYPE_LINEAR: cv2.INTER_LINEAR,
|
|
31
|
+
INTERPOLATION_TYPE_CUBIC: cv2.INTER_CUBIC,
|
|
32
|
+
INTERPOLATION_TYPE_AREA: cv2.INTER_AREA,
|
|
33
|
+
INTERPOLATION_TYPE_LANCZOS4: cv2.INTER_LANCZOS4,
|
|
34
|
+
}
|
tiamat/errors.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Custom error types used across the Tiamat image processing library.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TiamatError(Exception):
|
|
7
|
+
"""
|
|
8
|
+
Base class for all custom exceptions in the Tiamat library.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UnknownFileError(TiamatError):
|
|
15
|
+
"""
|
|
16
|
+
Raised when no compatible reader is found for a given file type or file name.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ReaderExistsError(TiamatError):
|
|
23
|
+
"""
|
|
24
|
+
Raised when attempting to register a reader that already exists in the registry.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
pass
|
tiamat/io.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""
|
|
2
|
+
IO objects.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from tiamat.metadata import ImageMetadata
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class ImageAccessor:
|
|
14
|
+
"""
|
|
15
|
+
Defines a region and settings for accessing an image.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
x, y, z: Coordinates or slices for each dimension. Can be an int, float, or a tuple
|
|
19
|
+
of (start, stop). Use None for unspecified.
|
|
20
|
+
c: Channel selection. Can be an int, a tuple of (start, stop), or a dictionary
|
|
21
|
+
mapping channel names to int or tuple.
|
|
22
|
+
scale: Scale factor to retrieve the image.
|
|
23
|
+
spacing: Spacing to retrieve the image. If None, original spacing is used.
|
|
24
|
+
coordinate_scale: Scale of coordinates relative to original image.
|
|
25
|
+
coordinate_spacing: Spacing of coordinates relative to original image.
|
|
26
|
+
interpolation: Interpolation strategy (use tiamat.constants.INTERPOLATION_TYPE_* constants).
|
|
27
|
+
anti_aliasing: Whether to apply Gaussian smoothing. Default is False.
|
|
28
|
+
fill_value: Value for out-of-bounds padding. None means no padding.
|
|
29
|
+
history: Dictionary storing history of operations or transformations.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
x: tuple[int | float | None, int | float | None] | int = None
|
|
33
|
+
y: tuple[int | float | None, int | float | None] | int = None
|
|
34
|
+
z: tuple[int | float | None, int | float | None] | int = None
|
|
35
|
+
c: (
|
|
36
|
+
tuple[int | float | None, int | float | None]
|
|
37
|
+
| int
|
|
38
|
+
| dict[str : tuple[int | float | None, int | float | None] | int]
|
|
39
|
+
) = None
|
|
40
|
+
# scale/spacing to retrieve
|
|
41
|
+
scale: float | tuple[float, ...] = 1.0
|
|
42
|
+
spacing: float | tuple[float, ...] = None
|
|
43
|
+
# scale/spacing of coordinates
|
|
44
|
+
coordinate_scale: float = 1.0
|
|
45
|
+
coordinate_spacing: float = 1.0
|
|
46
|
+
# One of the interpolation types in tiamat.constants
|
|
47
|
+
interpolation: str = None
|
|
48
|
+
# Wether to apply Gauss smothing, default is False:
|
|
49
|
+
anti_aliasing: bool = False
|
|
50
|
+
# (Maybe not needed) Std of Gauss filter, default is (s - 1) / 2:
|
|
51
|
+
# anti_aliasing_sigma: float = None
|
|
52
|
+
# Fill value for out-of-bounds request (padding)
|
|
53
|
+
# Can be set to None for no padding
|
|
54
|
+
fill_value: int | float = None
|
|
55
|
+
history: dict = field(default_factory=dict)
|
|
56
|
+
|
|
57
|
+
def __repr__(self):
|
|
58
|
+
return (
|
|
59
|
+
f"ImageAccessor("
|
|
60
|
+
f"x={self.x}, "
|
|
61
|
+
f"y={self.y}, "
|
|
62
|
+
f"z={self.z}, "
|
|
63
|
+
f"c={self.c},\n"
|
|
64
|
+
f" scale={self.scale}, "
|
|
65
|
+
f"spacing={self.spacing}, "
|
|
66
|
+
f"coordinate_scale={self.coordinate_scale}, "
|
|
67
|
+
f"coordinate_spacing={self.coordinate_spacing},\n"
|
|
68
|
+
f" interpolation={self.interpolation}, "
|
|
69
|
+
f"anti_aliasing={self.anti_aliasing}, "
|
|
70
|
+
f"fill_value={self.fill_value}"
|
|
71
|
+
f")"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def __str__(self):
|
|
75
|
+
return self.__repr__()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class ImageResult:
|
|
80
|
+
"""
|
|
81
|
+
Stores an image with its corresponding metadata.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
image: np.ndarray
|
|
85
|
+
metadata: ImageMetadata | None = None
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Specification of dimension in image data.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
X = "x" # spatial x-axis
|
|
6
|
+
Y = "y" # spatial y-axis
|
|
7
|
+
Z = "z" # spatial z-axis
|
|
8
|
+
C = "c" # generic channel
|
|
9
|
+
T = "t" # time
|
|
10
|
+
RGB = "rgb" # color channels (e.g., red, green, blue)
|
|
11
|
+
RGBA = "rgba" # color channels (e.g., red, green, blue, alpha)
|
|
12
|
+
VECTOR = "vec" # vector valued data (e.g., deformations)
|
|
13
|
+
|
|
14
|
+
# Order for spatial dimensions in the image (shape)
|
|
15
|
+
SPATIAL_DIMENSIONS = (Z, Y, X)
|
|
16
|
+
|
|
17
|
+
# Order of dimensions in image metadata (spacing, scale, ...)
|
|
18
|
+
META_DIMENSIONS = (X, Y, Z)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Metadata on images.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from itertools import product, repeat
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
import tiamat.metadata.dimensions as dimensions
|
|
12
|
+
|
|
13
|
+
# Image types
|
|
14
|
+
IMAGE_TYPE_SEGMENTATION = "segmentation" # an image with discrete values, e.g., a mask or a segmentation.
|
|
15
|
+
IMAGE_TYPE_IMAGE = "image" # an image with continuous values (e.g., a microscopy image).
|
|
16
|
+
IMAGE_TYPE_VECTOR = "vector" # an image with continuous vector values (e.g., a deformation field).
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_dtype_limits(dtype):
|
|
20
|
+
"""Returns the min and max values for a given dtype.
|
|
21
|
+
|
|
22
|
+
Supports numpy dtypes (integer or float)
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
dtype: numpy dtype
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
tuple: min and max value of the dtype.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
dtype = np.dtype(dtype)
|
|
32
|
+
|
|
33
|
+
if issubclass(dtype.type, np.integer):
|
|
34
|
+
info = np.iinfo(dtype)
|
|
35
|
+
elif issubclass(dtype.type, np.floating):
|
|
36
|
+
info = np.finfo(dtype)
|
|
37
|
+
else:
|
|
38
|
+
raise RuntimeError(f"{dtype} is not a valid dtype")
|
|
39
|
+
return info.min, info.max
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class ImageMetadata:
|
|
44
|
+
"""
|
|
45
|
+
Metadata of an image.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
image_type: str
|
|
49
|
+
shape: tuple
|
|
50
|
+
value_range: tuple
|
|
51
|
+
dtype: np.dtype
|
|
52
|
+
dimensions: list[str, ...] | tuple[str, ...] = (dimensions.Y, dimensions.X, dimensions.C)
|
|
53
|
+
file_path: Iterable[str] | str | None = None
|
|
54
|
+
spacing: float | tuple[float, ...] | None = None
|
|
55
|
+
additional_metadata: dict = field(default_factory=dict)
|
|
56
|
+
scales: float | int | Iterable[float | int] | None = None
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def spatial_dimensions(self):
|
|
60
|
+
"""
|
|
61
|
+
Returns indices of spatial axes, excluding channels
|
|
62
|
+
"""
|
|
63
|
+
return tuple(
|
|
64
|
+
self.dimensions.index(dimension)
|
|
65
|
+
for dimension in dimensions.SPATIAL_DIMENSIONS
|
|
66
|
+
if dimension in self.dimensions
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def channel_dimensions(self):
|
|
71
|
+
"""
|
|
72
|
+
Returns indices of channels, excluding spatial axes
|
|
73
|
+
"""
|
|
74
|
+
return tuple(index for index, _ in enumerate(self.shape) if index not in self.spatial_dimensions)
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def spatial_shape(self):
|
|
78
|
+
return tuple(self.shape[i] for i in self.spatial_dimensions)
|
|
79
|
+
|
|
80
|
+
@spatial_shape.setter
|
|
81
|
+
def spatial_shape(self, shape):
|
|
82
|
+
shape_list = list(self.shape)
|
|
83
|
+
for i, ix in enumerate(self.spatial_dimensions):
|
|
84
|
+
shape_list[ix] = shape[i]
|
|
85
|
+
self.shape = tuple(shape_list)
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def extents(self):
|
|
89
|
+
"""
|
|
90
|
+
Extents of the image. Provided as a list of tuple of coordinates.
|
|
91
|
+
Extrapolated by shape. Can be set, and will then return the set value.
|
|
92
|
+
Delete the property to revert to the default behavior.
|
|
93
|
+
"""
|
|
94
|
+
if hasattr(self, "_extents"):
|
|
95
|
+
return self._extents
|
|
96
|
+
extents = list(zip(repeat(0), self.shape))
|
|
97
|
+
return list(product(*extents))
|
|
98
|
+
|
|
99
|
+
@extents.deleter
|
|
100
|
+
def extents(self):
|
|
101
|
+
delattr(self, "_extents")
|
|
102
|
+
|
|
103
|
+
def __repr__(self):
|
|
104
|
+
return (
|
|
105
|
+
f"ImageMetadata(\n"
|
|
106
|
+
f" image_type={self.image_type},\n"
|
|
107
|
+
f" shape={self.shape},\n"
|
|
108
|
+
f" value_range={self.value_range},\n"
|
|
109
|
+
f" dtype={self.dtype},\n"
|
|
110
|
+
f" spacing={self.spacing},\n"
|
|
111
|
+
f" dimensions=({','.join(self.dimensions)}),\n"
|
|
112
|
+
f" additional_metadata={self.additional_metadata},\n"
|
|
113
|
+
f" scales={self.scales}\n"
|
|
114
|
+
f")"
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
def __str__(self):
|
|
118
|
+
return self.__repr__()
|