bioimageflow-segmentation-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_segmentation_tools/__init__.py +60 -0
- bioimageflow_segmentation_tools/cellpose_sam.py +115 -0
- bioimageflow_segmentation_tools/cellpose_v3.py +203 -0
- bioimageflow_segmentation_tools/classical.py +795 -0
- bioimageflow_segmentation_tools/nninteractive.py +105 -0
- bioimageflow_segmentation_tools/stardist_segmenter.py +219 -0
- bioimageflow_segmentation_tools-0.1.6.dist-info/METADATA +69 -0
- bioimageflow_segmentation_tools-0.1.6.dist-info/RECORD +10 -0
- bioimageflow_segmentation_tools-0.1.6.dist-info/WHEEL +4 -0
- bioimageflow_segmentation_tools-0.1.6.dist-info/licenses/LICENSE +17 -0
|
@@ -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)
|