bioimageflow-segmentation-tools 0.1.6__tar.gz → 0.2.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.1.6 → bioimageflow_segmentation_tools-0.2.0}/.gitignore +0 -2
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/PKG-INFO +10 -3
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/README.md +6 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/bioimageflow_segmentation_tools/__init__.py +0 -3
- bioimageflow_segmentation_tools-0.2.0/bioimageflow_segmentation_tools/_arrays.py +104 -0
- bioimageflow_segmentation_tools-0.2.0/bioimageflow_segmentation_tools/cellpose_sam.py +168 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/bioimageflow_segmentation_tools/cellpose_v3.py +91 -13
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/bioimageflow_segmentation_tools/classical.py +173 -174
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/bioimageflow_segmentation_tools/stardist_segmenter.py +98 -30
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/index.md +1 -1
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/cellpose3.md +2 -3
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/cellpose_sam.md +5 -3
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/distance_watershed_segment.md +1 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/filter_labels.md +2 -2
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/local_threshold_segment.md +3 -2
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/otsu_threshold_segment.md +1 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/postprocess_labels.md +1 -2
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/stardist_segmenter.md +2 -1
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/threshold_segment.md +4 -5
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/watershed_segment.md +5 -6
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/pyproject.toml +3 -2
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/tests/test_execution.py +248 -51
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/tests/test_schema.py +19 -3
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/cellpose_sam.py +0 -115
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/nninteractive.py +0 -105
- bioimageflow_segmentation_tools-0.1.6/docs/tools/nninteractive.md +0 -7
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/LICENSE +0 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/images/README.md +0 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/tools/split_touching_objects.md +0 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/docs/workflows/bbbc038_segmentation_benchmark.md +0 -0
- {bioimageflow_segmentation_tools-0.1.6 → bioimageflow_segmentation_tools-0.2.0}/tests/conftest.py +0 -0
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
.claude/
|
|
6
6
|
.venv/
|
|
7
7
|
TODO.md
|
|
8
|
-
bif_data/
|
|
9
8
|
data/
|
|
10
9
|
!example_workflows/fish_analysis/data/
|
|
11
10
|
example_workflows/bbbc038_segmentation_benchmark/data/
|
|
@@ -15,7 +14,6 @@ packages/bioimageflow-common-tools/bioimageflow_common_tools/data/*
|
|
|
15
14
|
!packages/bioimageflow-common-tools/bioimageflow_common_tools/data/blobs.txt
|
|
16
15
|
packages/bioimageflow-common-tools/bioimageflow_common_tools/.vscode/
|
|
17
16
|
__pycache__/
|
|
18
|
-
docs/build/
|
|
19
17
|
docs/_build/
|
|
20
18
|
wetlands/
|
|
21
19
|
wetlands-lib/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: bioimageflow-segmentation-tools
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.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,10 +21,11 @@ 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.4,>=0.3.0
|
|
25
25
|
Requires-Dist: imageio>=2.31.0
|
|
26
26
|
Requires-Dist: numpy>=1.23.5
|
|
27
27
|
Requires-Dist: scikit-image>=0.21.0
|
|
28
|
+
Requires-Dist: scipy>=1.10.0
|
|
28
29
|
Description-Content-Type: text/markdown
|
|
29
30
|
|
|
30
31
|
# bioimageflow-segmentation-tools
|
|
@@ -34,6 +35,7 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
34
35
|
## Tools
|
|
35
36
|
|
|
36
37
|
- `Cellpose3`: Cellpose v3 pretrained model wrapper.
|
|
38
|
+
- `CellposeSAM`: Cellpose-SAM pretrained model wrapper.
|
|
37
39
|
- `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
|
|
38
40
|
- `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
|
|
39
41
|
- `OtsuThresholdSegment`: compute a global Otsu threshold and label foreground objects.
|
|
@@ -44,11 +46,16 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
44
46
|
- `FilterLabels`: remove labels by area, border contact, intensity, and shape constraints.
|
|
45
47
|
- `PostprocessLabels`: remove small labels and relabel label images sequentially.
|
|
46
48
|
|
|
49
|
+
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.
|
|
50
|
+
Default label-output paths use TIFF rather than inheriting an input extension that may be lossy or unable to store UInt32 label IDs.
|
|
51
|
+
|
|
47
52
|
Heavy model dependencies are declared in isolated `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require Cellpose, TensorFlow, StarDist, or other model packages to be installed in the main process.
|
|
48
53
|
`Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
|
|
49
54
|
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.
|
|
50
55
|
Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
|
|
51
56
|
|
|
57
|
+
The former `nnInteractive` wrapper was removed because nnInteractive requires a stateful volumetric inference session; its public point-list-to-2D-mask contract did not represent the upstream API.
|
|
58
|
+
|
|
52
59
|
## Example
|
|
53
60
|
|
|
54
61
|
```python
|
|
@@ -5,6 +5,7 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
5
5
|
## Tools
|
|
6
6
|
|
|
7
7
|
- `Cellpose3`: Cellpose v3 pretrained model wrapper.
|
|
8
|
+
- `CellposeSAM`: Cellpose-SAM pretrained model wrapper.
|
|
8
9
|
- `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
|
|
9
10
|
- `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
|
|
10
11
|
- `OtsuThresholdSegment`: compute a global Otsu threshold and label foreground objects.
|
|
@@ -15,11 +16,16 @@ Segmentation-focused tool package for BioImageFlow.
|
|
|
15
16
|
- `FilterLabels`: remove labels by area, border contact, intensity, and shape constraints.
|
|
16
17
|
- `PostprocessLabels`: remove small labels and relabel label images sequentially.
|
|
17
18
|
|
|
19
|
+
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.
|
|
20
|
+
Default label-output paths use TIFF rather than inheriting an input extension that may be lossy or unable to store UInt32 label IDs.
|
|
21
|
+
|
|
18
22
|
Heavy model dependencies are declared in isolated `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require Cellpose, TensorFlow, StarDist, or other model packages to be installed in the main process.
|
|
19
23
|
`Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
|
|
20
24
|
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.
|
|
21
25
|
Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
|
|
22
26
|
|
|
27
|
+
The former `nnInteractive` wrapper was removed because nnInteractive requires a stateful volumetric inference session; its public point-list-to-2D-mask contract did not represent the upstream API.
|
|
28
|
+
|
|
23
29
|
## Example
|
|
24
30
|
|
|
25
31
|
```python
|
|
@@ -14,7 +14,6 @@ if TYPE_CHECKING:
|
|
|
14
14
|
from .classical import SplitTouchingObjects as SplitTouchingObjects
|
|
15
15
|
from .classical import ThresholdSegment as ThresholdSegment
|
|
16
16
|
from .classical import WatershedSegment as WatershedSegment
|
|
17
|
-
from .nninteractive import nnInteractive as nnInteractive
|
|
18
17
|
from .stardist_segmenter import StarDistSegmenter as StarDistSegmenter
|
|
19
18
|
|
|
20
19
|
|
|
@@ -25,7 +24,6 @@ _EXPORTS = {
|
|
|
25
24
|
"FilterLabels": ("classical", "FilterLabels"),
|
|
26
25
|
"LocalThresholdSegment": ("classical", "LocalThresholdSegment"),
|
|
27
26
|
"OtsuThresholdSegment": ("classical", "OtsuThresholdSegment"),
|
|
28
|
-
"nnInteractive": ("nninteractive", "nnInteractive"),
|
|
29
27
|
"PostprocessLabels": ("classical", "PostprocessLabels"),
|
|
30
28
|
"SplitTouchingObjects": ("classical", "SplitTouchingObjects"),
|
|
31
29
|
"StarDistSegmenter": ("stardist_segmenter", "StarDistSegmenter"),
|
|
@@ -45,7 +43,6 @@ __all__ = [
|
|
|
45
43
|
"StarDistSegmenter",
|
|
46
44
|
"ThresholdSegment",
|
|
47
45
|
"WatershedSegment",
|
|
48
|
-
"nnInteractive",
|
|
49
46
|
]
|
|
50
47
|
|
|
51
48
|
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Array validation and label-image helpers shared by segmentation tools."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def validate_image(image: Any, *, name: str, dimensions: tuple[int, ...]) -> Any:
|
|
8
|
+
"""Return *image* as an array after validating its dimensions and values."""
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
array = np.asarray(image)
|
|
12
|
+
if array.ndim not in dimensions:
|
|
13
|
+
expected = " or ".join(f"{dimension}D" for dimension in dimensions)
|
|
14
|
+
raise ValueError(f"{name} must be {expected}; got shape {array.shape}.")
|
|
15
|
+
if not np.issubdtype(array.dtype, np.number) and array.dtype != np.bool_:
|
|
16
|
+
raise ValueError(f"{name} must contain numeric values.")
|
|
17
|
+
if np.issubdtype(array.dtype, np.inexact) and not np.isfinite(array).all():
|
|
18
|
+
raise ValueError(f"{name} must contain only finite values.")
|
|
19
|
+
return array
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def validate_labels(
|
|
23
|
+
labels: Any,
|
|
24
|
+
*,
|
|
25
|
+
name: str = "labels",
|
|
26
|
+
dimensions: tuple[int, ...] = (2, 3),
|
|
27
|
+
expected_shape: tuple[int, ...] | None = None,
|
|
28
|
+
) -> Any:
|
|
29
|
+
"""Return a non-negative integral label array after strict validation."""
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
array = validate_image(labels, name=name, dimensions=dimensions)
|
|
33
|
+
if expected_shape is not None and array.shape != expected_shape:
|
|
34
|
+
raise ValueError(
|
|
35
|
+
f"{name} must have shape {expected_shape}; got {array.shape}."
|
|
36
|
+
)
|
|
37
|
+
if not (
|
|
38
|
+
np.issubdtype(array.dtype, np.integer)
|
|
39
|
+
or np.issubdtype(array.dtype, np.floating)
|
|
40
|
+
or array.dtype == np.bool_
|
|
41
|
+
):
|
|
42
|
+
raise ValueError(f"{name} must contain integer label IDs.")
|
|
43
|
+
if np.issubdtype(array.dtype, np.floating) and not np.equal(array, np.floor(array)).all():
|
|
44
|
+
raise ValueError(f"{name} must contain integer label IDs.")
|
|
45
|
+
if np.any(array < 0):
|
|
46
|
+
raise ValueError(f"{name} must not contain negative label IDs.")
|
|
47
|
+
maximum = int(array.max(initial=0))
|
|
48
|
+
if maximum > np.iinfo(np.uint32).max:
|
|
49
|
+
raise ValueError(f"{name} contains a label ID that does not fit in uint32.")
|
|
50
|
+
return array.astype(np.uint32, copy=False)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def object_count(labels: Any) -> int:
|
|
54
|
+
"""Count distinct positive labels without assuming sequential IDs."""
|
|
55
|
+
import numpy as np
|
|
56
|
+
|
|
57
|
+
values = np.unique(np.asarray(labels))
|
|
58
|
+
return int(np.count_nonzero(values > 0))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def relabel_sequential(labels: Any, *, min_size: int = 0) -> tuple[Any, int]:
|
|
62
|
+
"""Filter small labels and map retained positive IDs to ``1..N``."""
|
|
63
|
+
import numpy as np
|
|
64
|
+
|
|
65
|
+
source = validate_labels(labels)
|
|
66
|
+
values, inverse, counts = np.unique(source, return_inverse=True, return_counts=True)
|
|
67
|
+
retained = (values > 0) & (counts >= min_size)
|
|
68
|
+
mapped_values = np.zeros(values.shape, dtype=np.uint32)
|
|
69
|
+
mapped_values[retained] = np.arange(1, int(retained.sum()) + 1, dtype=np.uint32)
|
|
70
|
+
output = mapped_values[inverse].reshape(source.shape)
|
|
71
|
+
return output, int(retained.sum())
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def write_labels(path: Path, labels: Any) -> None:
|
|
75
|
+
"""Write a validated label image with an unambiguous TIFF photometric mode."""
|
|
76
|
+
import imageio.v3 as iio
|
|
77
|
+
import numpy as np
|
|
78
|
+
|
|
79
|
+
array = validate_labels(labels).astype(np.uint32, copy=False)
|
|
80
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
kwargs = {"photometric": "minisblack"} if array.ndim >= 3 else {}
|
|
82
|
+
iio.imwrite(str(path), array, **kwargs)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def finite_float(value: Any, *, name: str) -> float:
|
|
86
|
+
"""Validate and return a finite floating-point parameter."""
|
|
87
|
+
import math
|
|
88
|
+
|
|
89
|
+
result = float(value)
|
|
90
|
+
if not math.isfinite(result):
|
|
91
|
+
raise ValueError(f"{name} must be finite.")
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def integer_parameter(value: Any, *, name: str, minimum: int = 0) -> int:
|
|
96
|
+
"""Validate an integer parameter without silently truncating floats."""
|
|
97
|
+
import numbers
|
|
98
|
+
|
|
99
|
+
if isinstance(value, bool) or not isinstance(value, numbers.Integral):
|
|
100
|
+
raise ValueError(f"{name} must be an integer greater than or equal to {minimum}.")
|
|
101
|
+
result = int(value)
|
|
102
|
+
if result < minimum:
|
|
103
|
+
raise ValueError(f"{name} must be greater than or equal to {minimum}.")
|
|
104
|
+
return result
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Cellpose-SAM segmentation wrapper."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated, Any, Literal
|
|
5
|
+
|
|
6
|
+
from bioimageflow_core import (
|
|
7
|
+
Arguments,
|
|
8
|
+
Category,
|
|
9
|
+
Connectable,
|
|
10
|
+
EnvironmentSpec,
|
|
11
|
+
GUIMeta,
|
|
12
|
+
ImageSpec,
|
|
13
|
+
IOModel,
|
|
14
|
+
Layout,
|
|
15
|
+
ProcessingTool,
|
|
16
|
+
RowConsumption,
|
|
17
|
+
Semantic,
|
|
18
|
+
Template,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
from ._arrays import finite_float, object_count, validate_image, validate_labels, write_labels
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
cellpose_sam_env = EnvironmentSpec(
|
|
25
|
+
name="segmentation-cellpose-sam",
|
|
26
|
+
dependencies={
|
|
27
|
+
"python": "3.12",
|
|
28
|
+
"pip": [
|
|
29
|
+
"cellpose==4.2.1.1",
|
|
30
|
+
"imageio==2.37.3",
|
|
31
|
+
"numpy==2.5.0",
|
|
32
|
+
"packaging==26.2",
|
|
33
|
+
"tifffile==2026.6.1",
|
|
34
|
+
],
|
|
35
|
+
}
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class CellposeSAM(ProcessingTool):
|
|
40
|
+
"""Segment cells or nuclei with Cellpose-SAM models."""
|
|
41
|
+
|
|
42
|
+
row_consumption = RowConsumption.MAPPED
|
|
43
|
+
display_name = "Cellpose-SAM"
|
|
44
|
+
documentation = "Segment cells or nuclei using Cellpose-SAM and write a label mask."
|
|
45
|
+
category = Category.SEGMENTATION
|
|
46
|
+
tags = ["segmentation", "cellpose", "sam", "deep learning"]
|
|
47
|
+
environment = cellpose_sam_env
|
|
48
|
+
|
|
49
|
+
def __init__(self) -> None:
|
|
50
|
+
super().__init__()
|
|
51
|
+
self._model_cache_key: str | None = None
|
|
52
|
+
self._cached_model: Any | None = None
|
|
53
|
+
|
|
54
|
+
def clear_model_cache(self) -> None:
|
|
55
|
+
"""Release the cached Cellpose-SAM model held by this tool instance."""
|
|
56
|
+
self._cached_model = None
|
|
57
|
+
self._model_cache_key = None
|
|
58
|
+
|
|
59
|
+
def _get_model(self, pretrained_model: str) -> Any:
|
|
60
|
+
"""Return the selected model, replacing a different cached model."""
|
|
61
|
+
if self._cached_model is None or self._model_cache_key != pretrained_model:
|
|
62
|
+
from cellpose import models # type: ignore
|
|
63
|
+
|
|
64
|
+
self.clear_model_cache()
|
|
65
|
+
model = models.CellposeModel(pretrained_model=pretrained_model)
|
|
66
|
+
self._cached_model = model
|
|
67
|
+
self._model_cache_key = pretrained_model
|
|
68
|
+
return self._cached_model
|
|
69
|
+
|
|
70
|
+
class Inputs(IOModel):
|
|
71
|
+
input_image: Annotated[
|
|
72
|
+
Path,
|
|
73
|
+
ImageSpec(
|
|
74
|
+
semantics={Semantic.INTENSITY},
|
|
75
|
+
layouts={Layout.PLANAR, Layout.PLANAR_CHANNEL},
|
|
76
|
+
),
|
|
77
|
+
GUIMeta(
|
|
78
|
+
display_name="Input image",
|
|
79
|
+
description="2D intensity image to segment.",
|
|
80
|
+
connectable=Connectable.BY_DEFAULT,
|
|
81
|
+
),
|
|
82
|
+
]
|
|
83
|
+
pretrained_model: Annotated[
|
|
84
|
+
str,
|
|
85
|
+
GUIMeta(
|
|
86
|
+
display_name="Pretrained model",
|
|
87
|
+
description="Cellpose-SAM built-in model name or checkpoint path.",
|
|
88
|
+
),
|
|
89
|
+
] = "cpsam_v2"
|
|
90
|
+
diameter: Annotated[float, GUIMeta(min=0.0, max=500.0, step=0.5)] = 0.0
|
|
91
|
+
channel_axis: Annotated[
|
|
92
|
+
Literal["first", "last"],
|
|
93
|
+
GUIMeta(
|
|
94
|
+
display_name="Channel axis",
|
|
95
|
+
description="Location of the channel axis in three-dimensional input images.",
|
|
96
|
+
),
|
|
97
|
+
] = "last"
|
|
98
|
+
flow_threshold: Annotated[float, GUIMeta(min=0.0, max=1.0, step=0.05)] = 0.4
|
|
99
|
+
cellprob_threshold: Annotated[float, GUIMeta(min=-6.0, max=6.0, step=0.5)] = 0.0
|
|
100
|
+
|
|
101
|
+
class Outputs(IOModel):
|
|
102
|
+
mask: Annotated[
|
|
103
|
+
Path,
|
|
104
|
+
ImageSpec(semantics={Semantic.LABEL}, layouts={Layout.PLANAR}),
|
|
105
|
+
GUIMeta(display_name="Segmentation mask"),
|
|
106
|
+
] = Template("{input_image.stem}_cellpose_sam_mask.tif")
|
|
107
|
+
cell_count: Annotated[int, GUIMeta(display_name="Object count")]
|
|
108
|
+
|
|
109
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
110
|
+
import imageio.v3 as iio
|
|
111
|
+
import numpy as np
|
|
112
|
+
|
|
113
|
+
image = validate_image(
|
|
114
|
+
iio.imread(str(arguments.input_image)),
|
|
115
|
+
name="input_image",
|
|
116
|
+
dimensions=(2, 3),
|
|
117
|
+
)
|
|
118
|
+
pretrained_model = str(arguments.pretrained_model).strip()
|
|
119
|
+
if not pretrained_model:
|
|
120
|
+
raise ValueError("pretrained_model must not be empty.")
|
|
121
|
+
diameter_value = finite_float(arguments.diameter, name="diameter")
|
|
122
|
+
if diameter_value < 0:
|
|
123
|
+
raise ValueError("diameter must be greater than or equal to zero.")
|
|
124
|
+
diameter = diameter_value if diameter_value > 0 else None
|
|
125
|
+
flow_threshold = finite_float(arguments.flow_threshold, name="flow_threshold")
|
|
126
|
+
cellprob_threshold = finite_float(
|
|
127
|
+
arguments.cellprob_threshold,
|
|
128
|
+
name="cellprob_threshold",
|
|
129
|
+
)
|
|
130
|
+
if not 0.0 <= flow_threshold <= 1.0:
|
|
131
|
+
raise ValueError("flow_threshold must be between 0 and 1.")
|
|
132
|
+
if not -6.0 <= cellprob_threshold <= 6.0:
|
|
133
|
+
raise ValueError("cellprob_threshold must be between -6 and 6.")
|
|
134
|
+
channel_axis_name = str(arguments.channel_axis)
|
|
135
|
+
if channel_axis_name not in {"first", "last"}:
|
|
136
|
+
raise ValueError("channel_axis must be 'first' or 'last'.")
|
|
137
|
+
channel_axis = None
|
|
138
|
+
expected_shape = image.shape
|
|
139
|
+
if image.ndim == 3:
|
|
140
|
+
channel_axis = 0 if channel_axis_name == "first" else 2
|
|
141
|
+
channel_count = image.shape[channel_axis]
|
|
142
|
+
if channel_count < 1 or channel_count > 4:
|
|
143
|
+
raise ValueError(
|
|
144
|
+
"Three-dimensional Cellpose-SAM input must have one to four channels "
|
|
145
|
+
f"on the declared channel axis; got shape {image.shape}."
|
|
146
|
+
)
|
|
147
|
+
expected_shape = tuple(
|
|
148
|
+
size for axis, size in enumerate(image.shape) if axis != channel_axis
|
|
149
|
+
)
|
|
150
|
+
model = self._get_model(pretrained_model)
|
|
151
|
+
result = model.eval(
|
|
152
|
+
image,
|
|
153
|
+
diameter=diameter,
|
|
154
|
+
channel_axis=channel_axis,
|
|
155
|
+
flow_threshold=flow_threshold,
|
|
156
|
+
cellprob_threshold=cellprob_threshold,
|
|
157
|
+
)
|
|
158
|
+
masks = result[0] if isinstance(result, tuple) else result
|
|
159
|
+
masks = validate_labels(
|
|
160
|
+
masks,
|
|
161
|
+
name="Cellpose-SAM mask",
|
|
162
|
+
dimensions=(2,),
|
|
163
|
+
expected_shape=expected_shape,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
mask_path = Path(arguments.mask)
|
|
167
|
+
write_labels(mask_path, np.asarray(masks, dtype=np.uint32))
|
|
168
|
+
return self.Outputs(mask=mask_path, cell_count=object_count(masks))
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Cellpose3 - fast cell/nuclei segmentation using Cellpose v3."""
|
|
2
2
|
|
|
3
3
|
from pathlib import Path
|
|
4
|
-
from typing import Annotated, Any
|
|
4
|
+
from typing import Annotated, Any, Literal
|
|
5
5
|
|
|
6
6
|
from bioimageflow_core import (
|
|
7
7
|
Arguments,
|
|
@@ -13,10 +13,20 @@ from bioimageflow_core import (
|
|
|
13
13
|
IOModel,
|
|
14
14
|
Layout,
|
|
15
15
|
ProcessingTool,
|
|
16
|
+
RowConsumption,
|
|
16
17
|
Semantic,
|
|
17
18
|
Template,
|
|
18
19
|
)
|
|
19
20
|
|
|
21
|
+
from ._arrays import (
|
|
22
|
+
finite_float,
|
|
23
|
+
integer_parameter,
|
|
24
|
+
object_count,
|
|
25
|
+
validate_image,
|
|
26
|
+
validate_labels,
|
|
27
|
+
write_labels,
|
|
28
|
+
)
|
|
29
|
+
|
|
20
30
|
cellpose_v3_env = EnvironmentSpec(
|
|
21
31
|
name="segmentation-cellpose-v3",
|
|
22
32
|
dependencies={
|
|
@@ -24,6 +34,7 @@ cellpose_v3_env = EnvironmentSpec(
|
|
|
24
34
|
"pip": [
|
|
25
35
|
"cellpose==3.1.1.1",
|
|
26
36
|
"imageio==2.37.3",
|
|
37
|
+
"numpy==2.0.2",
|
|
27
38
|
"packaging==26.2",
|
|
28
39
|
"tifffile==2026.3.3",
|
|
29
40
|
],
|
|
@@ -34,6 +45,7 @@ cellpose_v3_env = EnvironmentSpec(
|
|
|
34
45
|
class Cellpose3(ProcessingTool):
|
|
35
46
|
"""Segment cells or nuclei using the faster pre-SAM Cellpose v3 models."""
|
|
36
47
|
|
|
48
|
+
row_consumption = RowConsumption.MAPPED
|
|
37
49
|
display_name = "Cellpose 3"
|
|
38
50
|
documentation = (
|
|
39
51
|
"Segment cells or nuclei using Cellpose v3 pretrained models such as "
|
|
@@ -127,6 +139,14 @@ class Cellpose3(ProcessingTool):
|
|
|
127
139
|
group="channels",
|
|
128
140
|
),
|
|
129
141
|
] = 0
|
|
142
|
+
channel_axis: Annotated[
|
|
143
|
+
Literal["first", "last"],
|
|
144
|
+
GUIMeta(
|
|
145
|
+
display_name="Channel axis",
|
|
146
|
+
description="Location of the channel axis in three-dimensional input images.",
|
|
147
|
+
group="channels",
|
|
148
|
+
),
|
|
149
|
+
] = "last"
|
|
130
150
|
flow_threshold: Annotated[
|
|
131
151
|
float,
|
|
132
152
|
GUIMeta(
|
|
@@ -167,7 +187,7 @@ class Cellpose3(ProcessingTool):
|
|
|
167
187
|
display_name="Segmentation mask",
|
|
168
188
|
description="Label image where each detected object has a unique integer ID.",
|
|
169
189
|
),
|
|
170
|
-
] = Template("{input_image.stem}_cellpose3_mask
|
|
190
|
+
] = Template("{input_image.stem}_cellpose3_mask.tif")
|
|
171
191
|
cell_count: Annotated[
|
|
172
192
|
int,
|
|
173
193
|
GUIMeta(
|
|
@@ -178,26 +198,84 @@ class Cellpose3(ProcessingTool):
|
|
|
178
198
|
|
|
179
199
|
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
180
200
|
import imageio.v3 as iio
|
|
181
|
-
import numpy as np
|
|
182
201
|
|
|
183
|
-
image =
|
|
184
|
-
|
|
202
|
+
image = validate_image(
|
|
203
|
+
iio.imread(str(arguments.input_image)),
|
|
204
|
+
name="input_image",
|
|
205
|
+
dimensions=(2, 3),
|
|
206
|
+
)
|
|
207
|
+
diameter_value = finite_float(arguments.diameter, name="diameter")
|
|
208
|
+
if diameter_value < 0:
|
|
209
|
+
raise ValueError("diameter must be greater than or equal to zero.")
|
|
210
|
+
diameter = diameter_value if diameter_value > 0 else None
|
|
211
|
+
model_type = str(arguments.model_type).strip()
|
|
212
|
+
if not model_type:
|
|
213
|
+
raise ValueError("model_type must not be empty.")
|
|
214
|
+
channel = integer_parameter(arguments.channel, name="channel")
|
|
215
|
+
nuclear_channel = integer_parameter(
|
|
216
|
+
arguments.nuclear_channel,
|
|
217
|
+
name="nuclear_channel",
|
|
218
|
+
)
|
|
219
|
+
if channel > 3 or nuclear_channel > 3:
|
|
220
|
+
raise ValueError("channel and nuclear_channel must be between 0 and 3.")
|
|
221
|
+
if image.ndim == 2 and (channel != 0 or nuclear_channel != 0):
|
|
222
|
+
raise ValueError("2D grayscale input requires channel=0 and nuclear_channel=0.")
|
|
223
|
+
channel_axis_name = str(arguments.channel_axis)
|
|
224
|
+
if channel_axis_name not in {"first", "last"}:
|
|
225
|
+
raise ValueError("channel_axis must be 'first' or 'last'.")
|
|
226
|
+
channel_axis = None
|
|
227
|
+
expected_shape = image.shape
|
|
228
|
+
if image.ndim == 3:
|
|
229
|
+
channel_axis = 0 if channel_axis_name == "first" else 2
|
|
230
|
+
channel_count = image.shape[channel_axis]
|
|
231
|
+
if channel_count < 1 or channel_count > 4:
|
|
232
|
+
raise ValueError(
|
|
233
|
+
"Three-dimensional Cellpose input must have one to four channels "
|
|
234
|
+
f"on the declared channel axis; got shape {image.shape}."
|
|
235
|
+
)
|
|
236
|
+
for selector_name, selector in (
|
|
237
|
+
("channel", channel),
|
|
238
|
+
("nuclear_channel", nuclear_channel),
|
|
239
|
+
):
|
|
240
|
+
if selector > channel_count:
|
|
241
|
+
raise ValueError(
|
|
242
|
+
f"{selector_name}={selector} is out of range for "
|
|
243
|
+
f"{channel_count} channels."
|
|
244
|
+
)
|
|
245
|
+
expected_shape = tuple(
|
|
246
|
+
size for axis, size in enumerate(image.shape) if axis != channel_axis
|
|
247
|
+
)
|
|
248
|
+
flow_threshold = finite_float(arguments.flow_threshold, name="flow_threshold")
|
|
249
|
+
cellprob_threshold = finite_float(
|
|
250
|
+
arguments.cellprob_threshold,
|
|
251
|
+
name="cellprob_threshold",
|
|
252
|
+
)
|
|
253
|
+
if not 0.0 <= flow_threshold <= 1.0:
|
|
254
|
+
raise ValueError("flow_threshold must be between 0 and 1.")
|
|
255
|
+
if not -6.0 <= cellprob_threshold <= 6.0:
|
|
256
|
+
raise ValueError("cellprob_threshold must be between -6 and 6.")
|
|
185
257
|
|
|
186
|
-
print(f"Performing Cellpose v3 segmentation (model={
|
|
187
|
-
model = self._get_model(
|
|
258
|
+
print(f"Performing Cellpose v3 segmentation (model={model_type})...")
|
|
259
|
+
model = self._get_model(model_type)
|
|
188
260
|
masks, _, _, _ = model.eval(
|
|
189
261
|
image,
|
|
190
262
|
diameter=diameter,
|
|
191
|
-
channels=[
|
|
192
|
-
|
|
193
|
-
|
|
263
|
+
channels=[channel, nuclear_channel],
|
|
264
|
+
channel_axis=channel_axis,
|
|
265
|
+
flow_threshold=flow_threshold,
|
|
266
|
+
cellprob_threshold=cellprob_threshold,
|
|
267
|
+
)
|
|
268
|
+
masks = validate_labels(
|
|
269
|
+
masks,
|
|
270
|
+
name="Cellpose 3 mask",
|
|
271
|
+
dimensions=(2,),
|
|
272
|
+
expected_shape=expected_shape,
|
|
194
273
|
)
|
|
195
274
|
|
|
196
|
-
cell_count =
|
|
275
|
+
cell_count = object_count(masks)
|
|
197
276
|
print(f"Cellpose v3: {cell_count} objects detected")
|
|
198
277
|
|
|
199
278
|
mask_path = Path(arguments.mask)
|
|
200
|
-
mask_path
|
|
201
|
-
iio.imwrite(str(mask_path), masks.astype(np.uint32))
|
|
279
|
+
write_labels(mask_path, masks)
|
|
202
280
|
|
|
203
281
|
return self.Outputs(mask=mask_path, cell_count=cell_count)
|