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,216 @@
1
+ """
2
+ Transformers that affect how files are accessed.
3
+ """
4
+
5
+ import math
6
+
7
+ import numpy as np
8
+
9
+ from ..io import ImageAccessor
10
+ from ..metadata import ImageMetadata
11
+ from .protocol import Transformer
12
+
13
+
14
+ class SpacingToScaleTransformer(Transformer):
15
+ """
16
+ Transformer that converts spacing information from metadata into scaling factors for accessors.
17
+
18
+ This transformer adjusts the `scale`, `x`, and `y` coordinates of an ImageAccessor
19
+ based on the image spacing provided in the metadata.
20
+ """
21
+
22
+ def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
23
+ """
24
+ Adjusts the accessor's scale and coordinates according to metadata spacing.
25
+
26
+ Args:
27
+ accessor: The ImageAccessor to transform.
28
+ metadata: The metadata of the image to transform.
29
+
30
+ Returns:
31
+ A new ImageAccessor with adjusted scale and coordinates.
32
+
33
+ Raises:
34
+ AssertionError: If metadata or required spacing fields are missing.
35
+ AssertionError: If anisotropic image spacing is encountered (unsupported).
36
+ """
37
+ from dataclasses import replace
38
+
39
+ assert metadata.spacing is not None, (
40
+ "SpacingToScaleTransformer requires spacing, but metadata does not provide it. "
41
+ "Make sure to use a suitable reader, or provide the metadata yourself."
42
+ )
43
+ assert (
44
+ accessor.coordinate_spacing is not None
45
+ ), "SpacingToScaleTransformer requires accessor.coordinate_spacing."
46
+ assert accessor.spacing is not None, "SpacingToScaleTransformer requires accessor.spacing."
47
+
48
+ accessor = replace(accessor)
49
+ # Compute the scale
50
+ image_spacing = metadata.spacing
51
+ if isinstance(image_spacing, (list, tuple)):
52
+
53
+ assert all(image_spacing[0] == i for i in image_spacing), (
54
+ "SpacingToScaleTransformer does currently not support anisotropic "
55
+ f"image spacing (got {image_spacing}). PRs welcome."
56
+ )
57
+ image_spacing = image_spacing[0]
58
+
59
+ accessor.scale = image_spacing / accessor.spacing
60
+ accessor.x = self._scale_coordinate(
61
+ coordinate=accessor.x, input_spacing=accessor.coordinate_spacing, output_spacing=image_spacing
62
+ )
63
+ accessor.y = self._scale_coordinate(
64
+ coordinate=accessor.y, input_spacing=accessor.coordinate_spacing, output_spacing=image_spacing
65
+ )
66
+
67
+ return accessor
68
+
69
+ def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
70
+ """Return metadata unchanged."""
71
+ from dataclasses import replace
72
+
73
+ metadata = replace(metadata)
74
+
75
+ return metadata
76
+
77
+ def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
78
+ """
79
+ Return the image unchanged.
80
+
81
+ Args:
82
+ image (np.ndarray): The input image.
83
+ metadata (ImageMetadata): The image metadata.
84
+ accessor (ImageAccessor): The accessor used for this transformation.
85
+
86
+ Returns:
87
+ np.ndarray: The unchanged image.
88
+ """
89
+ return image
90
+
91
+ @classmethod
92
+ def _scale_coordinate(
93
+ cls,
94
+ coordinate: int | tuple[int, ...],
95
+ input_spacing: float,
96
+ output_spacing: float,
97
+ ) -> int | tuple[int, ...]:
98
+ """
99
+ Scale a coordinate from one spacing system to another.
100
+
101
+ Args:
102
+ coordinate (int | tuple[int, ...] | None): The coordinate to scale.
103
+ input_spacing (float): The input spacing value.
104
+ output_spacing (float): The output spacing value.
105
+
106
+ Returns:
107
+ int | tuple[int, ...] | None: The scaled coordinate, or None if not provided.
108
+ """
109
+ if coordinate is None:
110
+ # Read entire image, no change needed with different coordinate.
111
+ return coordinate
112
+ elif isinstance(coordinate, int):
113
+ return int(math.ceil(coordinate * input_spacing / output_spacing))
114
+ else:
115
+ # assume tuple
116
+ return tuple(
117
+ cls._scale_coordinate(coordinate_i, input_spacing=input_spacing, output_spacing=output_spacing)
118
+ for coordinate_i in coordinate
119
+ )
120
+
121
+
122
+ class FractionTransformer(Transformer):
123
+ """
124
+ Transformer that converts fractional coordinates into absolute pixel coordinates
125
+ based on the metadata shape.
126
+ """
127
+
128
+ def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
129
+ """
130
+ Scale accessor coordinates from fractions of image dimensions to absolute pixel positions.
131
+
132
+ Args:
133
+ accessor (ImageAccessor): The ImageAccessor to transform.
134
+ metadata (ImageMetadata): The metadata providing the image shape.
135
+
136
+ Returns:
137
+ ImageAccessor: A new accessor with scaled coordinates.
138
+
139
+ Raises:
140
+ AssertionError: If `metadata.shape` is missing.
141
+ """
142
+ from dataclasses import replace
143
+
144
+ assert metadata.shape is not None, "FractionTransformer requires metadata.shape."
145
+
146
+ accessor = replace(accessor)
147
+ # Note the correct the dimensions for x and y.
148
+ accessor.x = self._scale_coordinate(accessor.x, metadata.shape[1])
149
+ accessor.y = self._scale_coordinate(accessor.y, metadata.shape[0])
150
+ if len(metadata.shape) > 2:
151
+ accessor.z = self._scale_coordinate(accessor.z, metadata.shape[2])
152
+ if len(metadata.shape) > 3:
153
+ accessor.c = self._scale_coordinate(accessor.c, metadata.shape[3])
154
+
155
+ # In case there is a spacing provided, the coordinates are now given in this spacing.
156
+ accessor.coordinate_spacing = metadata.spacing
157
+
158
+ return accessor
159
+
160
+ def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
161
+ """
162
+ Return metadata unchanged.
163
+
164
+ Args:
165
+ metadata (ImageMetadata): The metadata to process.
166
+
167
+ Returns:
168
+ ImageMetadata: The unchanged metadata.
169
+ """
170
+ from dataclasses import replace
171
+
172
+ metadata = replace(metadata)
173
+
174
+ return metadata
175
+
176
+ def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
177
+ """
178
+ Return the image unchanged.
179
+
180
+ Args:
181
+ image (np.ndarray): The input image.
182
+ metadata (ImageMetadata): The image metadata.
183
+ accessor (ImageAccessor): The accessor used for this transformation.
184
+
185
+ Returns:
186
+ np.ndarray: The unchanged image.
187
+ """
188
+ return image
189
+
190
+ @classmethod
191
+ def _scale_coordinate(
192
+ cls,
193
+ fraction: int | float | tuple[int | float, ...],
194
+ image_dimension: int,
195
+ ) -> int | tuple[int, ...]:
196
+ """
197
+ Scale a fractional coordinate into an absolute pixel coordinate.
198
+
199
+ Args:
200
+ fraction (int | float | tuple[int | float, ...] | None): Fraction(s) of the dimension.
201
+ image_dimension (int): The corresponding image dimension length.
202
+
203
+ Returns:
204
+ int | tuple[int, ...] | None: The scaled coordinate as an int, tuple of ints, or None.
205
+ """
206
+ import math
207
+
208
+ if isinstance(fraction, (int, float)):
209
+ # scale dimension by fraction
210
+ return math.ceil(image_dimension * fraction)
211
+ elif fraction is None:
212
+ # leave untouched
213
+ return fraction
214
+ else:
215
+ # scale each coordinate
216
+ return tuple(cls._scale_coordinate(fraction_i, image_dimension) for fraction_i in fraction)
@@ -0,0 +1,341 @@
1
+ """
2
+ Affine transformers.
3
+ """
4
+
5
+ import logging
6
+ from itertools import product, repeat
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+ from tiamat.constants import OPENCV_INTERPOLATION_CODES
12
+
13
+ from ..io import ImageAccessor
14
+ from ..metadata import ImageMetadata
15
+ from .protocol import Transformer
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class AffineTransformer(Transformer):
21
+ """
22
+ Transformer that applies affine transformations to images and metadata.
23
+
24
+ Supports affine transformations in 2D using a (3, 3) or (2, 3) matrix.
25
+ - `transform_access` modifies the accessor to request the correct input region.
26
+ - `transform_metadata` updates metadata dimensions after the transform.
27
+ - `transform_image` resamples the image using OpenCV warpAffine.
28
+ """
29
+
30
+ # TODO: define a unit of affine matrix, e.g. microns, mm, ...
31
+ # TODO: allow to use center-pixel / corner-pixel aligned affine
32
+ def __init__(
33
+ self,
34
+ affine_matrix: np.ndarray | list[list[float]],
35
+ request_margin: int = 2,
36
+ fill_value: int | float | None = None,
37
+ ):
38
+ """
39
+ Initialize an AffineTransformer.
40
+
41
+ Args:
42
+ affine_matrix: 2x3 or 3x3 affine matrix (list or numpy array).
43
+ request_margin: Pixel margin around requested image to avoid resampling artifacts.
44
+ fill_value: Value used for filling empty regions after transformation.
45
+ """
46
+
47
+ self.affine_matrix = np.array(affine_matrix)
48
+
49
+ # If affine is of shape (2, 3), extent to its (3, 3) form
50
+ if self.affine_matrix.shape == (2, 3):
51
+ self.affine_matrix = np.vstack((self.affine_matrix, [0.0, 0.0, 1.0]))
52
+
53
+ # Pixel margin around requested image to avoid resampling artifacts
54
+ self.request_margin = request_margin
55
+
56
+ self.fill_value = fill_value
57
+
58
+ def _make_corner_px_affine(self, affine: np.ndarray) -> np.ndarray:
59
+ """
60
+ Convert affine matrix to corner pixel aligned form.
61
+
62
+ Args:
63
+ affine: The affine matrix.
64
+
65
+ Returns:
66
+ Corner pixel aligned affine matrix.
67
+ """
68
+ input_offset = np.eye(3)
69
+ input_offset[:2, -1] = (0.5, 0.5)
70
+
71
+ target_offset = np.eye(3)
72
+ target_offset[:2, -1] = (-0.5, -0.5)
73
+
74
+ return target_offset @ affine @ input_offset
75
+
76
+ def _transform_point(self, x: int | float, y: int | float, affine: np.ndarray) -> tuple[int | float, int | float]:
77
+ """
78
+ Transform a point using an affine matrix.
79
+
80
+ Args:
81
+ x: X coordinate.
82
+ y: Y coordinate.
83
+ affine: Affine matrix.
84
+
85
+ Returns:
86
+ Transformed (x, y) coordinates.
87
+ """
88
+ return affine[:2, :2] @ (x, y) + affine[:2, -1]
89
+
90
+ def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
91
+ """
92
+ Transform the accessor so that the correct input region is read before affine warping.
93
+
94
+ Args:
95
+ accessor: The ImageAccessor to transform.
96
+ metadata: The metadata.
97
+
98
+ Returns:
99
+ A new ImageAccessor with adjusted coordinates and history.
100
+
101
+ Raises:
102
+ AssertionError: If metadata is missing.
103
+ """
104
+ import math
105
+ from dataclasses import replace
106
+
107
+ from tiamat.readers.processing import _prepare_coordinates
108
+ from tiamat.transformers.coordinates import resolve_coordinate_slice
109
+
110
+ target_spacing = metadata.spacing
111
+ target_spacing = np.array(target_spacing) if target_spacing is not None else np.array((1.0, 1.0))
112
+ if target_spacing.size == 1:
113
+ target_spacing = np.array([target_spacing, target_spacing])
114
+ target_spacing = target_spacing[:2] # TODO: general solution for 3D
115
+
116
+ # Invert affine to compute source coordinates
117
+ affine = np.linalg.inv(self.affine_matrix)
118
+ affine[:2, -1] = affine[:2, -1] / target_spacing # Convert translation to pixel coordinates
119
+
120
+ coordinate_scale = np.array(accessor.coordinate_scale)
121
+ if coordinate_scale.size == 1:
122
+ coordinate_scale = np.array([coordinate_scale, coordinate_scale])
123
+
124
+ prepared_coordinates = _prepare_coordinates(x=accessor.x, y=accessor.y, coordinate_scale=coordinate_scale)
125
+ x, y = prepared_coordinates["x"], prepared_coordinates["y"]
126
+
127
+ spatial_dims = metadata.spatial_dimensions
128
+ x_from, x_to = resolve_coordinate_slice(x, metadata.shape[spatial_dims[-1]])
129
+ y_from, y_to = resolve_coordinate_slice(y, metadata.shape[spatial_dims[-2]])
130
+
131
+ # Transform all four corners of the frame
132
+ # Assume corner pixel coordinate system
133
+ x1, y1 = self._transform_point(x_from, y_from, affine)
134
+ x2, y2 = self._transform_point(x_to, y_from, affine)
135
+ x3, y3 = self._transform_point(x_to, y_to, affine)
136
+ x4, y4 = self._transform_point(x_from, y_to, affine)
137
+
138
+ scale = np.array(accessor.scale)
139
+ if scale.size == 1:
140
+ scale = np.array([scale, scale])
141
+
142
+ # Scale the margin by self.request_margin to obtain physical extent
143
+ scaled_margin = self.request_margin / scale
144
+
145
+ # Bounding box of transformed coordinates
146
+ x_from_t = min(x1, x2, x3, x4) - scaled_margin[0]
147
+ y_from_t = min(y1, y2, y3, y4) - scaled_margin[1]
148
+ x_to_t = max(x1, x2, x3, x4) + scaled_margin[0]
149
+ y_to_t = max(y1, y2, y3, y4) + scaled_margin[1]
150
+
151
+ # Offset due to rounding
152
+ offset_x_input = math.floor(x_from_t) - x_from_t
153
+ offset_y_input = math.floor(y_from_t) - y_from_t
154
+
155
+ # Replace accessor with new requested input
156
+ accessor = replace(accessor)
157
+ # TODO: Reconsider (math.floor(x_from_t), math.ceil(x_to_t) + 1)
158
+ x_from_input, x_to_input = (math.floor(x_from_t), math.ceil(x_to_t))
159
+ accessor.x = x_from_input, x_to_input
160
+ y_from_input, y_to_input = (math.floor(y_from_t), math.ceil(y_to_t))
161
+ accessor.y = y_from_input, y_to_input
162
+ if self.fill_value is not None:
163
+ accessor.fill_value = self.fill_value
164
+ elif accessor.fill_value is None:
165
+ accessor.fill_value = 0
166
+
167
+ # Affine transformation is always applied at full coordinate scale
168
+ accessor.coordinate_scale = 1.0
169
+
170
+ # Up to here everything is physical coordinates, but in transform_image we need pixel coordinates
171
+ # We need to scale the coordinates to obtain pixel coordinates
172
+ accessor.history[id(self)] = (
173
+ x_from_input,
174
+ y_from_input,
175
+ x_from,
176
+ x_to,
177
+ offset_x_input,
178
+ y_from,
179
+ y_to,
180
+ offset_y_input,
181
+ )
182
+
183
+ return accessor
184
+
185
+ def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
186
+ """
187
+ Transform metadata spatial shape according to the affine transformation.
188
+
189
+ Args:
190
+ metadata: Original metadata.
191
+
192
+ Returns:
193
+ Updated ImageMetadata with transformed shape.
194
+ """
195
+ from dataclasses import replace
196
+
197
+ shape_tuple = metadata.spatial_shape[-2:]
198
+
199
+ # converts shape to extents
200
+ # e.g. shape of 10, 20
201
+ # extents = ((0, 10), (0, 20))
202
+ extents = list(zip(repeat(0), shape_tuple[::-1]))
203
+ extent_coords = list(product(*extents))
204
+
205
+ metadata = replace(metadata)
206
+
207
+ transformed_coords = (self.affine_matrix @ np.vstack((np.array(extent_coords).T, [1, 1, 1, 1])))[:2, :].T
208
+
209
+ out_shape = (
210
+ round(np.max(transformed_coords[:, 1]).item() - np.min(transformed_coords[:, 1]).item()),
211
+ round(np.max(transformed_coords[:, 0]).item() - np.min(transformed_coords[:, 0]).item()),
212
+ )
213
+
214
+ metadata.spatial_shape = (*metadata.spatial_shape[:-2], *out_shape)
215
+
216
+ return metadata
217
+
218
+ def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
219
+ """
220
+ Apply affine transformation to the image using OpenCV.
221
+
222
+ Args:
223
+ image: The Image.
224
+ metadata: The metadata of the image.
225
+ accessor: the accessor of the image.
226
+
227
+ Returns:
228
+ Transformed Image.
229
+
230
+ Raises:
231
+ Exception: If transform_access has not been called first.
232
+ """
233
+ import cv2
234
+
235
+ from tiamat.readers.processing import (
236
+ get_interpolation_for_accessor,
237
+ rescale_shape,
238
+ )
239
+
240
+ target_scale = accessor.scale
241
+ target_scale = np.array(target_scale) if target_scale is not None else np.array((1,))
242
+ if target_scale.size == 1:
243
+ target_scale = np.array([target_scale, target_scale])
244
+ target_scale = target_scale[:2] # TODO: general solution for 3D
245
+
246
+ target_spacing = metadata.spacing
247
+ target_spacing = np.array(target_spacing) if target_spacing is not None else np.array((1.0, 1.0))
248
+ if target_spacing.size == 1:
249
+ target_spacing = np.array([target_spacing, target_spacing])
250
+ target_spacing = target_spacing[:2] # TODO: general solution for 3D
251
+
252
+ # Restore extent from requested frame
253
+ try:
254
+ x_from_input, y_from_input, x_from, x_to, offset_x_input, y_from, y_to, offset_y_input = accessor.history[
255
+ id(self)
256
+ ]
257
+ except KeyError:
258
+ raise Exception("transform_access has to be called once before transform_image")
259
+
260
+ target_shape = rescale_shape(((y_to - y_from), (x_to - x_from)), target_scale)[::-1]
261
+
262
+ # We have to take into account that our input image is not the actual origin of the image.
263
+ # Also, the target image we aim to compute is not at the origin.
264
+ # Subtract and add 0.5 to make the transformation corner aligned (center is default in CV2)
265
+ # To get the result we want, we do the following:
266
+ # 1. Specify an affine matrix shifting towards the origin of the input image
267
+ # 2. Apply our actual affine matrix.
268
+ # 3. Specify an affine matrix shifting towards the origin of the target image.
269
+
270
+ px_affine = self.affine_matrix.copy()
271
+
272
+ # scale translation to pixel coordinates
273
+ px_affine[:2, -1] = px_affine[:2, -1] / target_spacing
274
+
275
+ # Transform affine to pixel coordinates and make it corner pixel aligned
276
+ px_affine[:2, -1] = px_affine[:2, -1] * target_scale
277
+ px_affine = self._make_corner_px_affine(px_affine)
278
+
279
+ # Step 1: Shift towards input.
280
+ input_origin_affine = np.eye(3)
281
+ input_origin_affine[:2, -1] = (x_from_input + offset_x_input, y_from_input + offset_y_input)
282
+ input_origin_affine[:2, -1] = input_origin_affine[:2, -1] * target_scale
283
+
284
+ # Step 3: Shift towards target.
285
+ target_origin_affine = np.eye(3)
286
+ target_origin_affine[:2, -1] = (-x_from, -y_from)
287
+ target_origin_affine[:2, -1] = target_origin_affine[:2, -1] * target_scale
288
+ # Step 1., 2., and 3.
289
+ affine = target_origin_affine @ px_affine @ input_origin_affine
290
+ interpolation = get_interpolation_for_accessor(accessor=accessor, metadata=metadata)
291
+
292
+ if self.fill_value is None:
293
+ if accessor.fill_value is None:
294
+ fill_value = 0
295
+ else:
296
+ fill_value = accessor.fill_value
297
+ else:
298
+ fill_value = self.fill_value
299
+
300
+ def _apply_affine(image):
301
+ return cv2.warpAffine(
302
+ src=image,
303
+ M=affine[:2],
304
+ dsize=target_shape,
305
+ flags=OPENCV_INTERPOLATION_CODES[interpolation],
306
+ borderValue=fill_value,
307
+ )
308
+
309
+ # Apply to image or loop over stack of images if 3 spatial dims
310
+ spatial_dimensions = metadata.spatial_dimensions
311
+ if len(spatial_dimensions) > 2:
312
+ result_imgs = []
313
+ # Loop over first spatial dimension
314
+ for i in range(image.shape[spatial_dimensions[0]]):
315
+ result_imgs.append(_apply_affine(image[i]))
316
+ result_image = np.stack(result_imgs, axis=0)
317
+ image = result_image
318
+ else:
319
+ image = _apply_affine(image)
320
+
321
+ return image
322
+
323
+ @classmethod
324
+ def from_json(cls, args: dict[str, Any]) -> "AffineTransformer":
325
+ """
326
+ Create an AffineTransformer from a JSON-style dictionary.
327
+
328
+ Args:
329
+ args: Dictionary with keys:
330
+ - `affine_matrix`: 2x3 or 3x3 matrix
331
+ - optional `request_margin`: int
332
+ - optional `fill_value`: float
333
+
334
+ Returns:
335
+ AffineTransformer instance.
336
+ """
337
+ return cls(
338
+ affine_matrix=np.array(args["affine_matrix"]),
339
+ request_margin=args.get("request_margin", 2),
340
+ fill_value=args.get("fill_value"),
341
+ )