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/pipeline.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Helper functions for running a tiamat processing pipeline.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Callable, Iterable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .io import ImageAccessor, ImageResult
|
|
11
|
+
from .metadata import ImageMetadata
|
|
12
|
+
from .readers.factory import get_reader
|
|
13
|
+
from .readers.protocol import ImageReader
|
|
14
|
+
from .transformers.protocol import Transformer
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Pipeline:
|
|
18
|
+
"""
|
|
19
|
+
A processing pipeline to read and transform images.
|
|
20
|
+
|
|
21
|
+
The pipeline first transforms the image accessor (e.g. coordinates),
|
|
22
|
+
reads image data using the appropriate reader, and then applies image transformations.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
transformers: Iterable[Transformer] | None = None,
|
|
28
|
+
access_transformers: Iterable[Transformer] | None = None,
|
|
29
|
+
image_transformers: Iterable[Transformer] | None = None,
|
|
30
|
+
reader_factory: Callable[[str], ImageReader] | None = None,
|
|
31
|
+
auto_register_default_readers: bool = True,
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initializes the Pipeline.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
transformers (Iterable[Transformer] | None): Transformers applied to both access and image.
|
|
38
|
+
access_transformers (Iterable[Transformer] | None): Transformers for modifying image access (coordinates).
|
|
39
|
+
Cannot be used together with `transformers`.
|
|
40
|
+
image_transformers (Iterable[Transformer] | None): Transformers for modifying image data.
|
|
41
|
+
Cannot be used together with `transformers`.
|
|
42
|
+
reader_factory (Callable[[str], ImageReader] | None): Function returning a reader for a given file name.
|
|
43
|
+
auto_register_default_readers (bool): Whether to auto-register default readers on pipeline call.
|
|
44
|
+
"""
|
|
45
|
+
if transformers:
|
|
46
|
+
assert (
|
|
47
|
+
not access_transformers and not image_transformers
|
|
48
|
+
), "access_transformers and image_transformers may not be used together with transformers argument."
|
|
49
|
+
self.transformers = list(transformers or [])
|
|
50
|
+
|
|
51
|
+
# For convenience, access transformers and image transformers can be specified separately.
|
|
52
|
+
# This saves users from thinking about the (maybe) unintuitive order of coordinate transformers.
|
|
53
|
+
if image_transformers:
|
|
54
|
+
self.transformers.extend(image_transformers)
|
|
55
|
+
if access_transformers:
|
|
56
|
+
# Access transformers are applied in reverse order. Make sure that access_transformers is reversable first.
|
|
57
|
+
access_transformers = list(access_transformers)
|
|
58
|
+
self.transformers.extend(access_transformers[::-1])
|
|
59
|
+
|
|
60
|
+
self.reader_factory = reader_factory or get_reader
|
|
61
|
+
self.auto_register_default_readers = auto_register_default_readers
|
|
62
|
+
|
|
63
|
+
def __call__(
|
|
64
|
+
self,
|
|
65
|
+
file_name: str,
|
|
66
|
+
accessor: ImageAccessor,
|
|
67
|
+
**reader_kwargs: Any,
|
|
68
|
+
) -> ImageResult:
|
|
69
|
+
"""
|
|
70
|
+
Runs the pipeline on a file and returns the processed result.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
file_name (str): Path to the image file.
|
|
74
|
+
accessor (ImageAccessor): Image accessor specifying region and resolution.
|
|
75
|
+
read_metadata (bool): Whether to read metadata if not already set.
|
|
76
|
+
**reader_kwargs: Additional keyword arguments passed to the reader.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
ImageResult: The final image result after all transformations.
|
|
80
|
+
"""
|
|
81
|
+
from dataclasses import replace
|
|
82
|
+
|
|
83
|
+
if self.auto_register_default_readers:
|
|
84
|
+
from tiamat.readers import register_all_readers
|
|
85
|
+
|
|
86
|
+
register_all_readers()
|
|
87
|
+
reader = self.reader_factory(file_name, **reader_kwargs)
|
|
88
|
+
|
|
89
|
+
# Forward rollout of metadata through transformers
|
|
90
|
+
metadata = [reader.read_metadata()]
|
|
91
|
+
|
|
92
|
+
for transformer in self.transformers:
|
|
93
|
+
# Check for transformers that do not implement transform_metadata
|
|
94
|
+
if hasattr(transformer, "transform_metadata"):
|
|
95
|
+
metadata.append(
|
|
96
|
+
transformer.transform_metadata(metadata=replace(metadata[-1])),
|
|
97
|
+
)
|
|
98
|
+
else:
|
|
99
|
+
metadata.append(replace(metadata[-1]))
|
|
100
|
+
|
|
101
|
+
# Backwards rollout of accessor through transformers and metadata
|
|
102
|
+
accessors = [accessor]
|
|
103
|
+
for transformer, meta in zip(self.transformers[::-1], metadata[::-1][:-1]):
|
|
104
|
+
accessor = transformer.transform_access(accessor=replace(accessors[-1]), metadata=meta)
|
|
105
|
+
accessors.append(accessor)
|
|
106
|
+
|
|
107
|
+
# Read image data
|
|
108
|
+
image = reader.read_image(accessor=accessors[-1])
|
|
109
|
+
|
|
110
|
+
# Forward pass through the transformers to get final image result
|
|
111
|
+
for transformer, meta, acc in zip(self.transformers, metadata[:-1], accessors[::-1][1:]):
|
|
112
|
+
image = transformer.transform_image(
|
|
113
|
+
image=image,
|
|
114
|
+
metadata=meta,
|
|
115
|
+
accessor=acc,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
# Associate final output image with output metadata
|
|
119
|
+
return ImageResult(
|
|
120
|
+
image=image,
|
|
121
|
+
metadata=metadata[-1],
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def read_metadata(self, file_name: str, **reader_kwargs: Any) -> ImageMetadata:
|
|
125
|
+
"""
|
|
126
|
+
Reads and transforms image metadata.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
file_name (str): Path to the image file.
|
|
130
|
+
**reader_kwargs: Additional keyword arguments passed to the reader.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
ImageMetadata: The (possibly transformed) metadata.
|
|
134
|
+
"""
|
|
135
|
+
from dataclasses import replace
|
|
136
|
+
|
|
137
|
+
reader = self.reader_factory(file_name, **reader_kwargs)
|
|
138
|
+
metadata = reader.read_metadata()
|
|
139
|
+
# backwards pass through the transformers to transform the accessor
|
|
140
|
+
for transformer in self.transformers:
|
|
141
|
+
if hasattr(transformer, "transform_metadata"):
|
|
142
|
+
# check for transformers that do not implement transform_metadata
|
|
143
|
+
metadata = transformer.transform_metadata(metadata=replace(metadata))
|
|
144
|
+
return metadata
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from .factory import get_reader, register_reader # noqa: F401
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def register_all_readers():
|
|
5
|
+
# Generic image formats
|
|
6
|
+
from .generic import GenericReader
|
|
7
|
+
|
|
8
|
+
register_reader(GenericReader)
|
|
9
|
+
|
|
10
|
+
# NIFTI
|
|
11
|
+
from .nifti import NiftiReader
|
|
12
|
+
|
|
13
|
+
register_reader(NiftiReader)
|
|
14
|
+
|
|
15
|
+
# In-memory arrays
|
|
16
|
+
from .memory import MemoryReader
|
|
17
|
+
|
|
18
|
+
register_reader(MemoryReader)
|
|
19
|
+
|
|
20
|
+
from .stack import ImageStackReader, VolumeStackReader
|
|
21
|
+
|
|
22
|
+
register_reader(ImageStackReader)
|
|
23
|
+
register_reader(VolumeStackReader)
|
|
24
|
+
|
|
25
|
+
from .pipeline import PipelineReader
|
|
26
|
+
|
|
27
|
+
register_reader(PipelineReader)
|
|
28
|
+
|
|
29
|
+
from .zarr import OmeZarrReader
|
|
30
|
+
|
|
31
|
+
register_reader(OmeZarrReader)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Factory for managing and instantiating ImageReader classes.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from ..readers.protocol import ImageReader
|
|
6
|
+
|
|
7
|
+
# Registry of registered ImageReader classes
|
|
8
|
+
_READER_REGISTRY: list[type[ImageReader]] = []
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def register_reader(*reader_classes: type[ImageReader]) -> None:
|
|
12
|
+
"""
|
|
13
|
+
Register one or more ImageReader classes to the global registry.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
*reader_classes: One or more ImageReader subclasses to register.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
for reader_class in reader_classes:
|
|
20
|
+
if reader_class not in _READER_REGISTRY:
|
|
21
|
+
_READER_REGISTRY.append(reader_class)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_reader_for_file_type(file_type):
|
|
25
|
+
from tiamat.errors import UnknownFileError
|
|
26
|
+
|
|
27
|
+
if file_type in _READER_REGISTRY:
|
|
28
|
+
return _READER_REGISTRY[file_type]
|
|
29
|
+
else:
|
|
30
|
+
raise UnknownFileError(f"Could not find reader for file type {file_type}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_reader_from_registry(reader_name: str) -> type[ImageReader]:
|
|
34
|
+
"""
|
|
35
|
+
Get a registered ImageReader class by its class name.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
reader_name: The name of the reader class.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
The ImageReader class matching the name.
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
KeyError: If no reader with the given name is found.
|
|
45
|
+
"""
|
|
46
|
+
for cls in _READER_REGISTRY:
|
|
47
|
+
if cls.__name__ == reader_name:
|
|
48
|
+
return cls
|
|
49
|
+
raise KeyError(f"No reader found with name {reader_name}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def get_reader(fname: str, auto_register_default_readers: bool = True, **kwargs) -> ImageReader:
|
|
53
|
+
"""
|
|
54
|
+
Select and instantiate the best matching reader for a given file.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
fname: Path to the image file.
|
|
58
|
+
auto_register_default_readers: If True, automatically register default readers before selection.
|
|
59
|
+
**kwargs: Additional keyword arguments passed to the reader constructor.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
An instantiated ImageReader object suitable for reading the file.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
UnknownFileError: If no reader can handle the file or multiple readers have the same priority.
|
|
66
|
+
"""
|
|
67
|
+
from tiamat.errors import UnknownFileError
|
|
68
|
+
|
|
69
|
+
if auto_register_default_readers:
|
|
70
|
+
from . import register_all_readers
|
|
71
|
+
|
|
72
|
+
register_all_readers()
|
|
73
|
+
|
|
74
|
+
reader_by_priority = []
|
|
75
|
+
reader_errors = []
|
|
76
|
+
for reader in _READER_REGISTRY:
|
|
77
|
+
try:
|
|
78
|
+
reader_priority = reader.check_file(fname)
|
|
79
|
+
except Exception as ex:
|
|
80
|
+
# Ignore errors in check_file, but keep track of them for diagnostics
|
|
81
|
+
reader_errors.append((reader, ex))
|
|
82
|
+
continue
|
|
83
|
+
if isinstance(reader_priority, bool):
|
|
84
|
+
if reader_priority:
|
|
85
|
+
reader_priority = 0
|
|
86
|
+
else:
|
|
87
|
+
# reader does not support this file
|
|
88
|
+
continue
|
|
89
|
+
elif isinstance(reader_priority, (float, int)):
|
|
90
|
+
if reader_priority < 0:
|
|
91
|
+
# reader does not support this file
|
|
92
|
+
continue
|
|
93
|
+
else:
|
|
94
|
+
raise RuntimeError("Reader must return bool or int from check_file")
|
|
95
|
+
reader_by_priority.append((reader, reader_priority))
|
|
96
|
+
if not reader_by_priority:
|
|
97
|
+
raise UnknownFileError(f"Could not find reader for file {fname}. Reader errors: {reader_errors}")
|
|
98
|
+
|
|
99
|
+
# sort by priority (descending)
|
|
100
|
+
reader_by_priority.sort(key=lambda x: -x[1])
|
|
101
|
+
top_priority = reader_by_priority[0][1]
|
|
102
|
+
second_priority = reader_by_priority[1][1] if len(reader_by_priority) > 1 else None
|
|
103
|
+
if second_priority is not None and top_priority == second_priority:
|
|
104
|
+
raise UnknownFileError(f"Multiple readers with same priority for file {fname}")
|
|
105
|
+
selected_reader = reader_by_priority[0][0]
|
|
106
|
+
return selected_reader(fname, **kwargs)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reader for generic image formats.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from tiamat.cache import instance_cache
|
|
12
|
+
|
|
13
|
+
from ..io import ImageAccessor
|
|
14
|
+
from ..metadata import ImageMetadata
|
|
15
|
+
from .protocol import ImageReader
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GenericReader(ImageReader):
|
|
19
|
+
"""
|
|
20
|
+
Reader for generic image formats using `imageio`.
|
|
21
|
+
|
|
22
|
+
This acts as a fallback reader for standard image files without a specialized format handler.
|
|
23
|
+
It supports caching the image in memory to avoid repeated disk reads.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
fname: str,
|
|
29
|
+
cache_image: bool = False,
|
|
30
|
+
image_spacing: float | Sequence[float] | None = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
"""
|
|
33
|
+
Initialize a generic image reader.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
fname: Path to the image file.
|
|
37
|
+
cache_image: If True, keep the loaded image in memory to avoid repeated disk access.
|
|
38
|
+
image_spacing: Physical pixel spacing as a single float (isotropic),
|
|
39
|
+
a tuple of floats (anisotropic), or None if not specified.
|
|
40
|
+
"""
|
|
41
|
+
self.fname = fname
|
|
42
|
+
self.image_spacing = image_spacing
|
|
43
|
+
self._cache_image = cache_image
|
|
44
|
+
self._cached_image: np.ndarray | None = None
|
|
45
|
+
|
|
46
|
+
def _read_image(self) -> np.ndarray:
|
|
47
|
+
"""
|
|
48
|
+
Load the image from disk or return the cached version.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
np.ndarray: Raw image array as loaded by `imageio`.
|
|
52
|
+
"""
|
|
53
|
+
from imageio.v3 import imread
|
|
54
|
+
|
|
55
|
+
image = self._cached_image if self._cached_image is not None else imread(self.fname)
|
|
56
|
+
if self._cache_image:
|
|
57
|
+
self._cached_image = image
|
|
58
|
+
|
|
59
|
+
return image
|
|
60
|
+
|
|
61
|
+
def read_image(self, accessor: ImageAccessor) -> np.ndarray:
|
|
62
|
+
"""
|
|
63
|
+
Read, crop, and rescale the image according to the accessor.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
accessor: ImageAccessor describing the requested region and scaling.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
np.ndarray: The processed image array.
|
|
70
|
+
"""
|
|
71
|
+
from .processing import access_and_rescale_image
|
|
72
|
+
|
|
73
|
+
# Read, crop, and rescale.
|
|
74
|
+
image = self._read_image()
|
|
75
|
+
image = access_and_rescale_image(image=image, metadata=self.read_metadata(), accessor=accessor)
|
|
76
|
+
|
|
77
|
+
return image
|
|
78
|
+
|
|
79
|
+
@instance_cache
|
|
80
|
+
def read_metadata(self) -> ImageMetadata:
|
|
81
|
+
"""
|
|
82
|
+
Read minimal metadata for a generic image.
|
|
83
|
+
|
|
84
|
+
Since no external metadata is available, dimensions and spacing
|
|
85
|
+
are inferred from the image array.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
ImageMetadata: Object with basic metadata such as shape, dtype,
|
|
89
|
+
dimensions, spacing, and value range.
|
|
90
|
+
"""
|
|
91
|
+
from tiamat import metadata as md
|
|
92
|
+
from tiamat.readers.processing import get_value_range_from_dtype
|
|
93
|
+
|
|
94
|
+
image = self._read_image()
|
|
95
|
+
dims = [md.dimensions.Y, md.dimensions.X]
|
|
96
|
+
|
|
97
|
+
if image.ndim == 3:
|
|
98
|
+
if image.shape[2] == 3:
|
|
99
|
+
dims.append(md.dimensions.RGB)
|
|
100
|
+
elif image.shape[2] == 4:
|
|
101
|
+
dims.append(md.dimensions.RGBA)
|
|
102
|
+
else:
|
|
103
|
+
dims.append(md.dimensions.C)
|
|
104
|
+
else:
|
|
105
|
+
dims.extend([md.dimensions.C for _ in range(max(len(image.shape) - 2, 0))])
|
|
106
|
+
|
|
107
|
+
shape = image.shape
|
|
108
|
+
dtype = image.dtype
|
|
109
|
+
value_range = get_value_range_from_dtype(dtype)
|
|
110
|
+
|
|
111
|
+
return md.ImageMetadata(
|
|
112
|
+
image_type=md.IMAGE_TYPE_IMAGE,
|
|
113
|
+
shape=shape,
|
|
114
|
+
dtype=dtype,
|
|
115
|
+
file_path=self.fname,
|
|
116
|
+
value_range=value_range,
|
|
117
|
+
spacing=self.image_spacing,
|
|
118
|
+
dimensions=dims,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
@classmethod
|
|
122
|
+
def supported_extensions(cls) -> list[str]:
|
|
123
|
+
"""
|
|
124
|
+
Get the list of file extensions supported by `imageio`.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
list[str]: Supported file extensions.
|
|
128
|
+
"""
|
|
129
|
+
import imageio
|
|
130
|
+
|
|
131
|
+
extensions: list[str] = []
|
|
132
|
+
for fmt in imageio.formats:
|
|
133
|
+
extensions.extend(fmt.extensions)
|
|
134
|
+
return extensions
|
|
135
|
+
|
|
136
|
+
@classmethod
|
|
137
|
+
def check_file(cls, fname: str) -> bool | int | float:
|
|
138
|
+
"""
|
|
139
|
+
Check if the file extension is supported by this reader.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
fname: Path to the file.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
True if supported, else False.
|
|
146
|
+
"""
|
|
147
|
+
import os
|
|
148
|
+
|
|
149
|
+
_, ext = os.path.splitext(fname)
|
|
150
|
+
return ext in cls.supported_extensions()
|
tiamat/readers/memory.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reader for in-memory arrays.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from tiamat.cache import instance_cache
|
|
13
|
+
|
|
14
|
+
from ..io import ImageAccessor
|
|
15
|
+
from ..metadata import ImageMetadata
|
|
16
|
+
from .protocol import ImageReader
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MemoryReader(ImageReader):
|
|
20
|
+
"""
|
|
21
|
+
Reader that serves images directly from an in-memory array-like object.
|
|
22
|
+
|
|
23
|
+
Notes:
|
|
24
|
+
- The constructor argument `image` can be a numpy array or any object exposing
|
|
25
|
+
a numpy-compatible `__array__` interface.
|
|
26
|
+
- Minimal metadata is inferred from the array, but can be overridden via `metadata_kwargs`.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, image: Any, **metadata_kwargs: Any) -> None:
|
|
30
|
+
"""
|
|
31
|
+
Initialize the memory reader.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
image: Array-like image data (e.g., numpy.ndarray).
|
|
35
|
+
**metadata_kwargs: Overrides for `ImageMetadata` fields.
|
|
36
|
+
Accepted keys include:
|
|
37
|
+
- image_type
|
|
38
|
+
- value_range
|
|
39
|
+
- spacing
|
|
40
|
+
- dimensions
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
self.image = image
|
|
44
|
+
self._cached_image = None
|
|
45
|
+
self.metadata_kwargs: dict[str, Any] = metadata_kwargs
|
|
46
|
+
|
|
47
|
+
def read_image(self, accessor: ImageAccessor) -> np.ndarray:
|
|
48
|
+
"""
|
|
49
|
+
Apply access (crop/roi) and rescale based on the given accessor.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
accessor: Access descriptor (slicing, scaling, spacing etc.).
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
np.ndarray: The processed image.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
from .processing import access_and_rescale_image
|
|
59
|
+
|
|
60
|
+
# Read, crop, and rescale.
|
|
61
|
+
image = access_and_rescale_image(image=self.image, metadata=self.read_metadata(), accessor=accessor)
|
|
62
|
+
|
|
63
|
+
return image
|
|
64
|
+
|
|
65
|
+
@instance_cache
|
|
66
|
+
def read_metadata(self) -> ImageMetadata:
|
|
67
|
+
"""
|
|
68
|
+
Infer minimal metadata from the in-memory image and apply overrides.
|
|
69
|
+
|
|
70
|
+
Heuristics for dimensions:
|
|
71
|
+
- Start with (Y, X).
|
|
72
|
+
- If ndim == 3 and last axis is 3 or 4, assume RGB / RGBA.
|
|
73
|
+
- Otherwise, treat extra axes as generic channels C.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
ImageMetadata: Object with inferred or overridden metadata.
|
|
77
|
+
"""
|
|
78
|
+
from tiamat import metadata as md
|
|
79
|
+
|
|
80
|
+
fallback_dimensions = [
|
|
81
|
+
md.dimensions.Y,
|
|
82
|
+
md.dimensions.X,
|
|
83
|
+
] + [md.dimensions.C for _ in range(len(self.image.shape) - 2)]
|
|
84
|
+
|
|
85
|
+
return md.ImageMetadata(
|
|
86
|
+
image_type=self.metadata_kwargs.get("image_type", md.IMAGE_TYPE_IMAGE),
|
|
87
|
+
shape=self.image.shape,
|
|
88
|
+
dtype=self.image.dtype,
|
|
89
|
+
value_range=self.metadata_kwargs.get("value_range", (0, 255)),
|
|
90
|
+
spacing=self.metadata_kwargs.get("spacing", None),
|
|
91
|
+
dimensions=self.metadata_kwargs.get(
|
|
92
|
+
"dimensions",
|
|
93
|
+
fallback_dimensions,
|
|
94
|
+
),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def check_file(cls, fname) -> bool | int | float:
|
|
99
|
+
"""
|
|
100
|
+
Indicate support for array-like inputs.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
fname: Object to test.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
True iff `fname` exposes a numpy-compatible array protocol.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
return hasattr(fname, "__array__")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ConstantImage:
|
|
113
|
+
"""
|
|
114
|
+
Lazy array-like that returns a constant value for any requested slice.
|
|
115
|
+
|
|
116
|
+
Only materializes the requested region in __getitem__, not the whole array.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
def __init__(self, shape: Sequence[int], dtype: np.dtype = np.uint8, constant: int | float = 0) -> None:
|
|
120
|
+
"""
|
|
121
|
+
Initialize a constant-valued image.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
shape: Shape of the virtual image.
|
|
125
|
+
dtype: NumPy dtype of the values.
|
|
126
|
+
constant: Constant fill value.
|
|
127
|
+
"""
|
|
128
|
+
self.shape: tuple[int, ...] = tuple(int(s) for s in shape)
|
|
129
|
+
self.constant: int | float = constant
|
|
130
|
+
self.dtype: np.dtype = np.dtype(dtype)
|
|
131
|
+
|
|
132
|
+
def __getitem__(self, array_slice: slice | tuple[slice] | None):
|
|
133
|
+
"""
|
|
134
|
+
Build a numpy array filled with the constant value for the requested slice.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
array_slice: Standard numpy slicing (can include ellipsis etc.).
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
np.ndarray with shape determined by the slice.
|
|
141
|
+
"""
|
|
142
|
+
from tiamat.array import slice_to_interval
|
|
143
|
+
|
|
144
|
+
array_intervals, _ = slice_to_interval(array_slice, self.shape)
|
|
145
|
+
|
|
146
|
+
out_shape = []
|
|
147
|
+
|
|
148
|
+
for i, ai in enumerate(array_intervals):
|
|
149
|
+
dim_size = min(ai[1], self.shape[i]) - max(ai[0], 0)
|
|
150
|
+
out_shape.append(dim_size)
|
|
151
|
+
|
|
152
|
+
out_array = np.full(out_shape, self.constant, dtype=self.dtype)
|
|
153
|
+
|
|
154
|
+
return out_array
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class ConstantReader(ImageReader):
|
|
158
|
+
"""
|
|
159
|
+
Reader that returns a constant-valued image with provided metadata.
|
|
160
|
+
Useful as a synthetic source, e.g., for padding or tests.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(self, fill_value: int | float, metadata: ImageMetadata) -> None:
|
|
164
|
+
"""
|
|
165
|
+
Initialize a constant reader.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
fill_value: Value used to fill the image.
|
|
169
|
+
metadata: ImageMetadata describing the constant image.
|
|
170
|
+
"""
|
|
171
|
+
from dataclasses import replace
|
|
172
|
+
|
|
173
|
+
self.fill_value: int | float = fill_value
|
|
174
|
+
self.metadata = replace(metadata)
|
|
175
|
+
self.metadata.file_path = None
|
|
176
|
+
|
|
177
|
+
self.image = ConstantImage(metadata.shape, metadata.dtype, constant=fill_value)
|
|
178
|
+
|
|
179
|
+
def read_image(self, accessor: ImageAccessor) -> np.ndarray:
|
|
180
|
+
"""
|
|
181
|
+
Build the requested region from the constant image and rescale if needed.
|
|
182
|
+
|
|
183
|
+
Args:
|
|
184
|
+
accessor: ImageAccessor describing requested region and scaling.
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
np.ndarray: The processed constant image.
|
|
188
|
+
"""
|
|
189
|
+
from .processing import access_and_rescale_image
|
|
190
|
+
|
|
191
|
+
# Read, crop, and rescale.
|
|
192
|
+
image = access_and_rescale_image(
|
|
193
|
+
image=self.image, metadata=self.read_metadata(), accessor=accessor, image_scale=accessor.scale
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
return image
|
|
197
|
+
|
|
198
|
+
@instance_cache
|
|
199
|
+
def read_metadata(self) -> ImageMetadata:
|
|
200
|
+
"""
|
|
201
|
+
Return the metadata of the constant image.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
ImageMetadata: Metadata associated with this constant image.
|
|
205
|
+
"""
|
|
206
|
+
return self.metadata
|
|
207
|
+
|
|
208
|
+
@classmethod
|
|
209
|
+
def check_file(cls, fname: Any) -> bool | int | float:
|
|
210
|
+
"""
|
|
211
|
+
For parity with MemoryReader: declare support for array-like inputs.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
fname: Object to test.
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
True if `fname` exposes a numpy-compatible array protocol.
|
|
218
|
+
|
|
219
|
+
Note:
|
|
220
|
+
In normal file-based selection this will evaluate to False (strings lack __array__),
|
|
221
|
+
so ConstantReader won't be selected by accident in the file reader factory.
|
|
222
|
+
"""
|
|
223
|
+
return hasattr(fname, "__array__")
|