bioimageflow-segmentation-tools 0.1.6__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/.gitignore +23 -0
- bioimageflow_segmentation_tools-0.1.6/LICENSE +17 -0
- bioimageflow_segmentation_tools-0.1.6/PKG-INFO +69 -0
- bioimageflow_segmentation_tools-0.1.6/README.md +40 -0
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/__init__.py +60 -0
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/cellpose_sam.py +115 -0
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/cellpose_v3.py +203 -0
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/classical.py +795 -0
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/nninteractive.py +105 -0
- bioimageflow_segmentation_tools-0.1.6/bioimageflow_segmentation_tools/stardist_segmenter.py +219 -0
- bioimageflow_segmentation_tools-0.1.6/docs/images/README.md +4 -0
- bioimageflow_segmentation_tools-0.1.6/docs/index.md +50 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/cellpose3.md +54 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/cellpose_sam.md +14 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/distance_watershed_segment.md +48 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/filter_labels.md +51 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/local_threshold_segment.md +48 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/nninteractive.md +7 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/otsu_threshold_segment.md +48 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/postprocess_labels.md +39 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/split_touching_objects.md +45 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/stardist_segmenter.md +53 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/threshold_segment.md +42 -0
- bioimageflow_segmentation_tools-0.1.6/docs/tools/watershed_segment.md +43 -0
- bioimageflow_segmentation_tools-0.1.6/docs/workflows/bbbc038_segmentation_benchmark.md +28 -0
- bioimageflow_segmentation_tools-0.1.6/pyproject.toml +67 -0
- bioimageflow_segmentation_tools-0.1.6/tests/conftest.py +1 -0
- bioimageflow_segmentation_tools-0.1.6/tests/test_execution.py +525 -0
- bioimageflow_segmentation_tools-0.1.6/tests/test_schema.py +102 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
.DS_Store
|
|
2
|
+
.worktrees/
|
|
3
|
+
.claude/worktrees/
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.claude/
|
|
6
|
+
.venv/
|
|
7
|
+
TODO.md
|
|
8
|
+
bif_data/
|
|
9
|
+
data/
|
|
10
|
+
!example_workflows/fish_analysis/data/
|
|
11
|
+
example_workflows/bbbc038_segmentation_benchmark/data/
|
|
12
|
+
example_workflows/outputs/
|
|
13
|
+
!packages/bioimageflow-common-tools/bioimageflow_common_tools/data/
|
|
14
|
+
packages/bioimageflow-common-tools/bioimageflow_common_tools/data/*
|
|
15
|
+
!packages/bioimageflow-common-tools/bioimageflow_common_tools/data/blobs.txt
|
|
16
|
+
packages/bioimageflow-common-tools/bioimageflow_common_tools/.vscode/
|
|
17
|
+
__pycache__/
|
|
18
|
+
docs/build/
|
|
19
|
+
docs/_build/
|
|
20
|
+
wetlands/
|
|
21
|
+
wetlands-lib/
|
|
22
|
+
docs/parsl_phase1a_implementation_spec.md
|
|
23
|
+
example_workflows/fish_analysis/data/*.tif
|
|
@@ -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.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bioimageflow-segmentation-tools
|
|
3
|
+
Version: 0.1.6
|
|
4
|
+
Summary: Segmentation tools for BioImageFlow
|
|
5
|
+
Project-URL: Homepage, https://github.com/Inria-SAIRPICO/bioimageflow
|
|
6
|
+
Project-URL: Documentation, https://bioimageflow.readthedocs.io/latest/
|
|
7
|
+
Project-URL: Repository, https://github.com/Inria-SAIRPICO/bioimageflow
|
|
8
|
+
Project-URL: Issues, https://github.com/Inria-SAIRPICO/bioimageflow/issues
|
|
9
|
+
Author: BioImageFlow Contributors
|
|
10
|
+
License-Expression: BSD-4-Clause
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: bioimage-analysis,bioimageflow,microscopy,workflow
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: bioimageflow-core<0.2,>=0.1.6
|
|
25
|
+
Requires-Dist: imageio>=2.31.0
|
|
26
|
+
Requires-Dist: numpy>=1.23.5
|
|
27
|
+
Requires-Dist: scikit-image>=0.21.0
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# bioimageflow-segmentation-tools
|
|
31
|
+
|
|
32
|
+
Segmentation-focused tool package for BioImageFlow.
|
|
33
|
+
|
|
34
|
+
## Tools
|
|
35
|
+
|
|
36
|
+
- `Cellpose3`: Cellpose v3 pretrained model wrapper.
|
|
37
|
+
- `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
|
|
38
|
+
- `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
|
|
39
|
+
- `OtsuThresholdSegment`: compute a global Otsu threshold and label foreground objects.
|
|
40
|
+
- `LocalThresholdSegment`: compute a Sauvola local threshold and label foreground objects.
|
|
41
|
+
- `WatershedSegment`: split foreground regions from marker labels or connected components.
|
|
42
|
+
- `DistanceWatershedSegment`: split foreground with marker-free distance-transform watershed.
|
|
43
|
+
- `SplitTouchingObjects`: split clumped labels using distance-transform watershed.
|
|
44
|
+
- `FilterLabels`: remove labels by area, border contact, intensity, and shape constraints.
|
|
45
|
+
- `PostprocessLabels`: remove small labels and relabel label images sequentially.
|
|
46
|
+
|
|
47
|
+
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
|
+
`Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
|
|
49
|
+
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
|
+
Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
|
|
51
|
+
|
|
52
|
+
## Example
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from bioimageflow_core import Arguments
|
|
56
|
+
from bioimageflow_segmentation_tools import ThresholdSegment
|
|
57
|
+
|
|
58
|
+
segment = ThresholdSegment()
|
|
59
|
+
result = segment.process_row(
|
|
60
|
+
Arguments(
|
|
61
|
+
input_image="input.tif",
|
|
62
|
+
threshold=128.0,
|
|
63
|
+
labels="labels.tif",
|
|
64
|
+
above=True,
|
|
65
|
+
)
|
|
66
|
+
)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Workflow graph construction with `segment(...)` requires installing the main-process `bioimageflow` orchestrator alongside this package.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# bioimageflow-segmentation-tools
|
|
2
|
+
|
|
3
|
+
Segmentation-focused tool package for BioImageFlow.
|
|
4
|
+
|
|
5
|
+
## Tools
|
|
6
|
+
|
|
7
|
+
- `Cellpose3`: Cellpose v3 pretrained model wrapper.
|
|
8
|
+
- `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
|
|
9
|
+
- `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
|
|
10
|
+
- `OtsuThresholdSegment`: compute a global Otsu threshold and label foreground objects.
|
|
11
|
+
- `LocalThresholdSegment`: compute a Sauvola local threshold and label foreground objects.
|
|
12
|
+
- `WatershedSegment`: split foreground regions from marker labels or connected components.
|
|
13
|
+
- `DistanceWatershedSegment`: split foreground with marker-free distance-transform watershed.
|
|
14
|
+
- `SplitTouchingObjects`: split clumped labels using distance-transform watershed.
|
|
15
|
+
- `FilterLabels`: remove labels by area, border contact, intensity, and shape constraints.
|
|
16
|
+
- `PostprocessLabels`: remove small labels and relabel label images sequentially.
|
|
17
|
+
|
|
18
|
+
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
|
+
`Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
|
|
20
|
+
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
|
+
Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
|
|
22
|
+
|
|
23
|
+
## Example
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from bioimageflow_core import Arguments
|
|
27
|
+
from bioimageflow_segmentation_tools import ThresholdSegment
|
|
28
|
+
|
|
29
|
+
segment = ThresholdSegment()
|
|
30
|
+
result = segment.process_row(
|
|
31
|
+
Arguments(
|
|
32
|
+
input_image="input.tif",
|
|
33
|
+
threshold=128.0,
|
|
34
|
+
labels="labels.tif",
|
|
35
|
+
above=True,
|
|
36
|
+
)
|
|
37
|
+
)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Workflow graph construction with `segment(...)` requires installing the main-process `bioimageflow` orchestrator alongside this package.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""BioImageFlow segmentation tools."""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .cellpose_sam import CellposeSAM as CellposeSAM
|
|
8
|
+
from .cellpose_v3 import Cellpose3 as Cellpose3
|
|
9
|
+
from .classical import DistanceWatershedSegment as DistanceWatershedSegment
|
|
10
|
+
from .classical import FilterLabels as FilterLabels
|
|
11
|
+
from .classical import LocalThresholdSegment as LocalThresholdSegment
|
|
12
|
+
from .classical import OtsuThresholdSegment as OtsuThresholdSegment
|
|
13
|
+
from .classical import PostprocessLabels as PostprocessLabels
|
|
14
|
+
from .classical import SplitTouchingObjects as SplitTouchingObjects
|
|
15
|
+
from .classical import ThresholdSegment as ThresholdSegment
|
|
16
|
+
from .classical import WatershedSegment as WatershedSegment
|
|
17
|
+
from .nninteractive import nnInteractive as nnInteractive
|
|
18
|
+
from .stardist_segmenter import StarDistSegmenter as StarDistSegmenter
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_EXPORTS = {
|
|
22
|
+
"CellposeSAM": ("cellpose_sam", "CellposeSAM"),
|
|
23
|
+
"Cellpose3": ("cellpose_v3", "Cellpose3"),
|
|
24
|
+
"DistanceWatershedSegment": ("classical", "DistanceWatershedSegment"),
|
|
25
|
+
"FilterLabels": ("classical", "FilterLabels"),
|
|
26
|
+
"LocalThresholdSegment": ("classical", "LocalThresholdSegment"),
|
|
27
|
+
"OtsuThresholdSegment": ("classical", "OtsuThresholdSegment"),
|
|
28
|
+
"nnInteractive": ("nninteractive", "nnInteractive"),
|
|
29
|
+
"PostprocessLabels": ("classical", "PostprocessLabels"),
|
|
30
|
+
"SplitTouchingObjects": ("classical", "SplitTouchingObjects"),
|
|
31
|
+
"StarDistSegmenter": ("stardist_segmenter", "StarDistSegmenter"),
|
|
32
|
+
"ThresholdSegment": ("classical", "ThresholdSegment"),
|
|
33
|
+
"WatershedSegment": ("classical", "WatershedSegment"),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"CellposeSAM",
|
|
38
|
+
"Cellpose3",
|
|
39
|
+
"DistanceWatershedSegment",
|
|
40
|
+
"FilterLabels",
|
|
41
|
+
"LocalThresholdSegment",
|
|
42
|
+
"OtsuThresholdSegment",
|
|
43
|
+
"PostprocessLabels",
|
|
44
|
+
"SplitTouchingObjects",
|
|
45
|
+
"StarDistSegmenter",
|
|
46
|
+
"ThresholdSegment",
|
|
47
|
+
"WatershedSegment",
|
|
48
|
+
"nnInteractive",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def __getattr__(name: str) -> Any:
|
|
53
|
+
try:
|
|
54
|
+
module_name, attribute_name = _EXPORTS[name]
|
|
55
|
+
except KeyError as exc:
|
|
56
|
+
raise AttributeError(name) from exc
|
|
57
|
+
module = import_module(f".{module_name}", __name__)
|
|
58
|
+
value = getattr(module, attribute_name)
|
|
59
|
+
globals()[name] = value
|
|
60
|
+
return value
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Cellpose-SAM segmentation wrapper."""
|
|
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
|
+
Layout,
|
|
15
|
+
ProcessingTool,
|
|
16
|
+
Semantic,
|
|
17
|
+
Template,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
cellpose_sam_env = EnvironmentSpec(
|
|
22
|
+
name="segmentation-cellpose-sam",
|
|
23
|
+
dependencies={
|
|
24
|
+
"python": "3.12",
|
|
25
|
+
"pip": [
|
|
26
|
+
"cellpose==4.2.1.1",
|
|
27
|
+
"imageio==2.37.3",
|
|
28
|
+
"numpy==2.5.0",
|
|
29
|
+
"tifffile==2026.6.1",
|
|
30
|
+
],
|
|
31
|
+
}
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CellposeSAM(ProcessingTool):
|
|
36
|
+
"""Segment cells or nuclei with Cellpose-SAM models."""
|
|
37
|
+
|
|
38
|
+
display_name = "Cellpose-SAM"
|
|
39
|
+
documentation = "Segment cells or nuclei using Cellpose-SAM and write a label mask."
|
|
40
|
+
category = Category.SEGMENTATION
|
|
41
|
+
tags = ["segmentation", "cellpose", "sam", "deep learning"]
|
|
42
|
+
environment = cellpose_sam_env
|
|
43
|
+
|
|
44
|
+
def __init__(self) -> None:
|
|
45
|
+
super().__init__()
|
|
46
|
+
self._model_cache_key: str | None = None
|
|
47
|
+
self._cached_model: Any | None = None
|
|
48
|
+
|
|
49
|
+
def clear_model_cache(self) -> None:
|
|
50
|
+
"""Release the cached Cellpose-SAM model held by this tool instance."""
|
|
51
|
+
self._cached_model = None
|
|
52
|
+
self._model_cache_key = None
|
|
53
|
+
|
|
54
|
+
def _get_model(self, model_type: str) -> Any:
|
|
55
|
+
"""Return the model for *model_type*, replacing a different cached model."""
|
|
56
|
+
if self._cached_model is None or self._model_cache_key != model_type:
|
|
57
|
+
from cellpose import models # type: ignore
|
|
58
|
+
|
|
59
|
+
self.clear_model_cache()
|
|
60
|
+
model_cls = getattr(models, "CellposeModel", None) or getattr(
|
|
61
|
+
models, "Cellpose"
|
|
62
|
+
)
|
|
63
|
+
model = model_cls(model_type=model_type)
|
|
64
|
+
self._cached_model = model
|
|
65
|
+
self._model_cache_key = model_type
|
|
66
|
+
return self._cached_model
|
|
67
|
+
|
|
68
|
+
class Inputs(IOModel):
|
|
69
|
+
input_image: Annotated[
|
|
70
|
+
Path,
|
|
71
|
+
ImageSpec(
|
|
72
|
+
semantics={Semantic.INTENSITY},
|
|
73
|
+
layouts={Layout.PLANAR, Layout.PLANAR_CHANNEL},
|
|
74
|
+
),
|
|
75
|
+
GUIMeta(
|
|
76
|
+
display_name="Input image",
|
|
77
|
+
description="2D intensity image to segment.",
|
|
78
|
+
connectable=Connectable.BY_DEFAULT,
|
|
79
|
+
),
|
|
80
|
+
]
|
|
81
|
+
model_type: Annotated[
|
|
82
|
+
str,
|
|
83
|
+
GUIMeta(display_name="Model", description="Cellpose-SAM model name."),
|
|
84
|
+
] = "cpsam"
|
|
85
|
+
diameter: Annotated[float, GUIMeta(min=0.0, max=500.0, step=0.5)] = 0.0
|
|
86
|
+
flow_threshold: Annotated[float, GUIMeta(min=0.0, max=1.0, step=0.05)] = 0.4
|
|
87
|
+
cellprob_threshold: Annotated[float, GUIMeta(min=-6.0, max=6.0, step=0.5)] = 0.0
|
|
88
|
+
|
|
89
|
+
class Outputs(IOModel):
|
|
90
|
+
mask: Annotated[
|
|
91
|
+
Path,
|
|
92
|
+
ImageSpec(semantics={Semantic.LABEL}, layouts={Layout.PLANAR}),
|
|
93
|
+
GUIMeta(display_name="Segmentation mask"),
|
|
94
|
+
] = Template("{input_image.stem}_cellpose_sam_mask{ext}")
|
|
95
|
+
cell_count: Annotated[int, GUIMeta(display_name="Object count")]
|
|
96
|
+
|
|
97
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
98
|
+
import imageio.v3 as iio
|
|
99
|
+
import numpy as np
|
|
100
|
+
|
|
101
|
+
image = iio.imread(arguments.input_image)
|
|
102
|
+
diameter = arguments.diameter if arguments.diameter > 0 else None
|
|
103
|
+
model = self._get_model(arguments.model_type)
|
|
104
|
+
result = model.eval(
|
|
105
|
+
image,
|
|
106
|
+
diameter=diameter,
|
|
107
|
+
flow_threshold=arguments.flow_threshold,
|
|
108
|
+
cellprob_threshold=arguments.cellprob_threshold,
|
|
109
|
+
)
|
|
110
|
+
masks = result[0] if isinstance(result, tuple) else result
|
|
111
|
+
|
|
112
|
+
mask_path = Path(arguments.mask)
|
|
113
|
+
mask_path.parent.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
iio.imwrite(mask_path, np.asarray(masks, dtype=np.uint32))
|
|
115
|
+
return self.Outputs(mask=mask_path, cell_count=int(np.asarray(masks).max()))
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Cellpose3 - fast cell/nuclei segmentation using Cellpose v3."""
|
|
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
|
+
Layout,
|
|
15
|
+
ProcessingTool,
|
|
16
|
+
Semantic,
|
|
17
|
+
Template,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
cellpose_v3_env = EnvironmentSpec(
|
|
21
|
+
name="segmentation-cellpose-v3",
|
|
22
|
+
dependencies={
|
|
23
|
+
"python": "3.12",
|
|
24
|
+
"pip": [
|
|
25
|
+
"cellpose==3.1.1.1",
|
|
26
|
+
"imageio==2.37.3",
|
|
27
|
+
"packaging==26.2",
|
|
28
|
+
"tifffile==2026.3.3",
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Cellpose3(ProcessingTool):
|
|
35
|
+
"""Segment cells or nuclei using the faster pre-SAM Cellpose v3 models."""
|
|
36
|
+
|
|
37
|
+
display_name = "Cellpose 3"
|
|
38
|
+
documentation = (
|
|
39
|
+
"Segment cells or nuclei using Cellpose v3 pretrained models such as "
|
|
40
|
+
"'cyto3' and 'nuclei'. Produces a labeled mask image."
|
|
41
|
+
)
|
|
42
|
+
category = Category.SEGMENTATION
|
|
43
|
+
tags = ["segmentation", "cellpose", "cellpose3", "deep learning"]
|
|
44
|
+
environment = cellpose_v3_env
|
|
45
|
+
|
|
46
|
+
def __init__(self) -> None:
|
|
47
|
+
super().__init__()
|
|
48
|
+
self._model_cache_key: str | None = None
|
|
49
|
+
self._cached_model: Any | None = None
|
|
50
|
+
|
|
51
|
+
def clear_model_cache(self) -> None:
|
|
52
|
+
"""Release the cached Cellpose model held by this tool instance."""
|
|
53
|
+
self._cached_model = None
|
|
54
|
+
self._model_cache_key = None
|
|
55
|
+
|
|
56
|
+
def _get_model(self, model_type: str) -> Any:
|
|
57
|
+
"""Return the model for *model_type*, replacing a different cached model."""
|
|
58
|
+
if self._cached_model is None or self._model_cache_key != model_type:
|
|
59
|
+
from cellpose import models # type: ignore
|
|
60
|
+
|
|
61
|
+
self.clear_model_cache()
|
|
62
|
+
model = models.Cellpose(model_type=model_type)
|
|
63
|
+
self._cached_model = model
|
|
64
|
+
self._model_cache_key = model_type
|
|
65
|
+
return self._cached_model
|
|
66
|
+
|
|
67
|
+
class Inputs(IOModel):
|
|
68
|
+
input_image: Annotated[
|
|
69
|
+
Path,
|
|
70
|
+
ImageSpec(
|
|
71
|
+
semantics={Semantic.INTENSITY},
|
|
72
|
+
layouts={Layout.PLANAR, Layout.PLANAR_CHANNEL},
|
|
73
|
+
),
|
|
74
|
+
GUIMeta(
|
|
75
|
+
display_name="Input image",
|
|
76
|
+
description="2D intensity image to segment, optionally with channels.",
|
|
77
|
+
connectable=Connectable.BY_DEFAULT,
|
|
78
|
+
),
|
|
79
|
+
]
|
|
80
|
+
diameter: Annotated[
|
|
81
|
+
float,
|
|
82
|
+
GUIMeta(
|
|
83
|
+
display_name="Object diameter",
|
|
84
|
+
description=(
|
|
85
|
+
"Approximate object diameter in pixels. Set to 0 for "
|
|
86
|
+
"Cellpose size estimation."
|
|
87
|
+
),
|
|
88
|
+
min=0.0,
|
|
89
|
+
max=500.0,
|
|
90
|
+
step=0.5,
|
|
91
|
+
group="general",
|
|
92
|
+
),
|
|
93
|
+
] = 0.0
|
|
94
|
+
model_type: Annotated[
|
|
95
|
+
str,
|
|
96
|
+
GUIMeta(
|
|
97
|
+
display_name="Model",
|
|
98
|
+
description="Cellpose v3 pretrained model name, for example 'cyto3' or 'nuclei'.",
|
|
99
|
+
group="general",
|
|
100
|
+
),
|
|
101
|
+
] = "cyto3"
|
|
102
|
+
channel: Annotated[
|
|
103
|
+
int,
|
|
104
|
+
GUIMeta(
|
|
105
|
+
display_name="Segmentation channel",
|
|
106
|
+
description=(
|
|
107
|
+
"Cellpose channel selector: 0 means grayscale/current image; "
|
|
108
|
+
"1 red, 2 green, 3 blue for RGB-like inputs."
|
|
109
|
+
),
|
|
110
|
+
min=0,
|
|
111
|
+
max=3,
|
|
112
|
+
step=1,
|
|
113
|
+
group="channels",
|
|
114
|
+
),
|
|
115
|
+
] = 0
|
|
116
|
+
nuclear_channel: Annotated[
|
|
117
|
+
int,
|
|
118
|
+
GUIMeta(
|
|
119
|
+
display_name="Nuclear channel",
|
|
120
|
+
description=(
|
|
121
|
+
"Optional nuclear channel selector for cytoplasm models. "
|
|
122
|
+
"Use 0 when no nuclear channel should be supplied."
|
|
123
|
+
),
|
|
124
|
+
min=0,
|
|
125
|
+
max=3,
|
|
126
|
+
step=1,
|
|
127
|
+
group="channels",
|
|
128
|
+
),
|
|
129
|
+
] = 0
|
|
130
|
+
flow_threshold: Annotated[
|
|
131
|
+
float,
|
|
132
|
+
GUIMeta(
|
|
133
|
+
display_name="Flow threshold",
|
|
134
|
+
description=(
|
|
135
|
+
"Maximum allowed flow reconstruction error. Increase to keep "
|
|
136
|
+
"more ROIs; decrease to reject more ill-shaped ROIs."
|
|
137
|
+
),
|
|
138
|
+
min=0.0,
|
|
139
|
+
max=1.0,
|
|
140
|
+
step=0.05,
|
|
141
|
+
group="advanced",
|
|
142
|
+
),
|
|
143
|
+
] = 0.4
|
|
144
|
+
cellprob_threshold: Annotated[
|
|
145
|
+
float,
|
|
146
|
+
GUIMeta(
|
|
147
|
+
display_name="Cell probability threshold",
|
|
148
|
+
description=(
|
|
149
|
+
"Threshold for Cellpose's cell-probability output. Lower values "
|
|
150
|
+
"usually return more ROIs; higher values return fewer ROIs."
|
|
151
|
+
),
|
|
152
|
+
min=-6.0,
|
|
153
|
+
max=6.0,
|
|
154
|
+
step=0.5,
|
|
155
|
+
group="advanced",
|
|
156
|
+
),
|
|
157
|
+
] = 0.0
|
|
158
|
+
|
|
159
|
+
class Outputs(IOModel):
|
|
160
|
+
mask: Annotated[
|
|
161
|
+
Path,
|
|
162
|
+
ImageSpec(
|
|
163
|
+
semantics={Semantic.LABEL},
|
|
164
|
+
layouts={Layout.PLANAR},
|
|
165
|
+
),
|
|
166
|
+
GUIMeta(
|
|
167
|
+
display_name="Segmentation mask",
|
|
168
|
+
description="Label image where each detected object has a unique integer ID.",
|
|
169
|
+
),
|
|
170
|
+
] = Template("{input_image.stem}_cellpose3_mask{ext}")
|
|
171
|
+
cell_count: Annotated[
|
|
172
|
+
int,
|
|
173
|
+
GUIMeta(
|
|
174
|
+
display_name="Object count",
|
|
175
|
+
description="Number of non-background labels detected in the mask.",
|
|
176
|
+
),
|
|
177
|
+
]
|
|
178
|
+
|
|
179
|
+
def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
|
|
180
|
+
import imageio.v3 as iio
|
|
181
|
+
import numpy as np
|
|
182
|
+
|
|
183
|
+
image = iio.imread(str(arguments.input_image))
|
|
184
|
+
diameter = arguments.diameter if arguments.diameter > 0 else None
|
|
185
|
+
|
|
186
|
+
print(f"Performing Cellpose v3 segmentation (model={arguments.model_type})...")
|
|
187
|
+
model = self._get_model(arguments.model_type)
|
|
188
|
+
masks, _, _, _ = model.eval(
|
|
189
|
+
image,
|
|
190
|
+
diameter=diameter,
|
|
191
|
+
channels=[arguments.channel, arguments.nuclear_channel],
|
|
192
|
+
flow_threshold=arguments.flow_threshold,
|
|
193
|
+
cellprob_threshold=arguments.cellprob_threshold,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
cell_count = int(masks.max())
|
|
197
|
+
print(f"Cellpose v3: {cell_count} objects detected")
|
|
198
|
+
|
|
199
|
+
mask_path = Path(arguments.mask)
|
|
200
|
+
mask_path.parent.mkdir(parents=True, exist_ok=True)
|
|
201
|
+
iio.imwrite(str(mask_path), masks.astype(np.uint32))
|
|
202
|
+
|
|
203
|
+
return self.Outputs(mask=mask_path, cell_count=cell_count)
|