tiamat-python 0.1.12__tar.gz → 0.1.15__tar.gz
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_python-0.1.12 → tiamat_python-0.1.15}/PKG-INFO +1 -1
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/metadata/metadata.py +42 -2
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/pipeline.py +10 -4
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/processing.py +7 -3
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/stack.py +8 -1
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/zarr.py +38 -29
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/serialization.py +10 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/color.py +22 -4
- tiamat_python-0.1.15/tiamat/transformers/intensity_mapping.py +288 -0
- tiamat_python-0.1.15/tiamat/transformers/mask.py +108 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/normalization.py +2 -4
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat_python.egg-info/PKG-INFO +1 -1
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat_python.egg-info/SOURCES.txt +2 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/LICENSE +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/README.md +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/README.rst +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/pyproject.toml +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/setup.cfg +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/setup.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tests/test_metadata.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tests/test_package.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/__init__.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/array.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/cache.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/cli.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/constants.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/errors.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/io.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/metadata/__init__.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/metadata/dimensions.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/__init__.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/factory.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/generic.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/memory.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/nifti.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/pipeline.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/readers/protocol.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/__init__.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/access.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/affine.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/axes.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/coordinates.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/dfield.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/metadata.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/protocol.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat/transformers/view.py +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat_python.egg-info/dependency_links.txt +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat_python.egg-info/entry_points.txt +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat_python.egg-info/requires.txt +0 -0
- {tiamat_python-0.1.12 → tiamat_python-0.1.15}/tiamat_python.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tiamat-python
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.15
|
|
4
4
|
Summary: Tiled Image Access, Manipulation, and Analysis Toolkit
|
|
5
5
|
Author-email: "Big Data Analytics Group, Forschungszentrum Juelich, Institute of Neuroscience and Medicine (INM-1)" <inm1-bda@fz-juelich.de>
|
|
6
6
|
License:
|
|
@@ -3,8 +3,9 @@ Metadata on images.
|
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
5
|
from collections.abc import Iterable
|
|
6
|
-
from dataclasses import dataclass, field
|
|
6
|
+
from dataclasses import dataclass, field, fields
|
|
7
7
|
from itertools import product, repeat
|
|
8
|
+
from typing import Any, Mapping
|
|
8
9
|
|
|
9
10
|
import numpy as np
|
|
10
11
|
|
|
@@ -138,7 +139,7 @@ class ImageMetadata:
|
|
|
138
139
|
file_path: Iterable[str] | str | None = None
|
|
139
140
|
spacing: float | tuple[float, ...] | None = None
|
|
140
141
|
additional_metadata: dict = field(default_factory=dict)
|
|
141
|
-
scales: float | int | Iterable[float | int] | None = None
|
|
142
|
+
scales: float | int | Iterable[float | int] | Iterable[tuple[float | int, ...]] | None = None
|
|
142
143
|
|
|
143
144
|
@property
|
|
144
145
|
def spatial_dimensions(self):
|
|
@@ -204,3 +205,42 @@ class ImageMetadata:
|
|
|
204
205
|
|
|
205
206
|
def __str__(self):
|
|
206
207
|
return self.__repr__()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _convert_metadata_value(key: str, value: Any) -> Any:
|
|
211
|
+
"""Convert metadata values to match ImageMetadata field conventions."""
|
|
212
|
+
if key in {"shape", "value_range", "dimensions", "spacing"}:
|
|
213
|
+
if isinstance(value, list):
|
|
214
|
+
return tuple(value)
|
|
215
|
+
|
|
216
|
+
if key == "dtype":
|
|
217
|
+
if isinstance(value, str):
|
|
218
|
+
return np.dtype(value)
|
|
219
|
+
|
|
220
|
+
if key == "scales":
|
|
221
|
+
if isinstance(value, list):
|
|
222
|
+
if value and all(isinstance(v, (list, tuple)) for v in value):
|
|
223
|
+
return [tuple(v) for v in value]
|
|
224
|
+
|
|
225
|
+
return value
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def update_metadata_from_dict(
|
|
229
|
+
image_metadata: ImageMetadata,
|
|
230
|
+
update_dict: Mapping[str, Any],
|
|
231
|
+
) -> ImageMetadata:
|
|
232
|
+
"""
|
|
233
|
+
Update an ImageMetadata instance from a dict.
|
|
234
|
+
|
|
235
|
+
Matching keys update dataclass fields; unknown keys are stored in
|
|
236
|
+
``additional_metadata``.
|
|
237
|
+
"""
|
|
238
|
+
valid_fields = {f.name for f in fields(image_metadata)}
|
|
239
|
+
|
|
240
|
+
for key, value in update_dict.items():
|
|
241
|
+
if key in valid_fields:
|
|
242
|
+
setattr(image_metadata, key, _convert_metadata_value(key, value))
|
|
243
|
+
else:
|
|
244
|
+
image_metadata.additional_metadata[key] = value
|
|
245
|
+
|
|
246
|
+
return image_metadata
|
|
@@ -5,10 +5,10 @@ Helper functions for running a tiamat processing pipeline.
|
|
|
5
5
|
from __future__ import annotations
|
|
6
6
|
|
|
7
7
|
from collections.abc import Callable, Iterable
|
|
8
|
-
from typing import Any
|
|
8
|
+
from typing import Any, Mapping
|
|
9
9
|
|
|
10
10
|
from .io import ImageAccessor, ImageResult
|
|
11
|
-
from .metadata import ImageMetadata
|
|
11
|
+
from .metadata import ImageMetadata, update_metadata_from_dict
|
|
12
12
|
from .readers.factory import get_reader
|
|
13
13
|
from .readers.protocol import ImageReader
|
|
14
14
|
from .transformers.protocol import Transformer
|
|
@@ -29,6 +29,7 @@ class Pipeline:
|
|
|
29
29
|
image_transformers: Iterable[Transformer] | None = None,
|
|
30
30
|
reader_factory: Callable[[str], ImageReader] | None = None,
|
|
31
31
|
auto_register_default_readers: bool = True,
|
|
32
|
+
metadata_overrides: Mapping[str, Any] | None = None,
|
|
32
33
|
):
|
|
33
34
|
"""
|
|
34
35
|
Initializes the Pipeline.
|
|
@@ -41,6 +42,8 @@ class Pipeline:
|
|
|
41
42
|
Cannot be used together with `transformers`.
|
|
42
43
|
reader_factory (Callable[[str], ImageReader] | None): Function returning a reader for a given file name.
|
|
43
44
|
auto_register_default_readers (bool): Whether to auto-register default readers on pipeline call.
|
|
45
|
+
metadata_overrides (Mapping[str, Any] | None): Optional metadata values that override or extend
|
|
46
|
+
metadata returned by the reader. Unknown keys are stored in ``additional_metadata``.
|
|
44
47
|
"""
|
|
45
48
|
if transformers:
|
|
46
49
|
assert (
|
|
@@ -60,6 +63,8 @@ class Pipeline:
|
|
|
60
63
|
self.reader_factory = reader_factory or get_reader
|
|
61
64
|
self.auto_register_default_readers = auto_register_default_readers
|
|
62
65
|
|
|
66
|
+
self.metadata_overrides = metadata_overrides if metadata_overrides is not None else {}
|
|
67
|
+
|
|
63
68
|
def __call__(
|
|
64
69
|
self,
|
|
65
70
|
file_name: str,
|
|
@@ -87,7 +92,7 @@ class Pipeline:
|
|
|
87
92
|
reader = self.reader_factory(file_name, **reader_kwargs)
|
|
88
93
|
|
|
89
94
|
# Forward rollout of metadata through transformers
|
|
90
|
-
metadata = [reader.read_metadata()]
|
|
95
|
+
metadata = [update_metadata_from_dict(reader.read_metadata(), self.metadata_overrides)]
|
|
91
96
|
|
|
92
97
|
for transformer in self.transformers:
|
|
93
98
|
# Check for transformers that do not implement transform_metadata
|
|
@@ -135,10 +140,11 @@ class Pipeline:
|
|
|
135
140
|
from dataclasses import replace
|
|
136
141
|
|
|
137
142
|
reader = self.reader_factory(file_name, **reader_kwargs)
|
|
138
|
-
metadata = reader.read_metadata()
|
|
143
|
+
metadata = update_metadata_from_dict(reader.read_metadata(), self.metadata_overrides)
|
|
139
144
|
# backwards pass through the transformers to transform the accessor
|
|
140
145
|
for transformer in self.transformers:
|
|
141
146
|
if hasattr(transformer, "transform_metadata"):
|
|
142
147
|
# check for transformers that do not implement transform_metadata
|
|
143
148
|
metadata = transformer.transform_metadata(metadata=replace(metadata))
|
|
149
|
+
|
|
144
150
|
return metadata
|
|
@@ -49,9 +49,13 @@ def expand_to_length(value: Any, length: int) -> list[Any]:
|
|
|
49
49
|
Returns:
|
|
50
50
|
List of length `length`.
|
|
51
51
|
"""
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
52
|
+
|
|
53
|
+
if np.ndim(value) == 0:
|
|
54
|
+
if isinstance(value, np.ndarray):
|
|
55
|
+
return [value.item()] * length
|
|
56
|
+
else:
|
|
57
|
+
return [value] * length
|
|
58
|
+
if len(value) == 1:
|
|
55
59
|
return [value[0]] * length
|
|
56
60
|
return value
|
|
57
61
|
|
|
@@ -187,7 +187,9 @@ class ImageStackReader(ImageReader):
|
|
|
187
187
|
"""
|
|
188
188
|
from tiamat.readers.processing import expand_to_length
|
|
189
189
|
|
|
190
|
-
if
|
|
190
|
+
if hasattr(spacing, "__len__") and len(spacing) == 3:
|
|
191
|
+
return spacing
|
|
192
|
+
elif slice_spacing is None:
|
|
191
193
|
spacing_2d = expand_to_length(spacing, 2)
|
|
192
194
|
assert (
|
|
193
195
|
spacing_2d[0] == spacing_2d[1]
|
|
@@ -768,6 +770,10 @@ class VolumeStackReader(ImageReader):
|
|
|
768
770
|
# Size of the current subvolume
|
|
769
771
|
z_size = shape[z_dim]
|
|
770
772
|
|
|
773
|
+
# Everything read
|
|
774
|
+
if coverage_offset >= z_to:
|
|
775
|
+
break
|
|
776
|
+
|
|
771
777
|
# Access only required subvolumes that lay in the accessor range and are not covered yet
|
|
772
778
|
if volume_z_offset + z_size > coverage_offset and volume_z_offset < z_to:
|
|
773
779
|
|
|
@@ -777,6 +783,7 @@ class VolumeStackReader(ImageReader):
|
|
|
777
783
|
|
|
778
784
|
# Access subvolume and read from it
|
|
779
785
|
tmp_accessor = replace(accessor, z=(from_ix, to_ix))
|
|
786
|
+
|
|
780
787
|
tmp_image = handle.read_image(accessor=tmp_accessor)
|
|
781
788
|
|
|
782
789
|
# Position result in the output array
|
|
@@ -25,10 +25,10 @@ from tiamat.io import ImageAccessor
|
|
|
25
25
|
from tiamat.metadata import ImageMetadata
|
|
26
26
|
from tiamat.readers.protocol import ImageReader
|
|
27
27
|
|
|
28
|
-
|
|
29
28
|
# retrieved from https://ngff.openmicroscopy.org/specifications/0.5/index.html#axes-metadata
|
|
30
29
|
# on 2026-03-05
|
|
31
30
|
|
|
31
|
+
|
|
32
32
|
class SiUnit(NamedTuple):
|
|
33
33
|
symbol: str
|
|
34
34
|
exponent: int
|
|
@@ -258,9 +258,7 @@ class OmeZarrReader(ImageReader):
|
|
|
258
258
|
@cached_property
|
|
259
259
|
def _kvstore(self):
|
|
260
260
|
if not _TENSORSTORE_AVAILABLE:
|
|
261
|
-
raise ImportError(
|
|
262
|
-
"tensorstore is not installed. Install `tensorstore` to read OME-Zarr data."
|
|
263
|
-
)
|
|
261
|
+
raise ImportError("tensorstore is not installed. Install `tensorstore` to read OME-Zarr data.")
|
|
264
262
|
return ts.KvStore.open(self._kvstore_spec).result()
|
|
265
263
|
|
|
266
264
|
@cached_property
|
|
@@ -346,40 +344,51 @@ class OmeZarrReader(ImageReader):
|
|
|
346
344
|
|
|
347
345
|
@cached_property
|
|
348
346
|
def pixel_spacing(self) -> tuple[float, ...]:
|
|
349
|
-
|
|
347
|
+
return tuple(self._dataset_physical_scales(0))
|
|
348
|
+
|
|
349
|
+
def _scale_transform_for_dataset(self, level: int) -> list[float]:
|
|
350
|
+
transforms = self._datasets[level].get("coordinateTransformations", [])
|
|
351
|
+
for transform in transforms or []:
|
|
352
|
+
if isinstance(transform, dict) and transform.get("type") == "scale":
|
|
353
|
+
scale = transform.get("scale")
|
|
354
|
+
if isinstance(scale, list) and len(scale) == len(self.axes_names):
|
|
355
|
+
return [float(x) for x in scale]
|
|
356
|
+
raise ValueError(f"OME-Zarr dataset at level {level} is missing a valid scale transformation.")
|
|
357
|
+
|
|
358
|
+
@cached_property
|
|
359
|
+
def _axis_unit_factors(self) -> list[float]:
|
|
360
|
+
axis_entries = self._pyramid.get("axes")
|
|
361
|
+
if not isinstance(axis_entries, list) or len(axis_entries) != len(self.axes_names):
|
|
362
|
+
return [1.0] * len(self.axes_names)
|
|
363
|
+
|
|
364
|
+
factors: list[float] = []
|
|
365
|
+
for axis in axis_entries:
|
|
366
|
+
if not isinstance(axis, dict):
|
|
367
|
+
factors.append(1.0)
|
|
368
|
+
continue
|
|
369
|
+
|
|
370
|
+
if axis.get("type") != "space":
|
|
371
|
+
factors.append(1.0)
|
|
372
|
+
continue
|
|
350
373
|
|
|
351
|
-
mul_factor: list[float] = []
|
|
352
|
-
for axis in self._pyramid.get("axes", []):
|
|
353
374
|
unit = axis.get("unit")
|
|
354
375
|
if factor := spatial_units_to_micron.get(unit):
|
|
355
|
-
|
|
376
|
+
factors.append(factor)
|
|
356
377
|
else:
|
|
357
378
|
raise RuntimeError(f"zarr unit {unit} either not recognized or factor not yet encoded.")
|
|
358
379
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
scale_vec = [float(x) * factor for x, factor in zip(scale, mul_factor)]
|
|
366
|
-
break
|
|
367
|
-
if scale_vec is None:
|
|
368
|
-
return tuple([1.0] * len(axes))
|
|
369
|
-
return tuple(scale_vec)
|
|
380
|
+
return factors
|
|
381
|
+
|
|
382
|
+
@instance_cache
|
|
383
|
+
def _dataset_physical_scales(self, level: int) -> list[float]:
|
|
384
|
+
scale = self._scale_transform_for_dataset(level)
|
|
385
|
+
return [axis_scale * factor for axis_scale, factor in zip(scale, self._axis_unit_factors)]
|
|
370
386
|
|
|
371
387
|
@instance_cache
|
|
372
388
|
def _level_factors(self, level: int) -> list[float]:
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
spatial = {"z", "y", "x"}
|
|
377
|
-
for i, axis_name in enumerate(self.axes_names):
|
|
378
|
-
if axis_name in spatial:
|
|
379
|
-
factors.append(float(cur[i]) / float(base[i]))
|
|
380
|
-
else:
|
|
381
|
-
factors.append(1.0)
|
|
382
|
-
return factors
|
|
389
|
+
base_scale = self._dataset_physical_scales(0)
|
|
390
|
+
level_scale = self._dataset_physical_scales(level)
|
|
391
|
+
return [float(base) / float(current) for base, current in zip(base_scale, level_scale)]
|
|
383
392
|
|
|
384
393
|
@cached_property
|
|
385
394
|
def scales(self) -> list[tuple[float, ...]]:
|
|
@@ -14,6 +14,9 @@ from tiamat.readers.protocol import ImageReader
|
|
|
14
14
|
class_registry: dict[str, type] = {}
|
|
15
15
|
|
|
16
16
|
|
|
17
|
+
pipeline_keys = ["transformers", "access_transformers", "image_transformers", "reader", "reader_factory"]
|
|
18
|
+
|
|
19
|
+
|
|
17
20
|
def register_class(cls: type) -> type:
|
|
18
21
|
"""
|
|
19
22
|
Decorator to register a class for safe instantiation from configuration.
|
|
@@ -142,6 +145,12 @@ def load_pipeline_from_config(
|
|
|
142
145
|
|
|
143
146
|
register_all_readers()
|
|
144
147
|
|
|
148
|
+
metadata_overrides = {k: config[k] for k in set(config) - set(pipeline_keys)}
|
|
149
|
+
|
|
150
|
+
# Resolve confusion between reader_factory and reader args
|
|
151
|
+
if "reader_factory" in config.keys():
|
|
152
|
+
config["reader"] = config["reader_factory"]
|
|
153
|
+
|
|
145
154
|
return Pipeline(
|
|
146
155
|
transformers=[make_object_from_config(item) for item in config.get("transformers", [])],
|
|
147
156
|
access_transformers=[make_object_from_config(item) for item in config.get("access_transformers", [])],
|
|
@@ -150,4 +159,5 @@ def load_pipeline_from_config(
|
|
|
150
159
|
config.get("reader", None), reader_post_creation_hook=reader_post_creation_hook
|
|
151
160
|
),
|
|
152
161
|
auto_register_default_readers=False,
|
|
162
|
+
metadata_overrides=metadata_overrides,
|
|
153
163
|
)
|
|
@@ -14,15 +14,27 @@ class LUTTransformer(Transformer):
|
|
|
14
14
|
Apply a look-up table (LUT) or color map to an image.
|
|
15
15
|
"""
|
|
16
16
|
|
|
17
|
-
def __init__(
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
color_map: str | np.ndarray | list | tuple,
|
|
20
|
+
vmin: float | None = None,
|
|
21
|
+
vmax: float | None = None,
|
|
22
|
+
) -> None:
|
|
18
23
|
"""
|
|
19
24
|
Initialize a LUTTransformer.
|
|
20
25
|
|
|
21
26
|
Args:
|
|
22
27
|
color_map: Colormap to apply. Can be a string (matplotlib name), numpy array,
|
|
23
28
|
list, or tuple.
|
|
29
|
+
vmin: Optional lower bound used for normalization when `color_map` is a
|
|
30
|
+
matplotlib colormap name. If `None`, metadata.value_range[0] is used.
|
|
31
|
+
vmax: Optional upper bound used for normalization when `color_map` is a
|
|
32
|
+
matplotlib colormap name. If `None`, metadata.value_range[1] is used.
|
|
24
33
|
"""
|
|
34
|
+
|
|
25
35
|
self.color_map = color_map
|
|
36
|
+
self.vmin = vmin
|
|
37
|
+
self.vmax = vmax
|
|
26
38
|
|
|
27
39
|
def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
|
|
28
40
|
"""
|
|
@@ -49,9 +61,16 @@ class LUTTransformer(Transformer):
|
|
|
49
61
|
Returns:
|
|
50
62
|
Color-mapped image as ndarray.
|
|
51
63
|
"""
|
|
52
|
-
|
|
64
|
+
if self.vmin is None or self.vmax is None:
|
|
65
|
+
assert metadata.value_range is not None, "LUTTransformer requires metadata.value_range."
|
|
66
|
+
metadata_vmin, metadata_vmax = metadata.value_range
|
|
67
|
+
else:
|
|
68
|
+
metadata_vmin, metadata_vmax = (None, None)
|
|
69
|
+
|
|
70
|
+
vmin = self.vmin if self.vmin is not None else metadata_vmin
|
|
71
|
+
vmax = self.vmax if self.vmax is not None else metadata_vmax
|
|
53
72
|
|
|
54
|
-
image = self._apply_color_map(image=image, value_range=
|
|
73
|
+
image = self._apply_color_map(image=image, value_range=(vmin, vmax))
|
|
55
74
|
|
|
56
75
|
return image
|
|
57
76
|
|
|
@@ -109,7 +128,6 @@ class LUTTransformer(Transformer):
|
|
|
109
128
|
metadata.dtype = np.asarray(self.color_map).dtype
|
|
110
129
|
ldim = len(self.color_map[0])
|
|
111
130
|
if isinstance(self.color_map, np.ndarray):
|
|
112
|
-
print(self.color_map)
|
|
113
131
|
metadata.value_range = (np.min(self.color_map).item(), np.max(self.color_map).max().item())
|
|
114
132
|
else:
|
|
115
133
|
metadata.value_range = (min(self.color_map), max(self.color_map))
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module containing transformers for intensity mapping of images.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
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 MappingTransformer(Transformer):
|
|
15
|
+
"""
|
|
16
|
+
Pointwise intensity mapping defined by a mathematical function.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
mapping_function: Callable[[np.ndarray | float], np.ndarray | float],
|
|
22
|
+
target_dtype: type[np.floating] = np.float32,
|
|
23
|
+
) -> None:
|
|
24
|
+
"""
|
|
25
|
+
Initialize the transformer.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
mapping_function: Callable used to map both image values and metadata
|
|
29
|
+
range bounds.
|
|
30
|
+
target_dtype: Floating point dtype for the mapped image.
|
|
31
|
+
Defaults to np.float32.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
self.mapping_function = mapping_function
|
|
35
|
+
self.target_dtype = target_dtype
|
|
36
|
+
|
|
37
|
+
def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
|
|
38
|
+
"""
|
|
39
|
+
No changes to the accessor are needed for intensity mapping.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
accessor: ImageAccessor of the target image.
|
|
43
|
+
metadata: Metadata of the target image.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
The unmodified ImageAccessor.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
return accessor
|
|
50
|
+
|
|
51
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
52
|
+
"""
|
|
53
|
+
Update metadata to reflect intensity mapping.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
metadata: Original ImageMetadata.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Updated ImageMetadata with dtype set to target_dtype and value_range mapped
|
|
60
|
+
through the transform function.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
from dataclasses import replace
|
|
64
|
+
|
|
65
|
+
metadata = replace(metadata)
|
|
66
|
+
|
|
67
|
+
metadata.dtype = self.target_dtype
|
|
68
|
+
assert metadata.value_range is not None, f"{type(self).__name__} requires metadata.value_range."
|
|
69
|
+
metadata.value_range = self._map_value_range(metadata.value_range)
|
|
70
|
+
|
|
71
|
+
return metadata
|
|
72
|
+
|
|
73
|
+
def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
|
|
74
|
+
"""
|
|
75
|
+
Apply pointwise intensity mapping to the image.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
image: Image to transform.
|
|
79
|
+
metadata: Metadata of the image.
|
|
80
|
+
accessor: Accessor to the image.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
np.ndarray: Mapped image.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
transformed_image = self._map_array(image)
|
|
87
|
+
return transformed_image.astype(self.target_dtype)
|
|
88
|
+
|
|
89
|
+
def _map_value_range(self, value_range: tuple[float, float]) -> tuple[float, float]:
|
|
90
|
+
"""Map the metadata value range through the transform function."""
|
|
91
|
+
|
|
92
|
+
vmin, vmax = value_range
|
|
93
|
+
return (self._map_scalar(vmin), self._map_scalar(vmax))
|
|
94
|
+
|
|
95
|
+
def _map_array(self, image: np.ndarray) -> np.ndarray:
|
|
96
|
+
"""Map the image values through the transform function."""
|
|
97
|
+
|
|
98
|
+
return self.mapping_function(image)
|
|
99
|
+
|
|
100
|
+
def _map_scalar(self, value: float) -> float:
|
|
101
|
+
"""Map a scalar through the transform function."""
|
|
102
|
+
|
|
103
|
+
return self.mapping_function(value)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# maybe only in tiamat-openseadragon?
|
|
107
|
+
# Commen used functions
|
|
108
|
+
class LogIntensityMappingTransformer(MappingTransformer):
|
|
109
|
+
"""
|
|
110
|
+
Map image intensities using a logarithmic response curve.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
target_dtype: type[np.floating] = np.float32,
|
|
116
|
+
) -> None:
|
|
117
|
+
"""Initialize the transformer with a logarithmic mapping."""
|
|
118
|
+
|
|
119
|
+
super().__init__(
|
|
120
|
+
mapping_function=np.log,
|
|
121
|
+
target_dtype=target_dtype,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Log1pIntensityMappingTransformer(MappingTransformer):
|
|
126
|
+
"""
|
|
127
|
+
Map image intensities using a logarithmic response curve with log1p.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
target_dtype: type[np.floating] = np.float32,
|
|
133
|
+
) -> None:
|
|
134
|
+
"""Initialize the transformer with a log1p mapping."""
|
|
135
|
+
|
|
136
|
+
super().__init__(
|
|
137
|
+
mapping_function=np.log1p,
|
|
138
|
+
target_dtype=target_dtype,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class GammaIntensityMappingTransformer(MappingTransformer):
|
|
143
|
+
"""
|
|
144
|
+
Map image intensities using gamma correction.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
def __init__(
|
|
148
|
+
self,
|
|
149
|
+
gamma: float,
|
|
150
|
+
target_dtype: type[np.floating] = np.float32,
|
|
151
|
+
) -> None:
|
|
152
|
+
"""
|
|
153
|
+
Initialize the transformer.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
gamma: Gamma value for correction.
|
|
157
|
+
target_dtype: Floating point dtype for the mapped image.
|
|
158
|
+
Defaults to np.float32.
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
self.gamma = gamma
|
|
162
|
+
super().__init__(
|
|
163
|
+
mapping_function=lambda value: np.power(value, self.gamma),
|
|
164
|
+
target_dtype=target_dtype,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class ClipIntensityMappingTransformer(MappingTransformer):
|
|
169
|
+
"""
|
|
170
|
+
Map image intensities by clipping to a specified range.
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
def __init__(
|
|
174
|
+
self,
|
|
175
|
+
vmin: float,
|
|
176
|
+
vmax: float,
|
|
177
|
+
target_dtype: type[np.floating] = np.float32,
|
|
178
|
+
) -> None:
|
|
179
|
+
"""
|
|
180
|
+
Initialize the transformer.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
vmin: Minimum intensity value for clipping.
|
|
184
|
+
vmax: Maximum intensity value for clipping.
|
|
185
|
+
target_dtype: Floating point dtype for the mapped image.
|
|
186
|
+
Defaults to np.float32.
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
self.vmin = vmin
|
|
190
|
+
self.vmax = vmax
|
|
191
|
+
super().__init__(
|
|
192
|
+
mapping_function=lambda value: np.clip(value, self.vmin, self.vmax),
|
|
193
|
+
target_dtype=target_dtype,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class BrightnessContrastIntensityMappingTransformer(Transformer):
|
|
198
|
+
"""
|
|
199
|
+
Map image intensities using brightness and contrast adjustment.
|
|
200
|
+
"""
|
|
201
|
+
|
|
202
|
+
def __init__(
|
|
203
|
+
self,
|
|
204
|
+
brightness: float = 0.0,
|
|
205
|
+
contrast: float = 1.0,
|
|
206
|
+
target_dtype: type[np.floating] = np.float32,
|
|
207
|
+
) -> None:
|
|
208
|
+
"""
|
|
209
|
+
Initialize the transformer.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
brightness: Additive offset expressed as a fraction of the
|
|
213
|
+
metadata value range.
|
|
214
|
+
contrast: Multiplicative contrast factor around the metadata
|
|
215
|
+
range midpoint.
|
|
216
|
+
target_dtype: Floating point dtype for the mapped image.
|
|
217
|
+
Defaults to np.float32.
|
|
218
|
+
"""
|
|
219
|
+
|
|
220
|
+
self.brightness = brightness
|
|
221
|
+
self.contrast = contrast
|
|
222
|
+
self.target_dtype = target_dtype
|
|
223
|
+
super().__init__(
|
|
224
|
+
mapping_function=lambda value: value,
|
|
225
|
+
target_dtype=target_dtype,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
229
|
+
"""Update metadata to reflect brightness and contrast mapping."""
|
|
230
|
+
|
|
231
|
+
from dataclasses import replace
|
|
232
|
+
|
|
233
|
+
metadata = replace(metadata)
|
|
234
|
+
metadata.dtype = self.target_dtype
|
|
235
|
+
|
|
236
|
+
assert (
|
|
237
|
+
metadata.value_range is not None
|
|
238
|
+
), "BrightnessContrastIntensityMappingTransformer requires metadata.value_range."
|
|
239
|
+
|
|
240
|
+
vmin, vmax = metadata.value_range
|
|
241
|
+
midpoint = (vmin + vmax) / 2.0
|
|
242
|
+
value_range = vmax - vmin
|
|
243
|
+
|
|
244
|
+
mapped_vmin = np.clip(
|
|
245
|
+
(vmin - midpoint) * self.contrast + midpoint + self.brightness * value_range,
|
|
246
|
+
vmin,
|
|
247
|
+
vmax,
|
|
248
|
+
)
|
|
249
|
+
mapped_vmax = np.clip(
|
|
250
|
+
(vmax - midpoint) * self.contrast + midpoint + self.brightness * value_range,
|
|
251
|
+
vmin,
|
|
252
|
+
vmax,
|
|
253
|
+
)
|
|
254
|
+
metadata.value_range = (float(mapped_vmin), float(mapped_vmax))
|
|
255
|
+
|
|
256
|
+
return metadata
|
|
257
|
+
|
|
258
|
+
def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
|
|
259
|
+
"""
|
|
260
|
+
Apply brightness and contrast intensity mapping to the image.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
image: Image to transform.
|
|
264
|
+
metadata: Metadata of the image.
|
|
265
|
+
accessor: Accessor to the image.
|
|
266
|
+
|
|
267
|
+
Returns:
|
|
268
|
+
np.ndarray: Brightness/contrast-mapped image clipped to metadata
|
|
269
|
+
value_range.
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
assert (
|
|
273
|
+
metadata.value_range is not None
|
|
274
|
+
), "BrightnessContrastIntensityMappingTransformer requires metadata.value_range."
|
|
275
|
+
|
|
276
|
+
vmin, vmax = metadata.value_range
|
|
277
|
+
midpoint = (vmin + vmax) / 2.0
|
|
278
|
+
value_range = vmax - vmin
|
|
279
|
+
|
|
280
|
+
# Apply contrast around native midpoint and brightness as a fraction of range,
|
|
281
|
+
# then clip to metadata range.
|
|
282
|
+
self.mapping_function = lambda value: np.clip(
|
|
283
|
+
(value.astype(self.target_dtype) - midpoint) * self.contrast + midpoint + self.brightness * value_range,
|
|
284
|
+
vmin,
|
|
285
|
+
vmax,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
return self.mapping_function(image).astype(self.target_dtype)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Mask 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 ApplyMaskTransformer(Transformer):
|
|
20
|
+
"""Transformer which applies a mask to an image, setting masked pixels to a specified value."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
mask_file: str,
|
|
25
|
+
mask_value: int | float = 0,
|
|
26
|
+
reader_factory: Callable[[str], ImageReader] | None = None,
|
|
27
|
+
):
|
|
28
|
+
"""
|
|
29
|
+
Creates an instance of ApplyMaskTransformer.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
mask_file: Path to the mask file.
|
|
33
|
+
mask_value: Value to set masked pixels to. Defaults to 0.
|
|
34
|
+
reader_factory: Callable returning ImageReader for a given file path.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from tiamat.readers.factory import get_reader
|
|
38
|
+
|
|
39
|
+
self.mask_file = mask_file
|
|
40
|
+
self.mask_value = mask_value
|
|
41
|
+
self.reader_factory = reader_factory or get_reader
|
|
42
|
+
|
|
43
|
+
@instance_cached_property
|
|
44
|
+
def mask_file_handle(self) -> ImageReader:
|
|
45
|
+
"""Return a cached ImageReader for the mask file."""
|
|
46
|
+
return self.reader_factory(self.mask_file)
|
|
47
|
+
|
|
48
|
+
@staticmethod
|
|
49
|
+
def apply_mask(image: np.ndarray, mask: np.ndarray, mask_value: int | float) -> np.ndarray:
|
|
50
|
+
"""Apply the mask to the image, setting masked pixels to mask_value."""
|
|
51
|
+
masked_image = image.copy()
|
|
52
|
+
masked_image[mask == 0] = mask_value
|
|
53
|
+
return masked_image
|
|
54
|
+
|
|
55
|
+
def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
|
|
56
|
+
return accessor
|
|
57
|
+
|
|
58
|
+
def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
|
|
59
|
+
return metadata
|
|
60
|
+
|
|
61
|
+
def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
|
|
62
|
+
|
|
63
|
+
metadata_mask = self.mask_file_handle.read_metadata()
|
|
64
|
+
if metadata.spatial_shape != metadata_mask.spatial_shape:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"Spatial shape mismatch: "
|
|
67
|
+
f"mask={metadata_mask.spatial_shape}, "
|
|
68
|
+
f"image={metadata.spatial_shape}. "
|
|
69
|
+
"It is currently required to match exactly."
|
|
70
|
+
)
|
|
71
|
+
if metadata.spacing != metadata_mask.spacing:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
"Spacing mismatch: "
|
|
74
|
+
f"mask={metadata_mask.spacing}, "
|
|
75
|
+
f"image={metadata.spacing}. "
|
|
76
|
+
"It is currently required to match exactly."
|
|
77
|
+
)
|
|
78
|
+
if metadata.scales != metadata_mask.scales:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
"Scales mismatch: "
|
|
81
|
+
f"mask={metadata_mask.scales}, "
|
|
82
|
+
f"image={metadata.scales}. "
|
|
83
|
+
"It is currently required to match exactly."
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
return self.apply_mask(image, self.mask_file_handle.read_image(accessor), self.mask_value)
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_json(cls, args: dict[str, Any]):
|
|
90
|
+
"""
|
|
91
|
+
Instantiate an ApplyMaskTransformer from a JSON-like dictionary.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
args: Dictionary containing configuration keys:
|
|
95
|
+
- mask_file: Path to the mask file (required).
|
|
96
|
+
- mask_value: Value to set masked pixels to (optional, default=0).
|
|
97
|
+
- reader_factory: Optional configuration for a custom ImageReader factory.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
An instance of ApplyMaskTransformer configured according to args.
|
|
101
|
+
"""
|
|
102
|
+
from tiamat.serialization import get_reader_from_config
|
|
103
|
+
|
|
104
|
+
return cls(
|
|
105
|
+
mask_file=args["mask_file"],
|
|
106
|
+
mask_value=args.get("mask_value", 0),
|
|
107
|
+
reader_factory=get_reader_from_config(args.get("reader_factory")),
|
|
108
|
+
)
|
|
@@ -50,7 +50,6 @@ class MinMaxNormalizationTransformer(Transformer):
|
|
|
50
50
|
from dataclasses import replace
|
|
51
51
|
|
|
52
52
|
metadata = replace(metadata)
|
|
53
|
-
|
|
54
53
|
metadata.dtype = self.target_dtype
|
|
55
54
|
metadata.value_range = (0.0, 1.0)
|
|
56
55
|
|
|
@@ -71,7 +70,6 @@ class MinMaxNormalizationTransformer(Transformer):
|
|
|
71
70
|
assert metadata.value_range is not None, "MinMaxNormalizationTransformer requires metadata.value_range."
|
|
72
71
|
|
|
73
72
|
vmin, vmax = metadata.value_range
|
|
73
|
+
image = (image - vmin) / (vmax - vmin)
|
|
74
74
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
return image
|
|
75
|
+
return image.astype(self.target_dtype)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tiamat-python
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.15
|
|
4
4
|
Summary: Tiled Image Access, Manipulation, and Analysis Toolkit
|
|
5
5
|
Author-email: "Big Data Analytics Group, Forschungszentrum Juelich, Institute of Neuroscience and Medicine (INM-1)" <inm1-bda@fz-juelich.de>
|
|
6
6
|
License:
|
|
@@ -34,6 +34,8 @@ tiamat/transformers/axes.py
|
|
|
34
34
|
tiamat/transformers/color.py
|
|
35
35
|
tiamat/transformers/coordinates.py
|
|
36
36
|
tiamat/transformers/dfield.py
|
|
37
|
+
tiamat/transformers/intensity_mapping.py
|
|
38
|
+
tiamat/transformers/mask.py
|
|
37
39
|
tiamat/transformers/metadata.py
|
|
38
40
|
tiamat/transformers/normalization.py
|
|
39
41
|
tiamat/transformers/protocol.py
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|