bioimageflow-io-tools 0.1.6__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.
- bioimageflow_io_tools/__init__.py +57 -0
- bioimageflow_io_tools/bioio_convert.py +176 -0
- bioimageflow_io_tools/image_io.py +843 -0
- bioimageflow_io_tools-0.1.6.dist-info/METADATA +51 -0
- bioimageflow_io_tools-0.1.6.dist-info/RECORD +7 -0
- bioimageflow_io_tools-0.1.6.dist-info/WHEEL +4 -0
- bioimageflow_io_tools-0.1.6.dist-info/licenses/LICENSE +17 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""BioImageFlow IO Tools."""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .bioio_convert import BioIOConvertImage as BioIOConvertImage
|
|
8
|
+
from .image_io import ConvertImageFormat as ConvertImageFormat
|
|
9
|
+
from .image_io import ConvertToOmeTiff as ConvertToOmeTiff
|
|
10
|
+
from .image_io import ConvertToOmeZarr as ConvertToOmeZarr
|
|
11
|
+
from .image_io import ReadImageMetadata as ReadImageMetadata
|
|
12
|
+
from .image_io import SelectChannel as SelectChannel
|
|
13
|
+
from .image_io import SelectDimensions as SelectDimensions
|
|
14
|
+
from .image_io import SelectScene as SelectScene
|
|
15
|
+
from .image_io import SelectTimepoint as SelectTimepoint
|
|
16
|
+
from .image_io import SelectZRange as SelectZRange
|
|
17
|
+
from .image_io import ValidateImageLayout as ValidateImageLayout
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_EXPORTS = {
|
|
21
|
+
"BioIOConvertImage": ("bioio_convert", "BioIOConvertImage"),
|
|
22
|
+
"ConvertImageFormat": ("image_io", "ConvertImageFormat"),
|
|
23
|
+
"ConvertToOmeTiff": ("image_io", "ConvertToOmeTiff"),
|
|
24
|
+
"ConvertToOmeZarr": ("image_io", "ConvertToOmeZarr"),
|
|
25
|
+
"ReadImageMetadata": ("image_io", "ReadImageMetadata"),
|
|
26
|
+
"SelectChannel": ("image_io", "SelectChannel"),
|
|
27
|
+
"SelectDimensions": ("image_io", "SelectDimensions"),
|
|
28
|
+
"SelectScene": ("image_io", "SelectScene"),
|
|
29
|
+
"SelectTimepoint": ("image_io", "SelectTimepoint"),
|
|
30
|
+
"SelectZRange": ("image_io", "SelectZRange"),
|
|
31
|
+
"ValidateImageLayout": ("image_io", "ValidateImageLayout"),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"BioIOConvertImage",
|
|
36
|
+
"ConvertImageFormat",
|
|
37
|
+
"ConvertToOmeTiff",
|
|
38
|
+
"ConvertToOmeZarr",
|
|
39
|
+
"ReadImageMetadata",
|
|
40
|
+
"SelectChannel",
|
|
41
|
+
"SelectDimensions",
|
|
42
|
+
"SelectScene",
|
|
43
|
+
"SelectTimepoint",
|
|
44
|
+
"SelectZRange",
|
|
45
|
+
"ValidateImageLayout",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def __getattr__(name: str) -> Any:
|
|
50
|
+
try:
|
|
51
|
+
module_name, attribute_name = _EXPORTS[name]
|
|
52
|
+
except KeyError as exc:
|
|
53
|
+
raise AttributeError(name) from exc
|
|
54
|
+
module = import_module(f".{module_name}", __name__)
|
|
55
|
+
value = getattr(module, attribute_name)
|
|
56
|
+
globals()[name] = value
|
|
57
|
+
return value
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""BioIOConvertImage — convert image file formats using bioio."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated, Any
|
|
5
|
+
|
|
6
|
+
from bioimageflow_core import (
|
|
7
|
+
Arguments,
|
|
8
|
+
Category,
|
|
9
|
+
Connectable,
|
|
10
|
+
EnvironmentSpec,
|
|
11
|
+
GUIMeta,
|
|
12
|
+
ImageSpec,
|
|
13
|
+
IOModel,
|
|
14
|
+
ProcessingTool,
|
|
15
|
+
Template,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
bioio_env = EnvironmentSpec(
|
|
19
|
+
name="bioio-all",
|
|
20
|
+
dependencies={
|
|
21
|
+
"python": "3.12",
|
|
22
|
+
"pip": [
|
|
23
|
+
"bioio==3.4.0",
|
|
24
|
+
"bioio-ome-zarr==3.5.1",
|
|
25
|
+
"bioio-ome-tiff==1.4.0",
|
|
26
|
+
"bioio-czi==2.8.0",
|
|
27
|
+
"bioio-imageio==1.3.0",
|
|
28
|
+
"bioio-tifffile==1.3.0",
|
|
29
|
+
"bioio-tiff-glob==1.2.0",
|
|
30
|
+
]
|
|
31
|
+
}
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class BioIOConvertImage(ProcessingTool):
|
|
36
|
+
"""Convert image file formats using bioio.
|
|
37
|
+
|
|
38
|
+
Supports reading CZI, DV, PNG, GIF, LIF, ND2, OME-TIFF, OME-ZARR,
|
|
39
|
+
SLDY, TIFF, and Bio-Formats files. The extension of the output file
|
|
40
|
+
specifies the target format.
|
|
41
|
+
"""
|
|
42
|
+
display_name = "BioIO Convert Image"
|
|
43
|
+
documentation = (
|
|
44
|
+
"Convert broad microscopy image file formats using bioio. The output format is "
|
|
45
|
+
"determined by the output file extension."
|
|
46
|
+
)
|
|
47
|
+
category = Category.CONVERSION
|
|
48
|
+
tags = ["format conversion", "bioio"]
|
|
49
|
+
environment = bioio_env
|
|
50
|
+
|
|
51
|
+
class Inputs(IOModel):
|
|
52
|
+
input_image: Annotated[
|
|
53
|
+
Path,
|
|
54
|
+
ImageSpec(),
|
|
55
|
+
GUIMeta(
|
|
56
|
+
display_name="Input image",
|
|
57
|
+
description="Source image file to convert.",
|
|
58
|
+
connectable=Connectable.BY_DEFAULT,
|
|
59
|
+
)
|
|
60
|
+
]
|
|
61
|
+
dim_order: Annotated[str, GUIMeta(
|
|
62
|
+
display_name="Dimension order",
|
|
63
|
+
description="Target dimension order used when reading the image.",
|
|
64
|
+
)] = "TCZYX"
|
|
65
|
+
scene: Annotated[int | None, GUIMeta(
|
|
66
|
+
display_name="Scene",
|
|
67
|
+
description="Optional scene index for multi-scene files. Leave empty to keep the default scene.",
|
|
68
|
+
min=0, step=1,
|
|
69
|
+
)] = None
|
|
70
|
+
channel: Annotated[int | None, GUIMeta(
|
|
71
|
+
display_name="Channel",
|
|
72
|
+
description="Optional channel index to select (0-based). Leave empty to keep all channels.",
|
|
73
|
+
min=0, step=1,
|
|
74
|
+
)] = None
|
|
75
|
+
z: Annotated[int | None, GUIMeta(
|
|
76
|
+
display_name="Z slice",
|
|
77
|
+
description="Optional Z-slice index to select (0-based). Leave empty to keep all Z slices.",
|
|
78
|
+
min=0, step=1,
|
|
79
|
+
)] = None
|
|
80
|
+
timepoint: Annotated[int | None, GUIMeta(
|
|
81
|
+
display_name="Timepoint",
|
|
82
|
+
description="Optional timepoint index to select (0-based). Leave empty to keep all timepoints.",
|
|
83
|
+
min=0, step=1,
|
|
84
|
+
)] = None
|
|
85
|
+
|
|
86
|
+
class Outputs(IOModel):
|
|
87
|
+
output_image: Annotated[
|
|
88
|
+
Path,
|
|
89
|
+
ImageSpec(),
|
|
90
|
+
GUIMeta(
|
|
91
|
+
display_name="Output image",
|
|
92
|
+
description="Converted image. The file extension controls the output format (e.g. .ome.tiff, .ome.zarr, .tif, .png).",
|
|
93
|
+
)
|
|
94
|
+
] = Template("{input_image.stem}.ome.tiff")
|
|
95
|
+
|
|
96
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
97
|
+
from bioio import BioImage #type: ignore
|
|
98
|
+
from bioio_ome_tiff.writers import OmeTiffWriter #type: ignore
|
|
99
|
+
from bioio_ome_zarr.writers import OMEZarrWriter #type: ignore
|
|
100
|
+
from bioio_imageio.writers import TwoDWriter #type: ignore
|
|
101
|
+
import numpy as np
|
|
102
|
+
import tifffile
|
|
103
|
+
|
|
104
|
+
input_path = Path(arguments.input_image)
|
|
105
|
+
output_path = Path(arguments.output_image)
|
|
106
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
|
|
108
|
+
print(f"Converting {input_path.name}...")
|
|
109
|
+
image = BioImage(input_path)
|
|
110
|
+
|
|
111
|
+
if arguments.scene is not None:
|
|
112
|
+
image.set_scene(arguments.scene)
|
|
113
|
+
|
|
114
|
+
# Show dimension sizes
|
|
115
|
+
print(f"Image: {input_path.name}")
|
|
116
|
+
print(f" Dimensions: {image.dims}")
|
|
117
|
+
print(f" Shape: {image.shape}")
|
|
118
|
+
print(f" Dtype: {image.dtype}")
|
|
119
|
+
|
|
120
|
+
dim_kwargs: dict[str, int] = {}
|
|
121
|
+
if arguments.channel is not None:
|
|
122
|
+
dim_kwargs["C"] = arguments.channel
|
|
123
|
+
if arguments.z is not None:
|
|
124
|
+
dim_kwargs["Z"] = arguments.z
|
|
125
|
+
if arguments.timepoint is not None:
|
|
126
|
+
dim_kwargs["T"] = arguments.timepoint
|
|
127
|
+
|
|
128
|
+
# Use user-specified dim_order for reading
|
|
129
|
+
dim_order = arguments.dim_order
|
|
130
|
+
if dim_kwargs:
|
|
131
|
+
data = image.get_image_data(dim_order, **dim_kwargs)
|
|
132
|
+
else:
|
|
133
|
+
data = image.get_image_data(dim_order)
|
|
134
|
+
|
|
135
|
+
# Squeeze singleton leading dimensions (T, Z) so downstream tools
|
|
136
|
+
# see CYX / YX shapes rather than TCZYX with size-1 axes.
|
|
137
|
+
while data.ndim > 2 and data.shape[0] == 1:
|
|
138
|
+
data = data[0]
|
|
139
|
+
dim_order = dim_order[1:]
|
|
140
|
+
|
|
141
|
+
print(f" Output shape ({dim_order}): {data.shape}")
|
|
142
|
+
|
|
143
|
+
suffixes = "".join(output_path.suffixes).lower()
|
|
144
|
+
|
|
145
|
+
if suffixes.endswith(".ome.tiff") or suffixes.endswith(".ome.tif"):
|
|
146
|
+
OmeTiffWriter.save(data, str(output_path), dim_order=dim_order)
|
|
147
|
+
elif suffixes.endswith(".ome.zarr"):
|
|
148
|
+
axes_map = {
|
|
149
|
+
"T": ("t", "time"), "C": ("c", "channel"), "Z": ("z", "space"),
|
|
150
|
+
"Y": ("y", "space"), "X": ("x", "space"), "S": ("s", "channel"),
|
|
151
|
+
}
|
|
152
|
+
axes_names = [axes_map[c][0] for c in dim_order]
|
|
153
|
+
axes_types = [axes_map[c][1] for c in dim_order]
|
|
154
|
+
writer = OMEZarrWriter(
|
|
155
|
+
store=str(output_path),
|
|
156
|
+
level_shapes=data.shape,
|
|
157
|
+
dtype=data.dtype,
|
|
158
|
+
axes_names=axes_names,
|
|
159
|
+
axes_types=axes_types,
|
|
160
|
+
)
|
|
161
|
+
writer.write_full_volume(data)
|
|
162
|
+
elif suffixes.endswith(".tiff") or suffixes.endswith(".tif"):
|
|
163
|
+
tifffile.imwrite(str(output_path), data)
|
|
164
|
+
else:
|
|
165
|
+
img_2d = np.squeeze(data)
|
|
166
|
+
if img_2d.ndim > 3:
|
|
167
|
+
raise ValueError(
|
|
168
|
+
f"Cannot save {img_2d.ndim}D data to {output_path.suffix}. "
|
|
169
|
+
f"Use dimension selection (channel, z, timepoint) to reduce."
|
|
170
|
+
)
|
|
171
|
+
if img_2d.ndim == 3 and img_2d.shape[0] in (1, 3, 4):
|
|
172
|
+
TwoDWriter.save(img_2d, str(output_path), "SYX")
|
|
173
|
+
else:
|
|
174
|
+
TwoDWriter.save(img_2d, str(output_path))
|
|
175
|
+
|
|
176
|
+
return self.Outputs(output_image=output_path)
|
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
"""Lightweight image IO tools."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Annotated, Any
|
|
6
|
+
import xml.etree.ElementTree as ET
|
|
7
|
+
|
|
8
|
+
from bioimageflow_core import (
|
|
9
|
+
Arguments,
|
|
10
|
+
Category,
|
|
11
|
+
Connectable,
|
|
12
|
+
GENERAL_ENV,
|
|
13
|
+
GUIMeta,
|
|
14
|
+
ImageSpec,
|
|
15
|
+
IOModel,
|
|
16
|
+
Layout,
|
|
17
|
+
ProcessingTool,
|
|
18
|
+
Semantic,
|
|
19
|
+
Template,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
class ReadImageMetadata(ProcessingTool):
|
|
23
|
+
"""Read lightweight image metadata without materializing workflow outputs."""
|
|
24
|
+
|
|
25
|
+
display_name = "Read Image Metadata"
|
|
26
|
+
documentation = "Report image shape, dtype, dimensionality, and a pragmatic axes guess."
|
|
27
|
+
category = Category.CONVERSION
|
|
28
|
+
tags = ["io", "metadata", "image"]
|
|
29
|
+
environment = GENERAL_ENV
|
|
30
|
+
|
|
31
|
+
class Inputs(IOModel):
|
|
32
|
+
input_image: Annotated[
|
|
33
|
+
Path,
|
|
34
|
+
ImageSpec(),
|
|
35
|
+
GUIMeta(
|
|
36
|
+
display_name="Input image",
|
|
37
|
+
description="Image file to inspect.",
|
|
38
|
+
connectable=Connectable.BY_DEFAULT,
|
|
39
|
+
),
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
class Outputs(IOModel):
|
|
43
|
+
shape: Annotated[list[int], GUIMeta(display_name="Shape")]
|
|
44
|
+
dtype: Annotated[str, GUIMeta(display_name="Dtype")]
|
|
45
|
+
ndim: Annotated[int, GUIMeta(display_name="Dimensions")]
|
|
46
|
+
axes: Annotated[str, GUIMeta(display_name="Axes guess")]
|
|
47
|
+
channel_names: Annotated[list[str], GUIMeta(display_name="Channel names")]
|
|
48
|
+
pixel_sizes: Annotated[dict[str, float | None], GUIMeta(display_name="Pixel sizes")]
|
|
49
|
+
|
|
50
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
51
|
+
data = _read_image(arguments.input_image)
|
|
52
|
+
axes = _axes_guess_for_shape(data.shape)
|
|
53
|
+
return self.Outputs(
|
|
54
|
+
shape=list(data.shape),
|
|
55
|
+
dtype=str(data.dtype),
|
|
56
|
+
ndim=data.ndim,
|
|
57
|
+
axes=axes,
|
|
58
|
+
channel_names=_channel_names_for_axes(data.shape, axes),
|
|
59
|
+
pixel_sizes=_pixel_sizes_from_metadata(arguments.input_image),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ValidateImageLayout(ProcessingTool):
|
|
64
|
+
"""Validate that a declared axis layout matches an image array."""
|
|
65
|
+
|
|
66
|
+
display_name = "Validate Image Layout"
|
|
67
|
+
documentation = "Validate layout length, required axes, and optional minimum axis sizes."
|
|
68
|
+
category = Category.UTILITIES
|
|
69
|
+
tags = ["io", "metadata", "validation", "layout"]
|
|
70
|
+
environment = GENERAL_ENV
|
|
71
|
+
|
|
72
|
+
class Inputs(IOModel):
|
|
73
|
+
input_image: Annotated[
|
|
74
|
+
Path,
|
|
75
|
+
ImageSpec(),
|
|
76
|
+
GUIMeta(
|
|
77
|
+
display_name="Input image",
|
|
78
|
+
description="Image file whose declared layout should be validated.",
|
|
79
|
+
connectable=Connectable.BY_DEFAULT,
|
|
80
|
+
),
|
|
81
|
+
]
|
|
82
|
+
layout: Annotated[str, GUIMeta(
|
|
83
|
+
display_name="Layout",
|
|
84
|
+
description="Declared axis order, such as YX, ZYX, CZYX, TCYX, or TCZYX.",
|
|
85
|
+
connectable=Connectable.NEVER,
|
|
86
|
+
)]
|
|
87
|
+
required_axes: Annotated[str, GUIMeta(
|
|
88
|
+
display_name="Required axes",
|
|
89
|
+
description="Axes that must be present in the declared layout.",
|
|
90
|
+
connectable=Connectable.NEVER,
|
|
91
|
+
)] = ""
|
|
92
|
+
min_size: Annotated[int | None, GUIMeta(
|
|
93
|
+
display_name="Minimum size",
|
|
94
|
+
description="Optional minimum size for every declared axis.",
|
|
95
|
+
min=0,
|
|
96
|
+
step=1,
|
|
97
|
+
connectable=Connectable.NEVER,
|
|
98
|
+
)] = None
|
|
99
|
+
|
|
100
|
+
class Outputs(IOModel):
|
|
101
|
+
valid: Annotated[bool, GUIMeta(display_name="Valid")]
|
|
102
|
+
axes: Annotated[str, GUIMeta(display_name="Axes")]
|
|
103
|
+
shape: Annotated[list[int], GUIMeta(display_name="Shape")]
|
|
104
|
+
|
|
105
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
106
|
+
data = _read_image(arguments.input_image)
|
|
107
|
+
layout = _validate_layout_for_data(data, arguments.layout)
|
|
108
|
+
required_axes = str(arguments.required_axes or "").upper()
|
|
109
|
+
for axis in required_axes:
|
|
110
|
+
if axis not in layout:
|
|
111
|
+
raise ValueError(f"Layout {layout!r} requires axis {axis!r}.")
|
|
112
|
+
if arguments.min_size is not None:
|
|
113
|
+
for axis, size in zip(layout, data.shape, strict=True):
|
|
114
|
+
if size < arguments.min_size:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
f"Axis {axis!r} has size {size}, below minimum "
|
|
117
|
+
f"{arguments.min_size}."
|
|
118
|
+
)
|
|
119
|
+
return self.Outputs(valid=True, axes=layout, shape=list(data.shape))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class ConvertImageFormat(ProcessingTool):
|
|
123
|
+
"""Convert an image to a path-selected output format, with optional slicing."""
|
|
124
|
+
|
|
125
|
+
display_name = "Convert Image Format"
|
|
126
|
+
documentation = (
|
|
127
|
+
"Convert an image through imageio, OME-TIFF, or minimal OME-Zarr output. "
|
|
128
|
+
"Optionally select a scene, channel, Z plane, or timepoint before export."
|
|
129
|
+
)
|
|
130
|
+
category = Category.CONVERSION
|
|
131
|
+
tags = ["io", "conversion", "format-conversion", "ome-tiff", "ome-zarr"]
|
|
132
|
+
environment = GENERAL_ENV
|
|
133
|
+
|
|
134
|
+
class Inputs(IOModel):
|
|
135
|
+
input_image: Annotated[
|
|
136
|
+
Path,
|
|
137
|
+
ImageSpec(),
|
|
138
|
+
GUIMeta(
|
|
139
|
+
display_name="Input image",
|
|
140
|
+
description="Image to convert.",
|
|
141
|
+
connectable=Connectable.BY_DEFAULT,
|
|
142
|
+
),
|
|
143
|
+
]
|
|
144
|
+
input_layout: Annotated[str | None, GUIMeta(
|
|
145
|
+
display_name="Input layout",
|
|
146
|
+
description="Optional source axis order for channel, Z, and timepoint selection.",
|
|
147
|
+
connectable=Connectable.NEVER,
|
|
148
|
+
)] = None
|
|
149
|
+
scene: Annotated[int | None, GUIMeta(
|
|
150
|
+
display_name="Scene",
|
|
151
|
+
description="Optional zero-based TIFF scene index.",
|
|
152
|
+
min=0,
|
|
153
|
+
step=1,
|
|
154
|
+
connectable=Connectable.NEVER,
|
|
155
|
+
)] = None
|
|
156
|
+
channel: Annotated[int | None, GUIMeta(
|
|
157
|
+
display_name="Channel",
|
|
158
|
+
description="Optional zero-based C index to export.",
|
|
159
|
+
min=0,
|
|
160
|
+
step=1,
|
|
161
|
+
connectable=Connectable.NEVER,
|
|
162
|
+
)] = None
|
|
163
|
+
z: Annotated[int | None, GUIMeta(
|
|
164
|
+
display_name="Z slice",
|
|
165
|
+
description="Optional zero-based Z index to export.",
|
|
166
|
+
min=0,
|
|
167
|
+
step=1,
|
|
168
|
+
connectable=Connectable.NEVER,
|
|
169
|
+
)] = None
|
|
170
|
+
timepoint: Annotated[int | None, GUIMeta(
|
|
171
|
+
display_name="Timepoint",
|
|
172
|
+
description="Optional zero-based T index to export.",
|
|
173
|
+
min=0,
|
|
174
|
+
step=1,
|
|
175
|
+
connectable=Connectable.NEVER,
|
|
176
|
+
)] = None
|
|
177
|
+
dimension_order: Annotated[str | None, GUIMeta(
|
|
178
|
+
display_name="Dimension order",
|
|
179
|
+
description="Optional OME axis order for OME-TIFF outputs.",
|
|
180
|
+
connectable=Connectable.NEVER,
|
|
181
|
+
)] = None
|
|
182
|
+
|
|
183
|
+
class Outputs(IOModel):
|
|
184
|
+
output_image: Annotated[
|
|
185
|
+
Path,
|
|
186
|
+
ImageSpec(),
|
|
187
|
+
GUIMeta(
|
|
188
|
+
display_name="Converted image path",
|
|
189
|
+
description="Destination path. .ome.tiff/.ome.tif and .ome.zarr choose OME writers.",
|
|
190
|
+
),
|
|
191
|
+
] = Template("{input_image.stem}_converted{ext}")
|
|
192
|
+
|
|
193
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
194
|
+
data = _read_image_for_conversion(arguments)
|
|
195
|
+
output_path = Path(arguments.output_image)
|
|
196
|
+
_write_image(data, output_path, dimension_order=arguments.dimension_order)
|
|
197
|
+
return self.Outputs(output_image=output_path)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class SelectScene(ProcessingTool):
|
|
201
|
+
"""Extract one image scene from an ordinary or TIFF-series image."""
|
|
202
|
+
|
|
203
|
+
display_name = "Select Scene"
|
|
204
|
+
documentation = "Extract scene 0 from ordinary images or a tifffile series by index."
|
|
205
|
+
category = Category.IMAGE_PROCESSING
|
|
206
|
+
tags = ["io", "scene-selection"]
|
|
207
|
+
environment = GENERAL_ENV
|
|
208
|
+
|
|
209
|
+
class Inputs(IOModel):
|
|
210
|
+
input_image: Annotated[
|
|
211
|
+
Path,
|
|
212
|
+
ImageSpec(),
|
|
213
|
+
GUIMeta(
|
|
214
|
+
display_name="Input image",
|
|
215
|
+
description="Image file or TIFF file with multiple series.",
|
|
216
|
+
connectable=Connectable.BY_DEFAULT,
|
|
217
|
+
),
|
|
218
|
+
]
|
|
219
|
+
scene: Annotated[int, GUIMeta(
|
|
220
|
+
display_name="Scene",
|
|
221
|
+
description="Zero-based scene index.",
|
|
222
|
+
min=0,
|
|
223
|
+
step=1,
|
|
224
|
+
)] = 0
|
|
225
|
+
|
|
226
|
+
class Outputs(IOModel):
|
|
227
|
+
output_image: Annotated[
|
|
228
|
+
Path,
|
|
229
|
+
ImageSpec(semantics={Semantic.INTENSITY}),
|
|
230
|
+
GUIMeta(display_name="Selected scene"),
|
|
231
|
+
] = Template("{input_image.stem}_scene_{scene}{ext}")
|
|
232
|
+
|
|
233
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
234
|
+
data = _read_scene(arguments.input_image, arguments.scene)
|
|
235
|
+
output_path = Path(arguments.output_image)
|
|
236
|
+
_write_image(data, output_path)
|
|
237
|
+
return self.Outputs(output_image=output_path)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class SelectDimensions(ProcessingTool):
|
|
241
|
+
"""Select channel, z, and/or time indices from a raster image."""
|
|
242
|
+
|
|
243
|
+
display_name = "Select Dimensions"
|
|
244
|
+
documentation = "Select channel, z, and time indices from CZYX, TCYX, or TZYX images."
|
|
245
|
+
category = Category.IMAGE_PROCESSING
|
|
246
|
+
tags = ["io", "dimension-selection"]
|
|
247
|
+
environment = GENERAL_ENV
|
|
248
|
+
|
|
249
|
+
class Inputs(IOModel):
|
|
250
|
+
input_image: Annotated[
|
|
251
|
+
Path,
|
|
252
|
+
ImageSpec(
|
|
253
|
+
layouts={
|
|
254
|
+
Layout.VOLUMETRIC_CHANNEL,
|
|
255
|
+
Layout.PLANAR_TIME_CHANNEL,
|
|
256
|
+
Layout.VOLUMETRIC_TIME,
|
|
257
|
+
}
|
|
258
|
+
),
|
|
259
|
+
GUIMeta(
|
|
260
|
+
display_name="Input image",
|
|
261
|
+
description="Image to slice. Axes are inferred from dimensionality and selected indices.",
|
|
262
|
+
connectable=Connectable.BY_DEFAULT,
|
|
263
|
+
),
|
|
264
|
+
]
|
|
265
|
+
layout: Annotated[str, GUIMeta(
|
|
266
|
+
display_name="Layout",
|
|
267
|
+
description="Axis order for the input image, such as CZYX, TCYX, or TZYX.",
|
|
268
|
+
connectable=Connectable.NEVER,
|
|
269
|
+
)] = "CZYX"
|
|
270
|
+
channel: Annotated[int | None, GUIMeta(
|
|
271
|
+
display_name="Channel",
|
|
272
|
+
description="Optional index for the C axis.",
|
|
273
|
+
min=0,
|
|
274
|
+
step=1,
|
|
275
|
+
)] = None
|
|
276
|
+
z: Annotated[int | None, GUIMeta(
|
|
277
|
+
display_name="Z",
|
|
278
|
+
description="Optional index for the Z axis.",
|
|
279
|
+
min=0,
|
|
280
|
+
step=1,
|
|
281
|
+
)] = None
|
|
282
|
+
timepoint: Annotated[int | None, GUIMeta(
|
|
283
|
+
display_name="Timepoint",
|
|
284
|
+
description="Optional index for the T axis.",
|
|
285
|
+
min=0,
|
|
286
|
+
step=1,
|
|
287
|
+
)] = None
|
|
288
|
+
|
|
289
|
+
class Outputs(IOModel):
|
|
290
|
+
output_image: Annotated[
|
|
291
|
+
Path,
|
|
292
|
+
ImageSpec(semantics={Semantic.INTENSITY}),
|
|
293
|
+
GUIMeta(
|
|
294
|
+
display_name="Selected image",
|
|
295
|
+
description="Image after requested dimension selection.",
|
|
296
|
+
),
|
|
297
|
+
] = Template("{input_image.stem}_selected{ext}")
|
|
298
|
+
|
|
299
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
300
|
+
data = _read_image(arguments.input_image)
|
|
301
|
+
selected = _select_dimensions(
|
|
302
|
+
data,
|
|
303
|
+
layout=arguments.layout,
|
|
304
|
+
channel=arguments.channel,
|
|
305
|
+
z=arguments.z,
|
|
306
|
+
timepoint=arguments.timepoint,
|
|
307
|
+
)
|
|
308
|
+
output_path = Path(arguments.output_image)
|
|
309
|
+
_write_image(selected, output_path)
|
|
310
|
+
return self.Outputs(output_image=output_path)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class SelectTimepoint(ProcessingTool):
|
|
314
|
+
"""Select one timepoint from an image using a declared layout."""
|
|
315
|
+
|
|
316
|
+
display_name = "Select Timepoint"
|
|
317
|
+
documentation = "Select one zero-based T index from a declared image layout."
|
|
318
|
+
category = Category.IMAGE_PROCESSING
|
|
319
|
+
tags = ["io", "dimension-selection", "time"]
|
|
320
|
+
environment = GENERAL_ENV
|
|
321
|
+
|
|
322
|
+
class Inputs(IOModel):
|
|
323
|
+
input_image: Annotated[Path, ImageSpec(), GUIMeta(
|
|
324
|
+
display_name="Input image",
|
|
325
|
+
description="Image to slice.",
|
|
326
|
+
connectable=Connectable.BY_DEFAULT,
|
|
327
|
+
)]
|
|
328
|
+
layout: Annotated[str, GUIMeta(
|
|
329
|
+
display_name="Layout",
|
|
330
|
+
description="Declared axis order containing T.",
|
|
331
|
+
connectable=Connectable.NEVER,
|
|
332
|
+
)]
|
|
333
|
+
timepoint: Annotated[int, GUIMeta(
|
|
334
|
+
display_name="Timepoint",
|
|
335
|
+
description="Zero-based T index.",
|
|
336
|
+
min=0,
|
|
337
|
+
step=1,
|
|
338
|
+
)] = 0
|
|
339
|
+
|
|
340
|
+
class Outputs(IOModel):
|
|
341
|
+
output_image: Annotated[
|
|
342
|
+
Path,
|
|
343
|
+
ImageSpec(semantics={Semantic.INTENSITY}),
|
|
344
|
+
GUIMeta(display_name="Selected timepoint"),
|
|
345
|
+
] = Template("{input_image.stem}_t{timepoint}{ext}")
|
|
346
|
+
|
|
347
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
348
|
+
data = _read_image(arguments.input_image)
|
|
349
|
+
selected = _select_dimensions(
|
|
350
|
+
data,
|
|
351
|
+
layout=arguments.layout,
|
|
352
|
+
channel=None,
|
|
353
|
+
z=None,
|
|
354
|
+
timepoint=arguments.timepoint,
|
|
355
|
+
)
|
|
356
|
+
output_path = Path(arguments.output_image)
|
|
357
|
+
_write_image(selected, output_path)
|
|
358
|
+
return self.Outputs(output_image=output_path)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class SelectChannel(ProcessingTool):
|
|
362
|
+
"""Select one channel from an image using a declared layout."""
|
|
363
|
+
|
|
364
|
+
display_name = "Select Channel"
|
|
365
|
+
documentation = "Select one zero-based C index from a declared image layout."
|
|
366
|
+
category = Category.IMAGE_PROCESSING
|
|
367
|
+
tags = ["io", "dimension-selection", "channel"]
|
|
368
|
+
environment = GENERAL_ENV
|
|
369
|
+
|
|
370
|
+
class Inputs(IOModel):
|
|
371
|
+
input_image: Annotated[Path, ImageSpec(), GUIMeta(
|
|
372
|
+
display_name="Input image",
|
|
373
|
+
description="Image to slice.",
|
|
374
|
+
connectable=Connectable.BY_DEFAULT,
|
|
375
|
+
)]
|
|
376
|
+
layout: Annotated[str, GUIMeta(
|
|
377
|
+
display_name="Layout",
|
|
378
|
+
description="Declared axis order containing C.",
|
|
379
|
+
connectable=Connectable.NEVER,
|
|
380
|
+
)]
|
|
381
|
+
channel: Annotated[int, GUIMeta(
|
|
382
|
+
display_name="Channel",
|
|
383
|
+
description="Zero-based C index.",
|
|
384
|
+
min=0,
|
|
385
|
+
step=1,
|
|
386
|
+
)] = 0
|
|
387
|
+
|
|
388
|
+
class Outputs(IOModel):
|
|
389
|
+
output_image: Annotated[
|
|
390
|
+
Path,
|
|
391
|
+
ImageSpec(semantics={Semantic.INTENSITY}),
|
|
392
|
+
GUIMeta(display_name="Selected channel"),
|
|
393
|
+
] = Template("{input_image.stem}_c{channel}{ext}")
|
|
394
|
+
|
|
395
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
396
|
+
data = _read_image(arguments.input_image)
|
|
397
|
+
selected = _select_dimensions(
|
|
398
|
+
data,
|
|
399
|
+
layout=arguments.layout,
|
|
400
|
+
channel=arguments.channel,
|
|
401
|
+
z=None,
|
|
402
|
+
timepoint=None,
|
|
403
|
+
)
|
|
404
|
+
output_path = Path(arguments.output_image)
|
|
405
|
+
_write_image(selected, output_path)
|
|
406
|
+
return self.Outputs(output_image=output_path)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
class SelectZRange(ProcessingTool):
|
|
410
|
+
"""Select a Z slab from an image using Python-style slice bounds."""
|
|
411
|
+
|
|
412
|
+
display_name = "Select Z Range"
|
|
413
|
+
documentation = "Select a start-inclusive, stop-exclusive Z range from a declared layout."
|
|
414
|
+
category = Category.IMAGE_PROCESSING
|
|
415
|
+
tags = ["io", "dimension-selection", "z"]
|
|
416
|
+
environment = GENERAL_ENV
|
|
417
|
+
|
|
418
|
+
class Inputs(IOModel):
|
|
419
|
+
input_image: Annotated[Path, ImageSpec(), GUIMeta(
|
|
420
|
+
display_name="Input image",
|
|
421
|
+
description="Image to slice.",
|
|
422
|
+
connectable=Connectable.BY_DEFAULT,
|
|
423
|
+
)]
|
|
424
|
+
layout: Annotated[str, GUIMeta(
|
|
425
|
+
display_name="Layout",
|
|
426
|
+
description="Declared axis order containing Z.",
|
|
427
|
+
connectable=Connectable.NEVER,
|
|
428
|
+
)]
|
|
429
|
+
start_z: Annotated[int, GUIMeta(
|
|
430
|
+
display_name="Start Z",
|
|
431
|
+
description="Start-inclusive zero-based Z index.",
|
|
432
|
+
min=0,
|
|
433
|
+
step=1,
|
|
434
|
+
)] = 0
|
|
435
|
+
stop_z: Annotated[int | None, GUIMeta(
|
|
436
|
+
display_name="Stop Z",
|
|
437
|
+
description="Stop-exclusive Z index. Leave empty to keep through the end.",
|
|
438
|
+
min=0,
|
|
439
|
+
step=1,
|
|
440
|
+
)] = None
|
|
441
|
+
|
|
442
|
+
class Outputs(IOModel):
|
|
443
|
+
output_image: Annotated[
|
|
444
|
+
Path,
|
|
445
|
+
ImageSpec(semantics={Semantic.INTENSITY}),
|
|
446
|
+
GUIMeta(display_name="Selected Z range"),
|
|
447
|
+
] = Template("{input_image.stem}_z{start_z}_{stop_z}{ext}")
|
|
448
|
+
|
|
449
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
450
|
+
data = _read_image(arguments.input_image)
|
|
451
|
+
selected = _select_z_range(
|
|
452
|
+
data,
|
|
453
|
+
layout=arguments.layout,
|
|
454
|
+
start_z=arguments.start_z,
|
|
455
|
+
stop_z=arguments.stop_z,
|
|
456
|
+
)
|
|
457
|
+
output_path = Path(arguments.output_image)
|
|
458
|
+
_write_image(selected, output_path)
|
|
459
|
+
return self.Outputs(output_image=output_path)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
class ConvertToOmeTiff(ProcessingTool):
|
|
463
|
+
"""Convert an image file to OME-TIFF using tifffile."""
|
|
464
|
+
|
|
465
|
+
display_name = "Convert to OME-TIFF"
|
|
466
|
+
documentation = (
|
|
467
|
+
"Read an image file and convert it to OME-TIFF with explicit OME axis metadata."
|
|
468
|
+
)
|
|
469
|
+
category = Category.CONVERSION
|
|
470
|
+
tags = ["io", "conversion", "ome-tiff"]
|
|
471
|
+
environment = GENERAL_ENV
|
|
472
|
+
|
|
473
|
+
class Inputs(IOModel):
|
|
474
|
+
input_image: Annotated[
|
|
475
|
+
Path,
|
|
476
|
+
ImageSpec(),
|
|
477
|
+
GUIMeta(
|
|
478
|
+
display_name="Input image",
|
|
479
|
+
description="Image file to convert to OME-TIFF.",
|
|
480
|
+
connectable=Connectable.BY_DEFAULT,
|
|
481
|
+
),
|
|
482
|
+
]
|
|
483
|
+
dimension_order: Annotated[str | None, GUIMeta(
|
|
484
|
+
display_name="Dimension order",
|
|
485
|
+
description="Optional OME axis order. Defaults are inferred from image dimensionality.",
|
|
486
|
+
connectable=Connectable.NEVER,
|
|
487
|
+
)] = None
|
|
488
|
+
|
|
489
|
+
class Outputs(IOModel):
|
|
490
|
+
output_image: Annotated[
|
|
491
|
+
Path,
|
|
492
|
+
ImageSpec(formats={"ome-tiff"}),
|
|
493
|
+
GUIMeta(
|
|
494
|
+
display_name="OME-TIFF image",
|
|
495
|
+
description="Converted OME-TIFF image.",
|
|
496
|
+
),
|
|
497
|
+
] = Template("{input_image.stem}.ome.tiff")
|
|
498
|
+
|
|
499
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
500
|
+
import imageio.v3 as iio
|
|
501
|
+
import tifffile
|
|
502
|
+
|
|
503
|
+
output_path = Path(arguments.output_image)
|
|
504
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
505
|
+
data = iio.imread(arguments.input_image)
|
|
506
|
+
axes = _dimension_order_for_shape(data.shape, arguments.dimension_order)
|
|
507
|
+
tifffile.imwrite(output_path, data, ome=True, metadata={"axes": axes})
|
|
508
|
+
return self.Outputs(output_image=output_path)
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
class ConvertToOmeZarr(ProcessingTool):
|
|
512
|
+
"""Convert an image file to a minimal OME-NGFF/Zarr v2 directory."""
|
|
513
|
+
|
|
514
|
+
display_name = "Convert to OME-Zarr"
|
|
515
|
+
documentation = (
|
|
516
|
+
"Read an image file and convert it to a single-scale uncompressed OME-Zarr v2 directory."
|
|
517
|
+
)
|
|
518
|
+
category = Category.CONVERSION
|
|
519
|
+
tags = ["io", "conversion", "ome-zarr", "zarr"]
|
|
520
|
+
environment = GENERAL_ENV
|
|
521
|
+
|
|
522
|
+
class Inputs(IOModel):
|
|
523
|
+
input_image: Annotated[
|
|
524
|
+
Path,
|
|
525
|
+
ImageSpec(),
|
|
526
|
+
GUIMeta(
|
|
527
|
+
display_name="Input image",
|
|
528
|
+
description="Image file to convert to OME-Zarr.",
|
|
529
|
+
connectable=Connectable.BY_DEFAULT,
|
|
530
|
+
),
|
|
531
|
+
]
|
|
532
|
+
|
|
533
|
+
class Outputs(IOModel):
|
|
534
|
+
output_image: Annotated[
|
|
535
|
+
Path,
|
|
536
|
+
ImageSpec(formats={"ome-zarr"}),
|
|
537
|
+
GUIMeta(
|
|
538
|
+
display_name="OME-Zarr path",
|
|
539
|
+
description="Converted OME-Zarr directory.",
|
|
540
|
+
),
|
|
541
|
+
] = Template("{input_image.stem}.ome.zarr")
|
|
542
|
+
|
|
543
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
544
|
+
import imageio.v3 as iio
|
|
545
|
+
|
|
546
|
+
output_path = Path(arguments.output_image)
|
|
547
|
+
data = iio.imread(arguments.input_image)
|
|
548
|
+
_write_minimal_ome_zarr(data, output_path)
|
|
549
|
+
return self.Outputs(output_image=output_path)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _read_image_for_conversion(arguments: Arguments) -> Any:
|
|
553
|
+
data = (
|
|
554
|
+
_read_scene(arguments.input_image, arguments.scene)
|
|
555
|
+
if arguments.scene is not None
|
|
556
|
+
else _read_image(arguments.input_image)
|
|
557
|
+
)
|
|
558
|
+
if any(
|
|
559
|
+
selection is not None
|
|
560
|
+
for selection in (arguments.channel, arguments.z, arguments.timepoint)
|
|
561
|
+
):
|
|
562
|
+
if arguments.input_layout is None:
|
|
563
|
+
raise ValueError(
|
|
564
|
+
"input_layout is required when selecting channel, z, or timepoint."
|
|
565
|
+
)
|
|
566
|
+
data = _select_dimensions(
|
|
567
|
+
data,
|
|
568
|
+
layout=arguments.input_layout,
|
|
569
|
+
channel=arguments.channel,
|
|
570
|
+
z=arguments.z,
|
|
571
|
+
timepoint=arguments.timepoint,
|
|
572
|
+
)
|
|
573
|
+
return data
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _select_dimensions(
|
|
577
|
+
data: Any,
|
|
578
|
+
*,
|
|
579
|
+
layout: str,
|
|
580
|
+
channel: int | None,
|
|
581
|
+
z: int | None,
|
|
582
|
+
timepoint: int | None,
|
|
583
|
+
) -> Any:
|
|
584
|
+
normalized_layout = _validate_layout_for_data(data, layout)
|
|
585
|
+
|
|
586
|
+
selectors: list[int | slice] = [slice(None)] * data.ndim
|
|
587
|
+
for axis, index in {"T": timepoint, "C": channel, "Z": z}.items():
|
|
588
|
+
if index is None:
|
|
589
|
+
continue
|
|
590
|
+
if axis not in normalized_layout:
|
|
591
|
+
raise ValueError(f"Cannot select {axis}: layout {layout!r} has no {axis} axis.")
|
|
592
|
+
selectors[normalized_layout.index(axis)] = index
|
|
593
|
+
return data[tuple(selectors)]
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _select_z_range(
|
|
597
|
+
data: Any,
|
|
598
|
+
*,
|
|
599
|
+
layout: str,
|
|
600
|
+
start_z: int,
|
|
601
|
+
stop_z: int | None,
|
|
602
|
+
) -> Any:
|
|
603
|
+
normalized_layout = _validate_layout_for_data(data, layout)
|
|
604
|
+
if "Z" not in normalized_layout:
|
|
605
|
+
raise ValueError(f"Cannot select Z: layout {layout!r} has no Z axis.")
|
|
606
|
+
if stop_z is not None and stop_z < start_z:
|
|
607
|
+
raise ValueError("stop_z must be greater than or equal to start_z.")
|
|
608
|
+
selectors: list[int | slice] = [slice(None)] * data.ndim
|
|
609
|
+
selectors[normalized_layout.index("Z")] = slice(start_z, stop_z)
|
|
610
|
+
return data[tuple(selectors)]
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def _validate_layout_for_data(data: Any, layout: str) -> str:
|
|
614
|
+
normalized_layout = layout.upper()
|
|
615
|
+
allowed_axes = {"T", "C", "Z", "Y", "X"}
|
|
616
|
+
unknown_axes = sorted(set(normalized_layout) - allowed_axes)
|
|
617
|
+
if unknown_axes:
|
|
618
|
+
raise ValueError(
|
|
619
|
+
f"Layout {layout!r} contains unknown axes: {''.join(unknown_axes)}."
|
|
620
|
+
)
|
|
621
|
+
if len(normalized_layout) != data.ndim:
|
|
622
|
+
raise ValueError(
|
|
623
|
+
f"Layout {layout!r} has {len(normalized_layout)} axes, "
|
|
624
|
+
f"but image has {data.ndim} dimensions."
|
|
625
|
+
)
|
|
626
|
+
if len(set(normalized_layout)) != len(normalized_layout):
|
|
627
|
+
raise ValueError(f"Layout {layout!r} contains duplicate axes.")
|
|
628
|
+
return normalized_layout
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _read_image(input_image: Path | str) -> Any:
|
|
632
|
+
import imageio.v3 as iio
|
|
633
|
+
|
|
634
|
+
return iio.imread(input_image)
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def _channel_names_for_axes(shape: tuple[int, ...], axes: str) -> list[str]:
|
|
638
|
+
if "C" not in axes:
|
|
639
|
+
return []
|
|
640
|
+
channel_count = int(shape[axes.index("C")])
|
|
641
|
+
return [f"channel_{index}" for index in range(channel_count)]
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def _pixel_sizes_from_metadata(input_image: Path | str) -> dict[str, float | None]:
|
|
645
|
+
pixel_sizes: dict[str, float | None] = {"X": None, "Y": None, "Z": None}
|
|
646
|
+
path = Path(input_image)
|
|
647
|
+
if not _is_tiff_path(path):
|
|
648
|
+
return pixel_sizes
|
|
649
|
+
|
|
650
|
+
try:
|
|
651
|
+
import tifffile
|
|
652
|
+
|
|
653
|
+
with tifffile.TiffFile(path) as tif:
|
|
654
|
+
if tif.ome_metadata:
|
|
655
|
+
return _pixel_sizes_from_ome_xml(tif.ome_metadata)
|
|
656
|
+
series = tif.series[0] if tif.series else None
|
|
657
|
+
if series is not None and getattr(series, "levels", None):
|
|
658
|
+
metadata = getattr(series.levels[0], "metadata", None) or {}
|
|
659
|
+
else:
|
|
660
|
+
metadata = {}
|
|
661
|
+
physical_size_x = metadata.get("PhysicalSizeX")
|
|
662
|
+
physical_size_y = metadata.get("PhysicalSizeY")
|
|
663
|
+
physical_size_z = metadata.get("PhysicalSizeZ")
|
|
664
|
+
pixel_sizes["X"] = float(physical_size_x) if physical_size_x else None
|
|
665
|
+
pixel_sizes["Y"] = float(physical_size_y) if physical_size_y else None
|
|
666
|
+
pixel_sizes["Z"] = float(physical_size_z) if physical_size_z else None
|
|
667
|
+
except Exception:
|
|
668
|
+
return pixel_sizes
|
|
669
|
+
return pixel_sizes
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _pixel_sizes_from_ome_xml(ome_xml: str) -> dict[str, float | None]:
|
|
673
|
+
pixel_sizes: dict[str, float | None] = {"X": None, "Y": None, "Z": None}
|
|
674
|
+
root = ET.fromstring(ome_xml)
|
|
675
|
+
pixels = root.find(".//{*}Pixels")
|
|
676
|
+
if pixels is None:
|
|
677
|
+
return pixel_sizes
|
|
678
|
+
for axis in pixel_sizes:
|
|
679
|
+
value = pixels.attrib.get(f"PhysicalSize{axis}")
|
|
680
|
+
pixel_sizes[axis] = float(value) if value else None
|
|
681
|
+
return pixel_sizes
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def _read_scene(input_image: Path | str, scene: int) -> Any:
|
|
685
|
+
import imageio.v3 as iio
|
|
686
|
+
|
|
687
|
+
path = Path(input_image)
|
|
688
|
+
if scene < 0:
|
|
689
|
+
raise IndexError(f"Scene index {scene} is invalid; scene indexes are zero-based.")
|
|
690
|
+
|
|
691
|
+
if _is_tiff_path(path):
|
|
692
|
+
import tifffile
|
|
693
|
+
|
|
694
|
+
with tifffile.TiffFile(path) as tif:
|
|
695
|
+
if scene < len(tif.series):
|
|
696
|
+
return tif.series[scene].asarray()
|
|
697
|
+
if scene != 0:
|
|
698
|
+
raise IndexError(
|
|
699
|
+
f"Scene index {scene} is out of range for {len(tif.series)} series."
|
|
700
|
+
)
|
|
701
|
+
|
|
702
|
+
if scene == 0:
|
|
703
|
+
return iio.imread(path)
|
|
704
|
+
raise IndexError(f"Scene index {scene} is only available for multi-series TIFF files.")
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _write_image(data: Any, output_path: Path, *, dimension_order: str | None = None) -> None:
|
|
708
|
+
import tifffile
|
|
709
|
+
|
|
710
|
+
output_path = Path(output_path)
|
|
711
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
712
|
+
if _is_ome_zarr_path(output_path):
|
|
713
|
+
_write_minimal_ome_zarr(data, output_path)
|
|
714
|
+
elif _is_ome_tiff_path(output_path):
|
|
715
|
+
axes = _dimension_order_for_shape(data.shape, dimension_order)
|
|
716
|
+
tifffile.imwrite(output_path, data, ome=True, metadata={"axes": axes})
|
|
717
|
+
else:
|
|
718
|
+
_write_tiff_safe_image(output_path, data)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _write_tiff_safe_image(output_path: Path, data: Any) -> None:
|
|
722
|
+
import imageio.v3 as iio
|
|
723
|
+
import numpy as np
|
|
724
|
+
|
|
725
|
+
array = np.asarray(data)
|
|
726
|
+
kwargs: dict[str, str] = {}
|
|
727
|
+
if _is_tiff_path(output_path) and _is_grayscale_stack(array):
|
|
728
|
+
kwargs["photometric"] = "minisblack"
|
|
729
|
+
iio.imwrite(output_path, array, **kwargs)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _is_grayscale_stack(array: Any) -> bool:
|
|
733
|
+
if array.ndim < 3:
|
|
734
|
+
return False
|
|
735
|
+
if array.ndim == 3 and array.shape[-1] in {3, 4}:
|
|
736
|
+
return False
|
|
737
|
+
return True
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _is_tiff_path(path: Path) -> bool:
|
|
741
|
+
return path.suffix.lower() in {".tif", ".tiff"}
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def _is_ome_tiff_path(path: Path) -> bool:
|
|
745
|
+
name = path.name.lower()
|
|
746
|
+
return name.endswith(".ome.tif") or name.endswith(".ome.tiff")
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def _is_ome_zarr_path(path: Path) -> bool:
|
|
750
|
+
return path.name.lower().endswith(".ome.zarr")
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def _dimension_order_for_shape(shape: tuple[int, ...], dimension_order: str | None) -> str:
|
|
754
|
+
if dimension_order is not None:
|
|
755
|
+
normalized = dimension_order.upper()
|
|
756
|
+
if len(normalized) != len(shape):
|
|
757
|
+
raise ValueError(
|
|
758
|
+
f"Dimension order {dimension_order!r} has {len(normalized)} axes, "
|
|
759
|
+
f"but image has {len(shape)} dimensions."
|
|
760
|
+
)
|
|
761
|
+
return normalized
|
|
762
|
+
|
|
763
|
+
default_by_ndim = {
|
|
764
|
+
2: "YX",
|
|
765
|
+
3: "ZYX",
|
|
766
|
+
4: "CZYX",
|
|
767
|
+
5: "TCZYX",
|
|
768
|
+
}
|
|
769
|
+
if len(shape) not in default_by_ndim:
|
|
770
|
+
raise ValueError(
|
|
771
|
+
f"Cannot infer OME dimension order for {len(shape)}D image; "
|
|
772
|
+
"set dimension_order explicitly."
|
|
773
|
+
)
|
|
774
|
+
return default_by_ndim[len(shape)]
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def _axes_guess_for_shape(shape: tuple[int, ...]) -> str:
|
|
778
|
+
default_by_ndim = {
|
|
779
|
+
2: "YX",
|
|
780
|
+
3: "ZYX",
|
|
781
|
+
4: "CZYX",
|
|
782
|
+
5: "TCZYX",
|
|
783
|
+
}
|
|
784
|
+
return default_by_ndim.get(len(shape), ",".join(f"D{i}" for i in range(len(shape))))
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def _write_minimal_ome_zarr(data: Any, output_path: Path) -> None:
|
|
788
|
+
import numpy as np
|
|
789
|
+
|
|
790
|
+
array = np.asarray(data)
|
|
791
|
+
output_path.mkdir(parents=True, exist_ok=True)
|
|
792
|
+
level_path = output_path / "0"
|
|
793
|
+
level_path.mkdir(exist_ok=True)
|
|
794
|
+
|
|
795
|
+
axes = _axes_for_shape(array.shape)
|
|
796
|
+
(output_path / ".zgroup").write_text(json.dumps({"zarr_format": 2}))
|
|
797
|
+
(output_path / ".zattrs").write_text(
|
|
798
|
+
json.dumps(
|
|
799
|
+
{
|
|
800
|
+
"multiscales": [
|
|
801
|
+
{
|
|
802
|
+
"version": "0.4",
|
|
803
|
+
"axes": [{"name": axis, "type": _axis_type(axis)} for axis in axes],
|
|
804
|
+
"datasets": [{"path": "0"}],
|
|
805
|
+
}
|
|
806
|
+
]
|
|
807
|
+
}
|
|
808
|
+
)
|
|
809
|
+
)
|
|
810
|
+
(level_path / ".zarray").write_text(
|
|
811
|
+
json.dumps(
|
|
812
|
+
{
|
|
813
|
+
"zarr_format": 2,
|
|
814
|
+
"shape": list(array.shape),
|
|
815
|
+
"chunks": list(array.shape),
|
|
816
|
+
"dtype": array.dtype.str,
|
|
817
|
+
"compressor": None,
|
|
818
|
+
"fill_value": 0,
|
|
819
|
+
"order": "C",
|
|
820
|
+
"filters": None,
|
|
821
|
+
}
|
|
822
|
+
)
|
|
823
|
+
)
|
|
824
|
+
chunk_key = ".".join("0" for _ in array.shape) if array.ndim else "0"
|
|
825
|
+
(level_path / chunk_key).write_bytes(np.ascontiguousarray(array).tobytes(order="C"))
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _axes_for_shape(shape: tuple[int, ...]) -> list[str]:
|
|
829
|
+
names_by_ndim = {
|
|
830
|
+
2: ["y", "x"],
|
|
831
|
+
3: ["z", "y", "x"],
|
|
832
|
+
4: ["c", "z", "y", "x"],
|
|
833
|
+
5: ["t", "c", "z", "y", "x"],
|
|
834
|
+
}
|
|
835
|
+
return names_by_ndim.get(len(shape), [f"dim_{i}" for i in range(len(shape))])
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def _axis_type(axis: str) -> str:
|
|
839
|
+
if axis == "t":
|
|
840
|
+
return "time"
|
|
841
|
+
if axis == "c":
|
|
842
|
+
return "channel"
|
|
843
|
+
return "space"
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bioimageflow-io-tools
|
|
3
|
+
Version: 0.1.6
|
|
4
|
+
Summary: Lightweight image IO tools for BioImageFlow
|
|
5
|
+
Project-URL: Homepage, https://github.com/bioimageit/bioimageflow
|
|
6
|
+
Project-URL: Repository, https://github.com/bioimageit/bioimageflow
|
|
7
|
+
Project-URL: Issues, https://github.com/bioimageit/bioimageflow/issues
|
|
8
|
+
Author: BioImageFlow Contributors
|
|
9
|
+
License-Expression: BSD-4-Clause
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: bioimage-analysis,bioimageflow,microscopy,workflow
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: bioimageflow-core<0.2,>=0.1.6
|
|
24
|
+
Requires-Dist: imageio
|
|
25
|
+
Requires-Dist: numpy
|
|
26
|
+
Requires-Dist: tifffile
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# bioimageflow-io-tools
|
|
30
|
+
|
|
31
|
+
Optional BioImageFlow package for image ingestion, metadata inspection, axis validation, slicing, lightweight format conversion, and explicit bioio/plugin-backed conversion.
|
|
32
|
+
|
|
33
|
+
Core libraries for lightweight tools are imageio, NumPy, tifffile, and the package's minimal OME-Zarr writer.
|
|
34
|
+
`BioIOConvertImage` declares a separate bioio/plugin-backed runtime for broad formats such as CZI and OME-Zarr.
|
|
35
|
+
|
|
36
|
+
## Tools
|
|
37
|
+
|
|
38
|
+
- `ReadImageMetadata`
|
|
39
|
+
- `ValidateImageLayout`
|
|
40
|
+
- `ConvertImageFormat`
|
|
41
|
+
- `BioIOConvertImage`
|
|
42
|
+
- `ConvertToOmeTiff`
|
|
43
|
+
- `ConvertToOmeZarr`
|
|
44
|
+
- `SelectScene`
|
|
45
|
+
- `SelectTimepoint`
|
|
46
|
+
- `SelectChannel`
|
|
47
|
+
- `SelectZRange`
|
|
48
|
+
- `SelectDimensions`
|
|
49
|
+
|
|
50
|
+
Use `BioIOConvertImage` for microscopy formats that need scene, channel, Z, timepoint, or dimension-order handling.
|
|
51
|
+
Use `ConvertImageFormat` for simple imageio/tifffile conversions.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
bioimageflow_io_tools/__init__.py,sha256=evSxU3VFmvuLQVRbKlXcSgTl4Dg6l9ou9hH6kGy0Mqc,2046
|
|
2
|
+
bioimageflow_io_tools/bioio_convert.py,sha256=S5RSVRRWqrVWtAe8HexOtTDh3z7f7X3VDd15-lK-BKo,6456
|
|
3
|
+
bioimageflow_io_tools/image_io.py,sha256=j6fLcD96OAa4bhfQwPwMnAuib2c1NuepYW7olHmzvoc,29248
|
|
4
|
+
bioimageflow_io_tools-0.1.6.dist-info/METADATA,sha256=U-_TeH_LDe488ebAd19MvDj7GaHmI778rRCqlRz6Ryw,2021
|
|
5
|
+
bioimageflow_io_tools-0.1.6.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
6
|
+
bioimageflow_io_tools-0.1.6.dist-info/licenses/LICENSE,sha256=JOhTAv94edQPgJ-ag70pmrEvSXwdv1zCv9uP3g_4m1Y,1701
|
|
7
|
+
bioimageflow_io_tools-0.1.6.dist-info/RECORD,,
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
BSD 4-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, BioImageFlow Contributors
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
11
|
+
|
|
12
|
+
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the BioImageFlow Contributors.
|
|
13
|
+
|
|
14
|
+
4. Neither the name of BioImageFlow nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
15
|
+
|
|
16
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
|
17
|
+
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT, INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|