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
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Deformation field transformers.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from tiamat.cache import instance_cached_property
|
|
13
|
+
from tiamat.io import ImageAccessor
|
|
14
|
+
from tiamat.metadata import ImageMetadata
|
|
15
|
+
from tiamat.readers.protocol import ImageReader
|
|
16
|
+
from tiamat.transformers.protocol import Transformer
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DeformationFieldTransformer(Transformer):
|
|
20
|
+
"""Transformer that warps images using a deformation field."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
dfield_file: str,
|
|
25
|
+
request_margin: int = 2,
|
|
26
|
+
interpolation="linear",
|
|
27
|
+
fill_value: int | float | None = None,
|
|
28
|
+
xy_coordinates=True,
|
|
29
|
+
reader_factory: Callable[[str], ImageReader] | None = None,
|
|
30
|
+
):
|
|
31
|
+
"""
|
|
32
|
+
Creates an instance of DeformationFieldTransformer
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
dfield_file: Path to file storing the deformation field.
|
|
36
|
+
request_margin: Pixel margin around requested image to avoid resampling artifacts.
|
|
37
|
+
interpolation: Interpolation method for deformation.
|
|
38
|
+
fill_value: Value used for padding areas outside the image.
|
|
39
|
+
xy_coordinates: Whether deformation field is in XY order.
|
|
40
|
+
reader_factory: Callable returning ImageReader for a given file path.
|
|
41
|
+
"""
|
|
42
|
+
from tiamat.readers.factory import get_reader
|
|
43
|
+
|
|
44
|
+
self.dfield_file = dfield_file
|
|
45
|
+
self.reader_factory = reader_factory or get_reader
|
|
46
|
+
|
|
47
|
+
self.xy_coordinates = xy_coordinates
|
|
48
|
+
|
|
49
|
+
self.request_margin = request_margin
|
|
50
|
+
self.interpolation = interpolation
|
|
51
|
+
self.fill_value = fill_value
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def get_pixel_coordinates(
|
|
55
|
+
dfield: np.ndarray,
|
|
56
|
+
dfield_spacing: tuple[float, float],
|
|
57
|
+
dfield_scale: tuple[int, int],
|
|
58
|
+
dfield_origin: tuple[float, float],
|
|
59
|
+
image_spacing: tuple[float, float],
|
|
60
|
+
coord_dim: int = 2,
|
|
61
|
+
xy: bool = True,
|
|
62
|
+
):
|
|
63
|
+
"""
|
|
64
|
+
Convert deformation field vectors to pixel coordinates in image space.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
dfield: Deformation field array.
|
|
68
|
+
dfield_spacing: Physical spacing of the deformation field.
|
|
69
|
+
dfield_scale: Scale of the deformation field.
|
|
70
|
+
dfield_origin: Physical origin of the deformation field.
|
|
71
|
+
image_spacing: Target image spacing.
|
|
72
|
+
coord_dim: Axis along which coordinate components are stored.
|
|
73
|
+
xy: Whether the deformation field uses XY or YX ordering.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
Pixel coordinates as an array of shape (2, H, W).
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
# Determine if deformation vectors are xy or yx order
|
|
80
|
+
if xy:
|
|
81
|
+
x_i, y_i = 0, 1
|
|
82
|
+
else:
|
|
83
|
+
x_i, y_i = 1, 0
|
|
84
|
+
|
|
85
|
+
# Convert relative deformation vectors to absolute physical coordinates
|
|
86
|
+
offset_x = np.arange(0, dfield.shape[1]) * dfield_spacing[0] / dfield_scale[0] + dfield_origin[0]
|
|
87
|
+
offset_y = np.arange(0, dfield.shape[0]) * dfield_spacing[1] / dfield_scale[1] + dfield_origin[1]
|
|
88
|
+
|
|
89
|
+
phys_x = np.take(dfield, x_i, axis=coord_dim) + offset_x[None]
|
|
90
|
+
phys_y = np.take(dfield, y_i, axis=coord_dim) + offset_y[:, None]
|
|
91
|
+
|
|
92
|
+
# Convert absolute physical coordinates to pixel coordinates of the image
|
|
93
|
+
coord_x = phys_x / image_spacing[0]
|
|
94
|
+
coord_y = phys_y / image_spacing[1]
|
|
95
|
+
|
|
96
|
+
return np.stack((coord_y, coord_x), axis=0)
|
|
97
|
+
|
|
98
|
+
@instance_cached_property
|
|
99
|
+
def dfield_file_handle(self) -> ImageReader:
|
|
100
|
+
"""Return a cached ImageReader for the deformation field file."""
|
|
101
|
+
# TODO: Need to connect this reader to a reader_post_creation_hook somehow and change
|
|
102
|
+
# to @property to manage caching of open file handles at a central location
|
|
103
|
+
return self.reader_factory(self.dfield_file)
|
|
104
|
+
|
|
105
|
+
@instance_cached_property
|
|
106
|
+
def dfield_metadata(self) -> ImageMetadata:
|
|
107
|
+
"""Metadata of the deformation field."""
|
|
108
|
+
return self.dfield_file_handle.read_metadata()
|
|
109
|
+
|
|
110
|
+
@instance_cached_property
|
|
111
|
+
def dfield_spacing(self) -> tuple[float, float]:
|
|
112
|
+
"""Return physical spacing of the deformation field in two dimensions."""
|
|
113
|
+
from tiamat.readers.processing import expand_to_length
|
|
114
|
+
|
|
115
|
+
return expand_to_length(self.dfield_file_handle.spacing, 2)
|
|
116
|
+
|
|
117
|
+
@instance_cached_property
|
|
118
|
+
def dfield_origin(self) -> tuple[float, float]:
|
|
119
|
+
"""Return physical origin of the deformation field."""
|
|
120
|
+
dfield_origin = (0.0, 0.0)
|
|
121
|
+
if self.dfield_metadata.additional_metadata is not None:
|
|
122
|
+
if "dfield_origin" in self.dfield_metadata.additional_metadata.keys():
|
|
123
|
+
dfield_origin = self.dfield_metadata.additional_metadata["dfield_origin"]
|
|
124
|
+
|
|
125
|
+
return dfield_origin
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def apply_deformation(
|
|
129
|
+
image: np.ndarray,
|
|
130
|
+
coordinates: np.ndarray,
|
|
131
|
+
channel_dim: int | None = None,
|
|
132
|
+
fill_value: int | float = 0,
|
|
133
|
+
interpolation: str = "nearest",
|
|
134
|
+
) -> np.ndarray:
|
|
135
|
+
"""
|
|
136
|
+
Apply a deformation field to an image using scipy map_coordinates.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
image: Image array to be deformed.
|
|
140
|
+
coordinates: Pixel coordinates computed from deformation field.
|
|
141
|
+
channel_dim: Channel axis to apply deformation per channel, if present.
|
|
142
|
+
fill_value: Value for pixels outside the input image.
|
|
143
|
+
interpolation: Interpolation method.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
Deformed image array.
|
|
147
|
+
"""
|
|
148
|
+
from scipy.ndimage import map_coordinates
|
|
149
|
+
|
|
150
|
+
from tiamat.constants import SCIPY_INTERPOLATION_CODES
|
|
151
|
+
|
|
152
|
+
if channel_dim is None:
|
|
153
|
+
out_image = map_coordinates(
|
|
154
|
+
image,
|
|
155
|
+
coordinates,
|
|
156
|
+
order=SCIPY_INTERPOLATION_CODES[interpolation],
|
|
157
|
+
mode="constant",
|
|
158
|
+
cval=fill_value,
|
|
159
|
+
)
|
|
160
|
+
else:
|
|
161
|
+
img_standard = np.moveaxis(image, channel_dim, -1)
|
|
162
|
+
num_channels = img_standard.shape[-1]
|
|
163
|
+
|
|
164
|
+
# Allocate memory for result
|
|
165
|
+
result = np.empty((*coordinates.shape[1:], num_channels), dtype=image.dtype)
|
|
166
|
+
|
|
167
|
+
# Loop over each channel
|
|
168
|
+
for c in range(num_channels):
|
|
169
|
+
image_channel = img_standard[..., c]
|
|
170
|
+
|
|
171
|
+
result[..., c] = map_coordinates(
|
|
172
|
+
image_channel,
|
|
173
|
+
coordinates,
|
|
174
|
+
order=SCIPY_INTERPOLATION_CODES[interpolation],
|
|
175
|
+
mode="constant",
|
|
176
|
+
cval=fill_value,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
out_image = np.moveaxis(result, -1, channel_dim)
|
|
180
|
+
|
|
181
|
+
return out_image
|
|
182
|
+
|
|
183
|
+
def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
|
|
184
|
+
"""
|
|
185
|
+
Compute the accessor coordinates needed to read the deformation field.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
accessor: ImageAccessor of the target image.
|
|
189
|
+
metadata: ImageMetadata of the target image.
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
Updated ImageAccessor with coordinates for deformation.
|
|
193
|
+
"""
|
|
194
|
+
import math
|
|
195
|
+
from dataclasses import replace
|
|
196
|
+
|
|
197
|
+
from tiamat.readers.processing import (
|
|
198
|
+
_prepare_coordinates,
|
|
199
|
+
expand_to_length,
|
|
200
|
+
rescale_shape,
|
|
201
|
+
)
|
|
202
|
+
from tiamat.transformers.coordinates import resolve_coordinate_slice
|
|
203
|
+
|
|
204
|
+
image_scale = expand_to_length(accessor.scale, 2)[:2]
|
|
205
|
+
image_spacing = expand_to_length(metadata.spacing, 2)[:2]
|
|
206
|
+
image_shape = metadata.shape
|
|
207
|
+
|
|
208
|
+
coord_scale = expand_to_length(accessor.coordinate_scale, 2)
|
|
209
|
+
|
|
210
|
+
# Input are pixel coordinates for scale=1.0
|
|
211
|
+
prepared_coordinates = _prepare_coordinates(x=accessor.x, y=accessor.y)
|
|
212
|
+
x, y = prepared_coordinates["x"], prepared_coordinates["y"]
|
|
213
|
+
|
|
214
|
+
spatial_dims = metadata.spatial_dimensions
|
|
215
|
+
x_from, x_to = resolve_coordinate_slice(x, image_shape[spatial_dims[-1]])
|
|
216
|
+
y_from, y_to = resolve_coordinate_slice(y, image_shape[spatial_dims[-2]])
|
|
217
|
+
|
|
218
|
+
scale_factor = (
|
|
219
|
+
self.dfield_spacing[0] / image_spacing[0],
|
|
220
|
+
self.dfield_spacing[1] / image_spacing[1],
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
# Request fitting scale of dfield that matches physical resolution of the request
|
|
224
|
+
target_scale = (
|
|
225
|
+
image_scale[0] * scale_factor[0],
|
|
226
|
+
image_scale[1] * scale_factor[1],
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
tmp_coord_scale = (
|
|
230
|
+
coord_scale[0] * scale_factor[0],
|
|
231
|
+
coord_scale[1] * scale_factor[1],
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
# Target shape of coordinates is same as image shape
|
|
235
|
+
target_shape = rescale_shape(
|
|
236
|
+
((y_to - y_from), (x_to - x_from)),
|
|
237
|
+
(target_scale[0] / tmp_coord_scale[0], target_scale[1] / tmp_coord_scale[1]),
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
# Request more coordinates if dfield needs to be upscaled to avoid artifacts at corners
|
|
241
|
+
tmp_margin = (
|
|
242
|
+
tmp_coord_scale[0] if target_scale[0] > 1.0 else 0,
|
|
243
|
+
tmp_coord_scale[1] if target_scale[1] > 1.0 else 0,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# Build temporary accessor to read dfield vectors
|
|
247
|
+
tmp_accessor = replace(accessor)
|
|
248
|
+
tmp_accessor.scale = target_scale
|
|
249
|
+
tmp_accessor.coordinate_scale = tmp_coord_scale
|
|
250
|
+
tmp_accessor.interpolation = "linear"
|
|
251
|
+
tmp_accessor.fill_value = -1
|
|
252
|
+
|
|
253
|
+
# Request margin if dfield needs upscaling to avoid artifacts
|
|
254
|
+
tmp_accessor.x = (
|
|
255
|
+
x_from - tmp_margin[0],
|
|
256
|
+
x_to + tmp_margin[0],
|
|
257
|
+
)
|
|
258
|
+
tmp_accessor.y = (
|
|
259
|
+
y_from - tmp_margin[1],
|
|
260
|
+
y_to + tmp_margin[1],
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
# Read the corresponding crop from dfield
|
|
264
|
+
dfield_crop = self.dfield_file_handle.read_image(tmp_accessor)
|
|
265
|
+
|
|
266
|
+
# Crop the output to valid pixels not affected by the margin
|
|
267
|
+
offset = (
|
|
268
|
+
math.floor((dfield_crop.shape[0] - target_shape[0]) / 2),
|
|
269
|
+
math.floor((dfield_crop.shape[1] - target_shape[1]) / 2),
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
assert offset[0] >= 0 and offset[1] >= 0, "target_shape can not be larger than dfield_crop shape"
|
|
273
|
+
|
|
274
|
+
dfield_vectors = dfield_crop[
|
|
275
|
+
offset[0] : (offset[0] + target_shape[0]),
|
|
276
|
+
offset[1] : (offset[1] + target_shape[1]),
|
|
277
|
+
]
|
|
278
|
+
|
|
279
|
+
# Convert pixel coordinates to physical coordinates
|
|
280
|
+
x_from_phys = x_from * image_spacing[0]
|
|
281
|
+
y_from_phys = y_from * image_spacing[1]
|
|
282
|
+
|
|
283
|
+
# Determine requested coordinates from deformation vectors
|
|
284
|
+
coordinates = DeformationFieldTransformer.get_pixel_coordinates(
|
|
285
|
+
dfield=dfield_vectors,
|
|
286
|
+
dfield_spacing=self.dfield_spacing,
|
|
287
|
+
dfield_scale=target_scale,
|
|
288
|
+
dfield_origin=(x_from_phys + self.dfield_origin[0], y_from_phys + self.dfield_origin[1]),
|
|
289
|
+
image_spacing=image_spacing,
|
|
290
|
+
xy=self.xy_coordinates,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
# Build requested frame from coordinates with margin
|
|
294
|
+
scaled_margin = np.divide(self.request_margin, image_scale)
|
|
295
|
+
|
|
296
|
+
min_xy = np.min(coordinates, axis=(1, 2)) - scaled_margin
|
|
297
|
+
max_xy = np.max(coordinates, axis=(1, 2)) + scaled_margin
|
|
298
|
+
min_x, max_x = min_xy[1], max_xy[1]
|
|
299
|
+
min_y, max_y = min_xy[0], max_xy[0]
|
|
300
|
+
|
|
301
|
+
# Store requested frame and coordinates in accessor
|
|
302
|
+
accessor = replace(accessor)
|
|
303
|
+
accessor.x = (math.floor(min_x), math.ceil(max_x) + 1)
|
|
304
|
+
accessor.y = (math.floor(min_y), math.ceil(max_y) + 1)
|
|
305
|
+
if self.fill_value is not None:
|
|
306
|
+
accessor.fill_value = self.fill_value
|
|
307
|
+
elif accessor.fill_value is None:
|
|
308
|
+
accessor.fill_value = 0
|
|
309
|
+
|
|
310
|
+
# Store pixel coordinates for transforming image
|
|
311
|
+
coord_origin = np.array((accessor.y[0], accessor.x[0]), dtype=float)
|
|
312
|
+
px_coordinates = (coordinates - coord_origin[:, np.newaxis, np.newaxis]) * np.array(image_scale)[
|
|
313
|
+
:, np.newaxis, np.newaxis
|
|
314
|
+
]
|
|
315
|
+
accessor.history[id(self)] = px_coordinates
|
|
316
|
+
|
|
317
|
+
return accessor
|
|
318
|
+
|
|
319
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
320
|
+
"""
|
|
321
|
+
Update metadata according to deformation field.
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
metadata: Original ImageMetadata.
|
|
325
|
+
|
|
326
|
+
Returns:
|
|
327
|
+
Updated ImageMetadata with modified spatial shape.
|
|
328
|
+
"""
|
|
329
|
+
from dataclasses import replace
|
|
330
|
+
|
|
331
|
+
from tiamat.readers.processing import expand_to_length
|
|
332
|
+
|
|
333
|
+
metadata = replace(metadata)
|
|
334
|
+
|
|
335
|
+
image_spacing = expand_to_length(metadata.spacing, 2)
|
|
336
|
+
|
|
337
|
+
out_shape = (
|
|
338
|
+
int(self.dfield_metadata.spatial_shape[-2] * self.dfield_spacing[1] / image_spacing[1]),
|
|
339
|
+
int(self.dfield_metadata.spatial_shape[-1] * self.dfield_spacing[0] / image_spacing[0]),
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
metadata.spatial_shape = (*metadata.shape[:-2], *out_shape)
|
|
343
|
+
|
|
344
|
+
return metadata
|
|
345
|
+
|
|
346
|
+
def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
|
|
347
|
+
"""
|
|
348
|
+
Apply deformation field to the image.
|
|
349
|
+
|
|
350
|
+
Args:
|
|
351
|
+
image: Input image array.
|
|
352
|
+
metadata: Metadata of the image.
|
|
353
|
+
accessor: ImageAccessor storing pixel coordinates in history.
|
|
354
|
+
|
|
355
|
+
Returns:
|
|
356
|
+
Deformed image array.
|
|
357
|
+
"""
|
|
358
|
+
try:
|
|
359
|
+
px_coordinates = accessor.history[id(self)]
|
|
360
|
+
except KeyError:
|
|
361
|
+
raise Exception("transform_access has to be called once before transform_image")
|
|
362
|
+
|
|
363
|
+
if self.fill_value is None:
|
|
364
|
+
if accessor.fill_value is None:
|
|
365
|
+
fill_value = 0
|
|
366
|
+
else:
|
|
367
|
+
fill_value = accessor.fill_value
|
|
368
|
+
else:
|
|
369
|
+
fill_value = self.fill_value
|
|
370
|
+
|
|
371
|
+
ch_dim = metadata.channel_dimensions
|
|
372
|
+
if len(ch_dim) > 1:
|
|
373
|
+
raise Exception(f"Multiple channels {ch_dim} not supported in DeformationField Transformer")
|
|
374
|
+
elif len(ch_dim) == 1:
|
|
375
|
+
ch_dim = ch_dim[0]
|
|
376
|
+
else:
|
|
377
|
+
ch_dim = None
|
|
378
|
+
|
|
379
|
+
spatial_dimensions = metadata.spatial_dimensions
|
|
380
|
+
if len(spatial_dimensions) > 2:
|
|
381
|
+
result_imgs = []
|
|
382
|
+
# Loop over first spatial dimension
|
|
383
|
+
for i in range(image.shape[spatial_dimensions[0]]):
|
|
384
|
+
result_imgs.append(
|
|
385
|
+
DeformationFieldTransformer.apply_deformation(
|
|
386
|
+
image=image[i],
|
|
387
|
+
coordinates=px_coordinates,
|
|
388
|
+
channel_dim=ch_dim,
|
|
389
|
+
fill_value=fill_value,
|
|
390
|
+
interpolation=self.interpolation,
|
|
391
|
+
)
|
|
392
|
+
)
|
|
393
|
+
result_image = np.stack(result_imgs, axis=0)
|
|
394
|
+
image = result_image
|
|
395
|
+
else:
|
|
396
|
+
image = DeformationFieldTransformer.apply_deformation(
|
|
397
|
+
image=image,
|
|
398
|
+
coordinates=px_coordinates,
|
|
399
|
+
channel_dim=ch_dim,
|
|
400
|
+
fill_value=fill_value,
|
|
401
|
+
interpolation=self.interpolation,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
return image
|
|
405
|
+
|
|
406
|
+
@classmethod
|
|
407
|
+
def from_json(cls, args: dict[str, Any]):
|
|
408
|
+
"""
|
|
409
|
+
Instantiate a DeformationFieldTransformer from a JSON-like dictionary.
|
|
410
|
+
|
|
411
|
+
Args:
|
|
412
|
+
args: Dictionary containing configuration keys:
|
|
413
|
+
- dfield_file: Path to the deformation field file (required).
|
|
414
|
+
- request_margin: Margin in pixels to avoid resampling artifacts (optional, default=2).
|
|
415
|
+
- interpolation: Interpolation method, e.g., 'linear' (optional, default='linear').
|
|
416
|
+
- fill_value: Value for pixels outside image bounds (optional).
|
|
417
|
+
- xy_coordinates: Whether deformation field uses XY ordering (optional, default=True).
|
|
418
|
+
- reader_factory: Optional configuration for a custom ImageReader factory.
|
|
419
|
+
|
|
420
|
+
Returns:
|
|
421
|
+
An instance of DeformationFieldTransformer configured according to args.
|
|
422
|
+
"""
|
|
423
|
+
from tiamat.serialization import get_reader_from_config
|
|
424
|
+
|
|
425
|
+
return cls(
|
|
426
|
+
dfield_file=args["dfield_file"],
|
|
427
|
+
request_margin=args.get("request_margin", 2),
|
|
428
|
+
interpolation=args.get("interpolation", "linear"),
|
|
429
|
+
fill_value=args.get("fill_value"),
|
|
430
|
+
xy_coordinates=args.get("xy_coordinates", True),
|
|
431
|
+
reader_factory=get_reader_from_config(args.get("reader_factory")),
|
|
432
|
+
)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Transformers to specifically modify metadata.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from abc import ABC
|
|
6
|
+
from dataclasses import fields
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from ..io import ImageAccessor
|
|
12
|
+
from ..metadata import ImageMetadata
|
|
13
|
+
from .protocol import Transformer
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _MetadataTransformer(ABC, Transformer):
|
|
17
|
+
"""
|
|
18
|
+
Base class for transformers that only modify metadata.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
|
|
22
|
+
# noop, no access transformation
|
|
23
|
+
return accessor
|
|
24
|
+
|
|
25
|
+
def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
|
|
26
|
+
# noop, no image transformation
|
|
27
|
+
return image
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class MetadataKwargsTransformer(_MetadataTransformer):
|
|
31
|
+
"""
|
|
32
|
+
Modify metadata based on given kwargs
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
**kwargs: Any,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""
|
|
40
|
+
Args:
|
|
41
|
+
**kwargs: Field-value pairs to set in the metadata.
|
|
42
|
+
"""
|
|
43
|
+
self.metadata_kwargs = kwargs
|
|
44
|
+
|
|
45
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
46
|
+
"""
|
|
47
|
+
Applied the transformation defined by the given lambda.
|
|
48
|
+
"""
|
|
49
|
+
from dataclasses import replace
|
|
50
|
+
|
|
51
|
+
metadata = replace(metadata)
|
|
52
|
+
|
|
53
|
+
field_names = {f.name for f in fields(metadata)}
|
|
54
|
+
|
|
55
|
+
for key, value in self.metadata_kwargs.items():
|
|
56
|
+
if key in field_names:
|
|
57
|
+
setattr(metadata, key, value)
|
|
58
|
+
else:
|
|
59
|
+
raise AttributeError(f"{key} is not a valid metadata attribute")
|
|
60
|
+
|
|
61
|
+
return metadata
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class MetadataLambdaTransformer(_MetadataTransformer):
|
|
65
|
+
"""
|
|
66
|
+
Modify metadata based on a given callable.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
metadata_lambda: Callable[
|
|
72
|
+
[
|
|
73
|
+
ImageMetadata,
|
|
74
|
+
],
|
|
75
|
+
ImageMetadata,
|
|
76
|
+
],
|
|
77
|
+
) -> None:
|
|
78
|
+
self.metadata_lambda = metadata_lambda
|
|
79
|
+
|
|
80
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
81
|
+
"""
|
|
82
|
+
Applied the transformation defined by the given lambda.
|
|
83
|
+
"""
|
|
84
|
+
from dataclasses import replace
|
|
85
|
+
|
|
86
|
+
metadata = replace(metadata)
|
|
87
|
+
|
|
88
|
+
return self.metadata_lambda(metadata)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Normalization transformers.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from ..io import ImageAccessor
|
|
8
|
+
from ..metadata import ImageMetadata
|
|
9
|
+
from .protocol import Transformer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MinMaxNormalizationTransformer(Transformer):
|
|
13
|
+
"""
|
|
14
|
+
Normalize image intensities to [0, 1] using the metadata value range.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, target_dtype: type[np.floating] = np.float32) -> None:
|
|
18
|
+
"""
|
|
19
|
+
Initialize the transformer.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
target_dtype: Floating point dtype for the normalized image.
|
|
23
|
+
Defaults to np.float32.
|
|
24
|
+
"""
|
|
25
|
+
self.target_dtype = target_dtype
|
|
26
|
+
|
|
27
|
+
def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
|
|
28
|
+
"""
|
|
29
|
+
No changes to the accessor are needed for normalization.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
accessor: ImageAccessor of the target image.
|
|
33
|
+
metadata: Metadata of the target image.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
The unmodified ImageAccessor.
|
|
37
|
+
"""
|
|
38
|
+
return accessor
|
|
39
|
+
|
|
40
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
41
|
+
"""
|
|
42
|
+
Update metadata to reflect normalization.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
metadata: Original ImageMetadata.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
Updated ImageMetadata with dtype set to target_dtype and value_range set to (0.0, 1.0).
|
|
49
|
+
"""
|
|
50
|
+
from dataclasses import replace
|
|
51
|
+
|
|
52
|
+
metadata = replace(metadata)
|
|
53
|
+
|
|
54
|
+
metadata.dtype = self.target_dtype
|
|
55
|
+
metadata.value_range = (0.0, 1.0)
|
|
56
|
+
|
|
57
|
+
return metadata
|
|
58
|
+
|
|
59
|
+
def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
|
|
60
|
+
"""
|
|
61
|
+
Apply min-max normalization to the image.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
image: Image to transform.
|
|
65
|
+
metadata: Metadata of the image.
|
|
66
|
+
accessor: Accessor to the image.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
np.ndarray: Image normalized to the range [0, 1].
|
|
70
|
+
"""
|
|
71
|
+
assert metadata.value_range is not None, "MinMaxNormalizationTransformer requires metadata.value_range."
|
|
72
|
+
|
|
73
|
+
vmin, vmax = metadata.value_range
|
|
74
|
+
|
|
75
|
+
image = (image.astype(self.target_dtype) - vmin) / (vmax - vmin)
|
|
76
|
+
|
|
77
|
+
return image
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Protocol for transformers.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from ..io import ImageAccessor
|
|
10
|
+
from ..metadata import ImageMetadata
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Transformer(Protocol):
|
|
14
|
+
"""
|
|
15
|
+
Protocol for image transformation steps in a pipeline.
|
|
16
|
+
|
|
17
|
+
A transformer can modify metadata, access parameters, and image data
|
|
18
|
+
in three stages, executed in the following order:
|
|
19
|
+
|
|
20
|
+
1. transform_metadata
|
|
21
|
+
2. transform_access
|
|
22
|
+
3. transform_image
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
26
|
+
"""
|
|
27
|
+
Adjusts image metadata to match the metadata describing
|
|
28
|
+
the transformed image returned by `transform_image`.
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
metadata : ImageMetadata
|
|
33
|
+
Metadata from the downstream transformer or pipeline reader.
|
|
34
|
+
|
|
35
|
+
Returns
|
|
36
|
+
-------
|
|
37
|
+
ImageMetadata
|
|
38
|
+
Updated metadata associated with the transformed image.
|
|
39
|
+
"""
|
|
40
|
+
from dataclasses import replace
|
|
41
|
+
|
|
42
|
+
metadata = replace(metadata)
|
|
43
|
+
|
|
44
|
+
return metadata
|
|
45
|
+
|
|
46
|
+
def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
|
|
47
|
+
"""
|
|
48
|
+
Modifies how the image should be accessed to read the correct image
|
|
49
|
+
input required by `transform_image`.
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
accessor : ImageAccessor
|
|
54
|
+
Access configuration from the upstream transformer or user.
|
|
55
|
+
metadata : ImageMetadata
|
|
56
|
+
Metadata output from this transformer's `transform_metadata`.
|
|
57
|
+
|
|
58
|
+
Returns
|
|
59
|
+
-------
|
|
60
|
+
ImageAccessor
|
|
61
|
+
Updated accessor to be passed downstream.
|
|
62
|
+
"""
|
|
63
|
+
return accessor
|
|
64
|
+
|
|
65
|
+
def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
|
|
66
|
+
"""
|
|
67
|
+
Modifies image pixel data based on its metadata and an accessor.
|
|
68
|
+
|
|
69
|
+
Parameters
|
|
70
|
+
----------
|
|
71
|
+
image : np.ndarray
|
|
72
|
+
Image data from a downstream transformer or the pipeline reader
|
|
73
|
+
to be transformed.
|
|
74
|
+
metadata : ImageMetadata
|
|
75
|
+
Associated metadata from the downstream transformer or reader.
|
|
76
|
+
accessor : ImageAccessor
|
|
77
|
+
Access configuration from the upstream transformer or user.
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
np.ndarray
|
|
82
|
+
Transformed image data.
|
|
83
|
+
"""
|
|
84
|
+
return image
|