bioimageflow-segmentation-tools 0.3.2__tar.gz → 0.5.0__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.
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/PKG-INFO +16 -5
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/README.md +14 -3
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/__init__.py +11 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/_arrays.py +6 -0
- bioimageflow_segmentation_tools-0.5.0/bioimageflow_segmentation_tools/_cellpose.py +252 -0
- bioimageflow_segmentation_tools-0.5.0/bioimageflow_segmentation_tools/_tiff.py +130 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/cellpose_sam.py +84 -45
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/cellpose_v3.py +79 -55
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/classical.py +9 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/instanseg_segmenter.py +6 -0
- bioimageflow_segmentation_tools-0.5.0/bioimageflow_segmentation_tools/intranuclear_candidates.py +258 -0
- bioimageflow_segmentation_tools-0.5.0/bioimageflow_segmentation_tools/intranuclear_enhancement.py +168 -0
- bioimageflow_segmentation_tools-0.5.0/bioimageflow_segmentation_tools/intranuclear_shape_filter.py +194 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/nagini3d_segmenter.py +6 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/bioimageflow_segmentation_tools/stardist_segmenter.py +40 -19
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/index.md +4 -0
- bioimageflow_segmentation_tools-0.5.0/docs/tools/cellpose3.md +74 -0
- bioimageflow_segmentation_tools-0.5.0/docs/tools/cellpose_sam.md +61 -0
- bioimageflow_segmentation_tools-0.5.0/docs/tools/stardist_segmenter.md +54 -0
- bioimageflow_segmentation_tools-0.5.0/docs/workflows/intranuclear_filament_candidates.md +27 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/pyproject.toml +2 -2
- bioimageflow_segmentation_tools-0.5.0/tests/test_calibrated_segmentation.py +212 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/tests/test_schema.py +9 -0
- bioimageflow_segmentation_tools-0.5.0/tests/test_volumetric_models.py +249 -0
- bioimageflow_segmentation_tools-0.3.2/docs/tools/cellpose3.md +0 -53
- bioimageflow_segmentation_tools-0.3.2/docs/tools/cellpose_sam.md +0 -16
- bioimageflow_segmentation_tools-0.3.2/docs/tools/stardist_segmenter.md +0 -55
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/.gitignore +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/LICENSE +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/images/README.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/distance_watershed_segment.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/filter_labels.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/instanseg_segmenter.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/local_threshold_segment.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/nagini3d_segmenter.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/otsu_threshold_segment.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/postprocess_labels.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/split_touching_objects.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/threshold_segment.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/tools/watershed_segment.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/workflows/bbbc038_segmentation_benchmark.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/workflows/instanseg_cell_segmentation.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/docs/workflows/nagini3d_caps_segmentation.md +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/tests/conftest.py +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/tests/test_execution.py +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/tests/test_instanseg_runtime.py +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/tests/test_model_adapters.py +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/tests/test_model_content_identity.py +0 -0
- {bioimageflow_segmentation_tools-0.3.2 → bioimageflow_segmentation_tools-0.5.0}/tests/test_nagini_runtime.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: bioimageflow-segmentation-tools
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Segmentation tools for BioImageFlow
|
|
5
5
|
Project-URL: Homepage, https://github.com/Inria-SAIRPICO/bioimageflow
|
|
6
6
|
Project-URL: Documentation, https://bioimageflow.readthedocs.io/latest/
|
|
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
21
21
|
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
22
22
|
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
23
23
|
Requires-Python: >=3.10
|
|
24
|
-
Requires-Dist: bioimageflow-core<0.
|
|
24
|
+
Requires-Dist: bioimageflow-core<0.7,>=0.6.0
|
|
25
25
|
Description-Content-Type: text/markdown
|
|
26
26
|
|
|
27
27
|
# bioimageflow-segmentation-tools
|
|
@@ -30,9 +30,9 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
30
30
|
|
|
31
31
|
## Tools
|
|
32
32
|
|
|
33
|
-
- `Cellpose3`: Cellpose v3 pretrained model wrapper.
|
|
34
|
-
- `CellposeSAM`: Cellpose-SAM pretrained model wrapper.
|
|
35
|
-
- `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
|
|
33
|
+
- `Cellpose3`: Cellpose v3 pretrained model wrapper for 2D images and 3D volumes.
|
|
34
|
+
- `CellposeSAM`: Cellpose-SAM pretrained model wrapper for 2D images and 3D volumes.
|
|
35
|
+
- `StarDistSegmenter`: StarDist 2D/3D pretrained model wrapper.
|
|
36
36
|
- `InstanSegSegment`: selected-target nuclei or cell segmentation with named or local InstanSeg models.
|
|
37
37
|
- `Nagini3DSegment`: volumetric NAGINI-3D segmentation with probability, parametric surfaces, and curvature outputs.
|
|
38
38
|
- `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
|
|
@@ -42,6 +42,9 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
42
42
|
- `DistanceWatershedSegment`: split foreground with marker-free distance-transform watershed.
|
|
43
43
|
- `SplitTouchingObjects`: split clumped labels using distance-transform watershed.
|
|
44
44
|
- `FilterLabels`: remove labels by area, border contact, intensity, and shape constraints.
|
|
45
|
+
- `EnhanceIntranuclearVolume`: feature response, filled nuclear interiors, and boundary distance from calibrated volumes.
|
|
46
|
+
- `FilterIntranuclearShapes`: per-slice hysteresis, physical XY shape filtering, and nuclear rim exclusion.
|
|
47
|
+
- `GroupIntranuclearCandidates`: neighboring-slice support, geometric group labels, measurements, and a review montage.
|
|
45
48
|
- `PostprocessLabels`: remove small labels and relabel label images sequentially.
|
|
46
49
|
|
|
47
50
|
Classical connected-component tools use face connectivity by default and treat `image > threshold` as foreground when `above` is enabled. Label inputs are validated as finite, integral, non-negative arrays, and object counts are based on distinct positive IDs rather than the largest ID.
|
|
@@ -53,6 +56,14 @@ Classical image dependencies and heavy model dependencies are declared in worker
|
|
|
53
56
|
Repeated calls with the same model selection reuse the weights; changing `model_type` or `model_name` replaces the cached model, and `clear_model_cache()` releases it explicitly.
|
|
54
57
|
Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
|
|
55
58
|
|
|
59
|
+
For volumetric Cellpose segmentation, set `do_3D=True` and use ZYX input, CZYX with `channel_axis="first"`, or ZYXC with `channel_axis="last"`.
|
|
60
|
+
Use `anisotropy_from_metadata=True` on calibrated OME-TIFF or supply the native Z/XY voxel spacing ratio explicitly.
|
|
61
|
+
Both wrappers support integer XY mean pooling, per-channel global percentile normalization, runtime resampling control, minimum object size, and 3D flow smoothing.
|
|
62
|
+
The UInt32 masks retain native axes, integer IDs, and available physical calibration.
|
|
63
|
+
Cellpose3 retains the faster `cellpose==3.1.1.1` runtime, which already supports 3D.
|
|
64
|
+
For StarDist volumes, select `model_name="3D_demo"` with the same supported volume layouts.
|
|
65
|
+
Existing 2D defaults are preserved.
|
|
66
|
+
|
|
56
67
|
## NAGINI-3D license boundary
|
|
57
68
|
|
|
58
69
|
`Nagini3DSegment` installs and executes the third-party `nagini3D` runtime, which is distributed under AGPL-3.0.
|
|
@@ -4,9 +4,9 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
4
4
|
|
|
5
5
|
## Tools
|
|
6
6
|
|
|
7
|
-
- `Cellpose3`: Cellpose v3 pretrained model wrapper.
|
|
8
|
-
- `CellposeSAM`: Cellpose-SAM pretrained model wrapper.
|
|
9
|
-
- `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
|
|
7
|
+
- `Cellpose3`: Cellpose v3 pretrained model wrapper for 2D images and 3D volumes.
|
|
8
|
+
- `CellposeSAM`: Cellpose-SAM pretrained model wrapper for 2D images and 3D volumes.
|
|
9
|
+
- `StarDistSegmenter`: StarDist 2D/3D pretrained model wrapper.
|
|
10
10
|
- `InstanSegSegment`: selected-target nuclei or cell segmentation with named or local InstanSeg models.
|
|
11
11
|
- `Nagini3DSegment`: volumetric NAGINI-3D segmentation with probability, parametric surfaces, and curvature outputs.
|
|
12
12
|
- `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
|
|
@@ -16,6 +16,9 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
16
16
|
- `DistanceWatershedSegment`: split foreground with marker-free distance-transform watershed.
|
|
17
17
|
- `SplitTouchingObjects`: split clumped labels using distance-transform watershed.
|
|
18
18
|
- `FilterLabels`: remove labels by area, border contact, intensity, and shape constraints.
|
|
19
|
+
- `EnhanceIntranuclearVolume`: feature response, filled nuclear interiors, and boundary distance from calibrated volumes.
|
|
20
|
+
- `FilterIntranuclearShapes`: per-slice hysteresis, physical XY shape filtering, and nuclear rim exclusion.
|
|
21
|
+
- `GroupIntranuclearCandidates`: neighboring-slice support, geometric group labels, measurements, and a review montage.
|
|
19
22
|
- `PostprocessLabels`: remove small labels and relabel label images sequentially.
|
|
20
23
|
|
|
21
24
|
Classical connected-component tools use face connectivity by default and treat `image > threshold` as foreground when `above` is enabled. Label inputs are validated as finite, integral, non-negative arrays, and object counts are based on distinct positive IDs rather than the largest ID.
|
|
@@ -27,6 +30,14 @@ Classical image dependencies and heavy model dependencies are declared in worker
|
|
|
27
30
|
Repeated calls with the same model selection reuse the weights; changing `model_type` or `model_name` replaces the cached model, and `clear_model_cache()` releases it explicitly.
|
|
28
31
|
Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
|
|
29
32
|
|
|
33
|
+
For volumetric Cellpose segmentation, set `do_3D=True` and use ZYX input, CZYX with `channel_axis="first"`, or ZYXC with `channel_axis="last"`.
|
|
34
|
+
Use `anisotropy_from_metadata=True` on calibrated OME-TIFF or supply the native Z/XY voxel spacing ratio explicitly.
|
|
35
|
+
Both wrappers support integer XY mean pooling, per-channel global percentile normalization, runtime resampling control, minimum object size, and 3D flow smoothing.
|
|
36
|
+
The UInt32 masks retain native axes, integer IDs, and available physical calibration.
|
|
37
|
+
Cellpose3 retains the faster `cellpose==3.1.1.1` runtime, which already supports 3D.
|
|
38
|
+
For StarDist volumes, select `model_name="3D_demo"` with the same supported volume layouts.
|
|
39
|
+
Existing 2D defaults are preserved.
|
|
40
|
+
|
|
30
41
|
## NAGINI-3D license boundary
|
|
31
42
|
|
|
32
43
|
`Nagini3DSegment` installs and executes the third-party `nagini3D` runtime, which is distributed under AGPL-3.0.
|
|
@@ -15,6 +15,9 @@ if TYPE_CHECKING:
|
|
|
15
15
|
from .classical import ThresholdSegment as ThresholdSegment
|
|
16
16
|
from .classical import WatershedSegment as WatershedSegment
|
|
17
17
|
from .instanseg_segmenter import InstanSegSegment as InstanSegSegment
|
|
18
|
+
from .intranuclear_candidates import GroupIntranuclearCandidates as GroupIntranuclearCandidates
|
|
19
|
+
from .intranuclear_enhancement import EnhanceIntranuclearVolume as EnhanceIntranuclearVolume
|
|
20
|
+
from .intranuclear_shape_filter import FilterIntranuclearShapes as FilterIntranuclearShapes
|
|
18
21
|
from .nagini3d_segmenter import Nagini3DSegment as Nagini3DSegment
|
|
19
22
|
from .stardist_segmenter import StarDistSegmenter as StarDistSegmenter
|
|
20
23
|
|
|
@@ -25,6 +28,9 @@ _EXPORTS = {
|
|
|
25
28
|
"DistanceWatershedSegment": ("classical", "DistanceWatershedSegment"),
|
|
26
29
|
"FilterLabels": ("classical", "FilterLabels"),
|
|
27
30
|
"InstanSegSegment": ("instanseg_segmenter", "InstanSegSegment"),
|
|
31
|
+
"GroupIntranuclearCandidates": ("intranuclear_candidates", "GroupIntranuclearCandidates"),
|
|
32
|
+
"EnhanceIntranuclearVolume": ("intranuclear_enhancement", "EnhanceIntranuclearVolume"),
|
|
33
|
+
"FilterIntranuclearShapes": ("intranuclear_shape_filter", "FilterIntranuclearShapes"),
|
|
28
34
|
"LocalThresholdSegment": ("classical", "LocalThresholdSegment"),
|
|
29
35
|
"Nagini3DSegment": ("nagini3d_segmenter", "Nagini3DSegment"),
|
|
30
36
|
"OtsuThresholdSegment": ("classical", "OtsuThresholdSegment"),
|
|
@@ -41,6 +47,9 @@ __all__ = [
|
|
|
41
47
|
"DistanceWatershedSegment",
|
|
42
48
|
"FilterLabels",
|
|
43
49
|
"InstanSegSegment",
|
|
50
|
+
"GroupIntranuclearCandidates",
|
|
51
|
+
"EnhanceIntranuclearVolume",
|
|
52
|
+
"FilterIntranuclearShapes",
|
|
44
53
|
"LocalThresholdSegment",
|
|
45
54
|
"Nagini3DSegment",
|
|
46
55
|
"OtsuThresholdSegment",
|
|
@@ -53,6 +62,8 @@ __all__ = [
|
|
|
53
62
|
|
|
54
63
|
|
|
55
64
|
def __getattr__(name: str) -> Any:
|
|
65
|
+
# Keep model families independent at import time; their incompatible ML
|
|
66
|
+
# runtimes are imported only when the selected tool runs in its environment.
|
|
56
67
|
try:
|
|
57
68
|
module_name, attribute_name = _EXPORTS[name]
|
|
58
69
|
except KeyError as exc:
|
|
@@ -44,6 +44,8 @@ def validate_labels(
|
|
|
44
44
|
raise ValueError(f"{name} must contain integer label IDs.")
|
|
45
45
|
if np.any(array < 0):
|
|
46
46
|
raise ValueError(f"{name} must not contain negative label IDs.")
|
|
47
|
+
# Validate before casting: uint32 conversion would wrap oversized IDs and
|
|
48
|
+
# could silently merge distinct objects or turn an object into background.
|
|
47
49
|
maximum = int(array.max(initial=0))
|
|
48
50
|
if maximum > np.iinfo(np.uint32).max:
|
|
49
51
|
raise ValueError(f"{name} contains a label ID that does not fit in uint32.")
|
|
@@ -64,9 +66,12 @@ def relabel_sequential(labels: Any, *, min_size: int = 0) -> tuple[Any, int]:
|
|
|
64
66
|
|
|
65
67
|
source = validate_labels(labels)
|
|
66
68
|
values, inverse, counts = np.unique(source, return_inverse=True, return_counts=True)
|
|
69
|
+
# Count pixels across each entire label, including disconnected components
|
|
70
|
+
# with the same ID; this filters objects without splitting them.
|
|
67
71
|
retained = (values > 0) & (counts >= min_size)
|
|
68
72
|
mapped_values = np.zeros(values.shape, dtype=np.uint32)
|
|
69
73
|
mapped_values[retained] = np.arange(1, int(retained.sum()) + 1, dtype=np.uint32)
|
|
74
|
+
# Map compact unique-value indices rather than allocating up to max(label).
|
|
70
75
|
output = mapped_values[inverse].reshape(source.shape)
|
|
71
76
|
return output, int(retained.sum())
|
|
72
77
|
|
|
@@ -78,6 +83,7 @@ def write_labels(path: Path, labels: Any) -> None:
|
|
|
78
83
|
|
|
79
84
|
array = validate_labels(labels).astype(np.uint32, copy=False)
|
|
80
85
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
86
|
+
# A stack with three or four planes must remain scalar labels, not RGB(A).
|
|
81
87
|
kwargs = {"photometric": "minisblack"} if array.ndim >= 3 else {}
|
|
82
88
|
iio.imwrite(str(path), array, **kwargs)
|
|
83
89
|
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Explicit spatial/channel layout validation for both Cellpose runtimes."""
|
|
2
|
+
|
|
3
|
+
from typing import Annotated, Any, Literal
|
|
4
|
+
|
|
5
|
+
from bioimageflow_core import Arguments, GUIMeta, IOModel
|
|
6
|
+
|
|
7
|
+
from ._arrays import finite_float, integer_parameter, validate_labels
|
|
8
|
+
from ._tiff import TiffMetadata, physical_spacing
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def cellpose_layout(
|
|
12
|
+
image: Any, *, do_3D: bool, channel_axis: str
|
|
13
|
+
) -> tuple[int | None, int | None, tuple[int, ...]]:
|
|
14
|
+
"""Resolve YX/CYX/YXC or ZYX/CZYX/ZYXC without guessing short axes."""
|
|
15
|
+
if not isinstance(do_3D, bool):
|
|
16
|
+
raise ValueError("do_3D must be a boolean.")
|
|
17
|
+
if channel_axis not in {"first", "last"}:
|
|
18
|
+
raise ValueError("channel_axis must be 'first' or 'last'.")
|
|
19
|
+
spatial_ndim = 3 if do_3D else 2
|
|
20
|
+
if image.ndim not in {spatial_ndim, spatial_ndim + 1}:
|
|
21
|
+
layouts = "ZYX, CZYX, or ZYXC" if do_3D else "YX, CYX, or YXC"
|
|
22
|
+
raise ValueError(f"do_3D={do_3D} requires {layouts} input; got {image.shape}.")
|
|
23
|
+
axis = None
|
|
24
|
+
if image.ndim == spatial_ndim + 1:
|
|
25
|
+
axis = 0 if channel_axis == "first" else image.ndim - 1
|
|
26
|
+
if not 1 <= image.shape[axis] <= 4:
|
|
27
|
+
raise ValueError(
|
|
28
|
+
"Cellpose input must have one to four channels on the declared "
|
|
29
|
+
f"channel axis; got shape {image.shape}."
|
|
30
|
+
)
|
|
31
|
+
# A short Z dimension is still spatial: only the explicit channel layout
|
|
32
|
+
# removes a dimension from the expected output mask shape.
|
|
33
|
+
spatial_shape = tuple(size for i, size in enumerate(image.shape) if i != axis)
|
|
34
|
+
if any(size < 1 for size in spatial_shape):
|
|
35
|
+
raise ValueError("Cellpose spatial axes must not be empty.")
|
|
36
|
+
# Z follows C for CZYX inputs and is first for both ZYX and ZYXC inputs.
|
|
37
|
+
z_axis = (1 if axis == 0 else 0) if do_3D else None
|
|
38
|
+
return axis, z_axis, spatial_shape
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cellpose_anisotropy(value: Any) -> float:
|
|
42
|
+
"""Validate the ratio of Z voxel spacing to XY pixel spacing."""
|
|
43
|
+
anisotropy = finite_float(value, name="anisotropy")
|
|
44
|
+
if anisotropy <= 0:
|
|
45
|
+
raise ValueError("anisotropy must be greater than zero.")
|
|
46
|
+
return anisotropy
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CellposeSamplingInputs(IOModel):
|
|
50
|
+
"""Shared preprocessing and inference settings for the pinned runtimes."""
|
|
51
|
+
|
|
52
|
+
xy_downsample: Annotated[
|
|
53
|
+
int,
|
|
54
|
+
GUIMeta(
|
|
55
|
+
display_name="XY mean-pooling factor",
|
|
56
|
+
description="Reduce X and Y by an integer factor before inference. Both sizes must divide evenly.",
|
|
57
|
+
min=1,
|
|
58
|
+
step=1,
|
|
59
|
+
group="advanced",
|
|
60
|
+
),
|
|
61
|
+
] = 1
|
|
62
|
+
anisotropy_from_metadata: Annotated[
|
|
63
|
+
bool,
|
|
64
|
+
GUIMeta(
|
|
65
|
+
display_name="Use physical spacing for anisotropy",
|
|
66
|
+
description="Derive Z/XY spacing from calibrated OME-TIFF in 3D. Requires equal X and Y spacing.",
|
|
67
|
+
group="advanced",
|
|
68
|
+
),
|
|
69
|
+
] = False
|
|
70
|
+
normalization: Annotated[
|
|
71
|
+
Literal["runtime", "disabled", "global_percentiles"],
|
|
72
|
+
GUIMeta(
|
|
73
|
+
display_name="Normalization",
|
|
74
|
+
description="Use Cellpose normalization, disable it, or normalize each channel across its entire spatial grid after pooling.",
|
|
75
|
+
group="advanced",
|
|
76
|
+
),
|
|
77
|
+
] = "runtime"
|
|
78
|
+
percentile_low: Annotated[
|
|
79
|
+
float,
|
|
80
|
+
GUIMeta(
|
|
81
|
+
display_name="Lower normalization percentile",
|
|
82
|
+
min=0,
|
|
83
|
+
max=100,
|
|
84
|
+
step=0.1,
|
|
85
|
+
group="advanced",
|
|
86
|
+
),
|
|
87
|
+
] = 1.0
|
|
88
|
+
percentile_high: Annotated[
|
|
89
|
+
float,
|
|
90
|
+
GUIMeta(
|
|
91
|
+
display_name="Upper normalization percentile",
|
|
92
|
+
min=0,
|
|
93
|
+
max=100,
|
|
94
|
+
step=0.1,
|
|
95
|
+
group="advanced",
|
|
96
|
+
),
|
|
97
|
+
] = 99.9
|
|
98
|
+
clip_normalized: Annotated[
|
|
99
|
+
bool,
|
|
100
|
+
GUIMeta(
|
|
101
|
+
display_name="Clip percentile-normalized intensities",
|
|
102
|
+
description="Clamp global percentile-normalized values to 0–1.",
|
|
103
|
+
group="advanced",
|
|
104
|
+
),
|
|
105
|
+
] = True
|
|
106
|
+
min_size: Annotated[
|
|
107
|
+
int,
|
|
108
|
+
GUIMeta(
|
|
109
|
+
display_name="Minimum inference object size",
|
|
110
|
+
description="Minimum object size in pixels (2D) or voxels (3D) on the pooled input grid.",
|
|
111
|
+
min=-1,
|
|
112
|
+
step=1,
|
|
113
|
+
group="advanced",
|
|
114
|
+
),
|
|
115
|
+
] = 15
|
|
116
|
+
flow3D_smooth: Annotated[
|
|
117
|
+
float,
|
|
118
|
+
GUIMeta(
|
|
119
|
+
display_name="3D flow smoothing",
|
|
120
|
+
description="Gaussian sigma in the runtime's flow-grid coordinates. Used only in 3D.",
|
|
121
|
+
min=0,
|
|
122
|
+
step=0.1,
|
|
123
|
+
group="advanced",
|
|
124
|
+
),
|
|
125
|
+
] = 0.0
|
|
126
|
+
resample: Annotated[
|
|
127
|
+
bool,
|
|
128
|
+
GUIMeta(
|
|
129
|
+
display_name="Cellpose runtime resampling",
|
|
130
|
+
description="Run mask dynamics at the runtime's input resolution. Output labels always return to the native grid.",
|
|
131
|
+
group="advanced",
|
|
132
|
+
),
|
|
133
|
+
] = True
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def prepare_cellpose(
|
|
137
|
+
image: Any,
|
|
138
|
+
arguments: Arguments,
|
|
139
|
+
*,
|
|
140
|
+
axes: str,
|
|
141
|
+
metadata: TiffMetadata | None,
|
|
142
|
+
channel_axis: int | None,
|
|
143
|
+
do_3D: bool,
|
|
144
|
+
) -> tuple[Any, int, dict[str, Any]]:
|
|
145
|
+
"""Prepare the inference grid and settings without changing model identity."""
|
|
146
|
+
import numpy as np
|
|
147
|
+
|
|
148
|
+
factor = integer_parameter(
|
|
149
|
+
getattr(arguments, "xy_downsample", 1),
|
|
150
|
+
name="xy_downsample",
|
|
151
|
+
minimum=1,
|
|
152
|
+
)
|
|
153
|
+
anisotropy = cellpose_anisotropy(getattr(arguments, "anisotropy", 1.0))
|
|
154
|
+
if do_3D and getattr(arguments, "anisotropy_from_metadata", False):
|
|
155
|
+
z, y, x = physical_spacing(metadata, "ZYX")
|
|
156
|
+
if not np.isclose(x, y):
|
|
157
|
+
raise ValueError(
|
|
158
|
+
"Metadata-derived anisotropy requires equal X and Y spacing."
|
|
159
|
+
)
|
|
160
|
+
anisotropy = z / x
|
|
161
|
+
if metadata is not None and metadata.axes.replace("S", "C") != axes:
|
|
162
|
+
# OME axes are authoritative. Ordinary TIFFs may have unknown axes.
|
|
163
|
+
if metadata.calibration or all(axis in "TCZYXS" for axis in metadata.axes):
|
|
164
|
+
raise ValueError(
|
|
165
|
+
f"Expected image axes {axes}; TIFF declares {metadata.axes}."
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
diameter = finite_float(arguments.diameter, name="diameter")
|
|
169
|
+
if diameter < 0:
|
|
170
|
+
raise ValueError("diameter must be greater than or equal to zero.")
|
|
171
|
+
normalization = getattr(arguments, "normalization", "runtime")
|
|
172
|
+
if normalization not in {"runtime", "disabled", "global_percentiles"}:
|
|
173
|
+
raise ValueError("Unknown Cellpose normalization mode.")
|
|
174
|
+
low = finite_float(getattr(arguments, "percentile_low", 1.0), name="percentile_low")
|
|
175
|
+
high = finite_float(
|
|
176
|
+
getattr(arguments, "percentile_high", 99.9), name="percentile_high"
|
|
177
|
+
)
|
|
178
|
+
if not 0 <= low < high <= 100:
|
|
179
|
+
raise ValueError("Require 0 <= percentile_low < percentile_high <= 100.")
|
|
180
|
+
smooth = finite_float(
|
|
181
|
+
getattr(arguments, "flow3D_smooth", 0.0), name="flow3D_smooth"
|
|
182
|
+
)
|
|
183
|
+
if smooth < 0:
|
|
184
|
+
raise ValueError("flow3D_smooth must be non-negative.")
|
|
185
|
+
min_size = integer_parameter(
|
|
186
|
+
getattr(arguments, "min_size", 15), name="min_size", minimum=-1
|
|
187
|
+
)
|
|
188
|
+
resample = getattr(arguments, "resample", True)
|
|
189
|
+
clip = getattr(arguments, "clip_normalized", True)
|
|
190
|
+
if not isinstance(clip, bool) or not isinstance(resample, bool):
|
|
191
|
+
raise ValueError("clip_normalized and resample must be booleans.")
|
|
192
|
+
|
|
193
|
+
if factor != 1 or normalization == "global_percentiles":
|
|
194
|
+
# Moving C outside the spatial axes makes each channel independent.
|
|
195
|
+
channels = (
|
|
196
|
+
image[None] if channel_axis is None else np.moveaxis(image, channel_axis, 0)
|
|
197
|
+
)
|
|
198
|
+
*leading, ny, nx = channels.shape
|
|
199
|
+
if ny % factor or nx % factor:
|
|
200
|
+
raise ValueError("X and Y sizes must divide evenly by xy_downsample.")
|
|
201
|
+
if factor != 1:
|
|
202
|
+
channels = channels.reshape(
|
|
203
|
+
*leading, ny // factor, factor, nx // factor, factor
|
|
204
|
+
)
|
|
205
|
+
channels = channels.mean(axis=(-3, -1)).astype(np.float32)
|
|
206
|
+
if normalization == "global_percentiles":
|
|
207
|
+
channels = channels.astype(np.float32, copy=True)
|
|
208
|
+
for data in channels:
|
|
209
|
+
lower, upper = np.percentile(data, [low, high])
|
|
210
|
+
scaled = (data - lower) / max(upper - lower, 1.0)
|
|
211
|
+
if clip:
|
|
212
|
+
np.clip(scaled, 0, 1, out=scaled)
|
|
213
|
+
data[...] = scaled
|
|
214
|
+
image = (
|
|
215
|
+
channels[0]
|
|
216
|
+
if channel_axis is None
|
|
217
|
+
else np.moveaxis(channels, 0, channel_axis)
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
return (
|
|
221
|
+
image,
|
|
222
|
+
factor,
|
|
223
|
+
{
|
|
224
|
+
"diameter": diameter / factor if diameter else None,
|
|
225
|
+
"anisotropy": anisotropy / factor if do_3D else anisotropy,
|
|
226
|
+
"normalize": normalization == "runtime",
|
|
227
|
+
"min_size": min_size,
|
|
228
|
+
"flow3D_smooth": smooth,
|
|
229
|
+
"resample": resample,
|
|
230
|
+
},
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def restore_cellpose_labels(
|
|
235
|
+
mask: Any,
|
|
236
|
+
*,
|
|
237
|
+
spatial_shape: tuple[int, ...],
|
|
238
|
+
factor: int,
|
|
239
|
+
name: str,
|
|
240
|
+
) -> Any:
|
|
241
|
+
import numpy as np
|
|
242
|
+
|
|
243
|
+
*leading, ny, nx = spatial_shape
|
|
244
|
+
labels = validate_labels(
|
|
245
|
+
mask,
|
|
246
|
+
name=name,
|
|
247
|
+
dimensions=(len(spatial_shape),),
|
|
248
|
+
expected_shape=(*leading, ny // factor, nx // factor),
|
|
249
|
+
)
|
|
250
|
+
if factor != 1:
|
|
251
|
+
labels = np.repeat(np.repeat(labels, factor, axis=-2), factor, axis=-1)
|
|
252
|
+
return labels
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""OME-TIFF spatial calibration and scalar image I/O for segmentation workers."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from math import isfinite
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
from xml.etree import ElementTree
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class TiffMetadata:
|
|
12
|
+
axes: str
|
|
13
|
+
calibration: dict[str, tuple[float, str]]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_MICROMETRES = {
|
|
17
|
+
"µm": 1.0,
|
|
18
|
+
"μm": 1.0,
|
|
19
|
+
"um": 1.0,
|
|
20
|
+
"micrometre": 1.0,
|
|
21
|
+
"micrometer": 1.0,
|
|
22
|
+
"nm": 0.001,
|
|
23
|
+
"mm": 1000.0,
|
|
24
|
+
"m": 1_000_000.0,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def read_image(path: Path | str) -> tuple[Any, TiffMetadata | None]:
|
|
29
|
+
path = Path(path)
|
|
30
|
+
if path.suffix.lower() not in {".tif", ".tiff"}:
|
|
31
|
+
import imageio.v3 as iio
|
|
32
|
+
|
|
33
|
+
return iio.imread(path), None
|
|
34
|
+
import tifffile
|
|
35
|
+
|
|
36
|
+
with tifffile.TiffFile(path) as tif:
|
|
37
|
+
series = tif.series[0]
|
|
38
|
+
calibration = {}
|
|
39
|
+
if tif.ome_metadata:
|
|
40
|
+
pixels = ElementTree.fromstring(tif.ome_metadata).find(".//{*}Pixels")
|
|
41
|
+
if pixels is not None:
|
|
42
|
+
for axis in "XYZ":
|
|
43
|
+
key = f"PhysicalSize{axis}"
|
|
44
|
+
if key in pixels.attrib:
|
|
45
|
+
size = float(pixels.attrib[key])
|
|
46
|
+
if not isfinite(size) or size <= 0:
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"Physical {axis} size must be finite and positive."
|
|
49
|
+
)
|
|
50
|
+
calibration[axis] = (
|
|
51
|
+
size,
|
|
52
|
+
pixels.attrib.get(f"{key}Unit", "µm"),
|
|
53
|
+
)
|
|
54
|
+
return series.asarray(), TiffMetadata(series.axes, calibration)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def physical_spacing(metadata: TiffMetadata | None, axes: str) -> tuple[float, ...]:
|
|
58
|
+
"""Return finite positive voxel sizes in micrometres, in the requested order."""
|
|
59
|
+
if metadata is None or not all(axis in metadata.calibration for axis in axes):
|
|
60
|
+
raise ValueError(f"Calibrated OME-TIFF with physical {axes} sizes is required.")
|
|
61
|
+
spacing = []
|
|
62
|
+
for axis in axes:
|
|
63
|
+
size, unit = metadata.calibration[axis]
|
|
64
|
+
if unit not in _MICROMETRES:
|
|
65
|
+
raise ValueError(f"Unsupported physical {axis} size unit {unit!r}.")
|
|
66
|
+
spacing.append(size * _MICROMETRES[unit])
|
|
67
|
+
return tuple(spacing)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def write_scalar_tiff(
|
|
71
|
+
path: Path | str,
|
|
72
|
+
data: Any,
|
|
73
|
+
axes: str,
|
|
74
|
+
*,
|
|
75
|
+
calibration: dict[str, tuple[float, str]],
|
|
76
|
+
) -> Path:
|
|
77
|
+
import tifffile
|
|
78
|
+
|
|
79
|
+
path = Path(path)
|
|
80
|
+
if path.suffix.lower() not in {".tif", ".tiff"}:
|
|
81
|
+
raise ValueError(
|
|
82
|
+
"Scalar segmentation images must use a .tif or .tiff destination."
|
|
83
|
+
)
|
|
84
|
+
metadata: dict[str, Any] = {"axes": axes}
|
|
85
|
+
for axis, (size, unit) in calibration.items():
|
|
86
|
+
if axis in axes:
|
|
87
|
+
metadata[f"PhysicalSize{axis}"] = size
|
|
88
|
+
metadata[f"PhysicalSize{axis}Unit"] = unit
|
|
89
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
90
|
+
ome = bool(calibration) or path.name.lower().endswith((".ome.tif", ".ome.tiff"))
|
|
91
|
+
tifffile.imwrite(
|
|
92
|
+
path,
|
|
93
|
+
data,
|
|
94
|
+
ome=ome,
|
|
95
|
+
metadata=metadata,
|
|
96
|
+
photometric="minisblack",
|
|
97
|
+
compression="deflate",
|
|
98
|
+
)
|
|
99
|
+
return path
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def read_volume(path: Path | str) -> tuple[Any, tuple[float, ...]]:
|
|
103
|
+
image, metadata = read_image(path)
|
|
104
|
+
if metadata is None or metadata.axes != "ZYX":
|
|
105
|
+
raise ValueError(f"{path} must be an explicitly declared ZYX OME-TIFF volume.")
|
|
106
|
+
return image, physical_spacing(metadata, "ZYX")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def registered_volume(
|
|
110
|
+
path: Path | str,
|
|
111
|
+
shape: tuple[int, ...],
|
|
112
|
+
spacing: tuple[float, ...],
|
|
113
|
+
) -> Any:
|
|
114
|
+
import numpy as np
|
|
115
|
+
|
|
116
|
+
image, actual = read_volume(path)
|
|
117
|
+
if image.shape != shape or not np.allclose(actual, spacing, rtol=1e-5, atol=0):
|
|
118
|
+
raise ValueError(f"{path} must have the same registered ZYX shape and spacing.")
|
|
119
|
+
return image
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def write_volume(path: Path | str, data: Any, spacing: tuple[float, ...]) -> Path:
|
|
123
|
+
return write_scalar_tiff(
|
|
124
|
+
path,
|
|
125
|
+
data,
|
|
126
|
+
"ZYX",
|
|
127
|
+
calibration={
|
|
128
|
+
axis: (size, "µm") for axis, size in zip("ZYX", spacing, strict=True)
|
|
129
|
+
},
|
|
130
|
+
)
|