Skip to content

_threshold_segmentation_utils

Pydantic models and utilities specific to threshold segmentation.

CreateMaskingRoiTable

Bases: BaseModel

Create Masking ROI Table Configuration.

ATTRIBUTE DESCRIPTION
mode

Mode to create masking ROI table.

TYPE: Literal['Create Masking ROI Table']

table_name

Name of the masking ROI table to be created. Defaults to "{output_label_name}_masking_ROI_table", where {output_label_name} is the name of the label image used for segmentation.

TYPE: str

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class CreateMaskingRoiTable(BaseModel):
    """Create Masking ROI Table Configuration.

    Attributes:
        mode (Literal["Create Masking ROI Table"]): Mode to create masking ROI table.
        table_name (str): Name of the masking ROI table to be created.
            Defaults to "{output_label_name}_masking_ROI_table", where
            {output_label_name} is the name of the label image used for segmentation.
    """

    mode: Literal["Create Masking ROI Table"] = "Create Masking ROI Table"
    table_name: str = "{output_label_name}_masking_ROI_table"
    """
    Name of the masking ROI table to be created. This can include the placeholder
    "{output_label_name}", which will be replaced by the name of the label image used
    for segmentation.
    """
    table_backend: AVAILABLE_TABLE_BACKENDS = DEFAULT_TABLE_BACKEND
    """
    Backend to use for storing the masking ROI table. Options are "anndata", "json",
    "csv", and "parquet".
    """

    def get_table_name(self, output_label_name: str) -> str:
        """Get the actual table name by replacing placeholder.

        Args:
            output_label_name (str): Name of the label image used for segmentation.

        Returns:
            str: Actual name of the masking ROI table.
        """
        return self.table_name.format(output_label_name=output_label_name)

    def create(
        self, ome_zarr: OmeZarrContainer, output_label_name: str, overwrite: bool = True
    ) -> None:
        """Create the masking ROI table based on the provided label image.

        Args:
            ome_zarr (OmeZarrContainer): The OME-Zarr container to add the table to.
            output_label_name (str): The name of the label image for which to create
                the masking ROI table.
            overwrite (bool): Whether to overwrite an existing table. Defaults to True.
        """
        table_name = self.get_table_name(output_label_name)
        label_img = ome_zarr.get_label(name=output_label_name)
        masking_roi_table = label_img.build_masking_roi_table()
        ome_zarr.add_table(
            name=table_name,
            table=masking_roi_table,
            overwrite=overwrite,
            backend=self.table_backend,
        )

table_backend: AVAILABLE_TABLE_BACKENDS = DEFAULT_TABLE_BACKEND class-attribute instance-attribute

Backend to use for storing the masking ROI table. Options are "anndata", "json", "csv", and "parquet".

table_name: str = '{output_label_name}_masking_ROI_table' class-attribute instance-attribute

Name of the masking ROI table to be created. This can include the placeholder "{output_label_name}", which will be replaced by the name of the label image used for segmentation.

create(ome_zarr, output_label_name, overwrite=True)

Create the masking ROI table based on the provided label image.

PARAMETER DESCRIPTION
ome_zarr

The OME-Zarr container to add the table to.

TYPE: OmeZarrContainer

output_label_name

The name of the label image for which to create the masking ROI table.

TYPE: str

overwrite

Whether to overwrite an existing table. Defaults to True.

TYPE: bool DEFAULT: True

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def create(
    self, ome_zarr: OmeZarrContainer, output_label_name: str, overwrite: bool = True
) -> None:
    """Create the masking ROI table based on the provided label image.

    Args:
        ome_zarr (OmeZarrContainer): The OME-Zarr container to add the table to.
        output_label_name (str): The name of the label image for which to create
            the masking ROI table.
        overwrite (bool): Whether to overwrite an existing table. Defaults to True.
    """
    table_name = self.get_table_name(output_label_name)
    label_img = ome_zarr.get_label(name=output_label_name)
    masking_roi_table = label_img.build_masking_roi_table()
    ome_zarr.add_table(
        name=table_name,
        table=masking_roi_table,
        overwrite=overwrite,
        backend=self.table_backend,
    )

get_table_name(output_label_name)

Get the actual table name by replacing placeholder.

PARAMETER DESCRIPTION
output_label_name

Name of the label image used for segmentation.

TYPE: str

RETURNS DESCRIPTION
str

Actual name of the masking ROI table.

TYPE: str

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
41
42
43
44
45
46
47
48
49
50
def get_table_name(self, output_label_name: str) -> str:
    """Get the actual table name by replacing placeholder.

    Args:
        output_label_name (str): Name of the label image used for segmentation.

    Returns:
        str: Actual name of the masking ROI table.
    """
    return self.table_name.format(output_label_name=output_label_name)

InputChannel

Bases: BaseModel

Input channel configuration for threshold segmentation.

This model is used to select a channel by label, wavelength ID, or index.

ATTRIBUTE DESCRIPTION
mode

Specifies how to interpret the identifier. Can be "label", "wavelength_id", or "index" (must be an integer string).

TYPE: Literal['label', 'wavelength_id', 'index']

identifier

Unique identifier for the channel. This can be a channel label, wavelength ID, or index.

TYPE: str

skip_if_missing

If True and the specified channel is not found in the image, the segmentation will be skipped instead of raising an error. Defaults to False.

TYPE: bool

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class InputChannel(BaseModel):
    """Input channel configuration for threshold segmentation.

    This model is used to select a channel by label, wavelength ID, or index.

    Attributes:
        mode (Literal["label", "wavelength_id", "index"]): Specifies how to
            interpret the identifier. Can be "label", "wavelength_id", or
            "index" (must be an integer string).
        identifier (str): Unique identifier for the channel. This can be a
            channel label, wavelength ID, or index.
        skip_if_missing (bool): If True and the specified channel is not found in
            the image, the segmentation will be skipped instead of raising an error.
            Defaults to False.
    """

    mode: Literal["label", "wavelength_id", "index"] = "label"
    """
    Specifies how to interpret the identifier for selecting the channel. Can be
    "label" to select by channel label, "wavelength_id" to select by wavelength ID,
    or "index" to select by channel index (the identifier must be an integer string).
    """
    identifier: str
    """
    Identifier for the channel to use for segmentation.
    """
    skip_if_missing: bool = False
    """
    If True and the specified channel is not found in the image, the segmentation
    will be skipped instead of raising an error. Defaults to False.
    """

    def to_channel_selection_models(self) -> ChannelSelectionModel:
        """Convert to ChannelSelectionModel.

        Returns:
            ChannelSelectionModel: Channel selection model.
        """
        return ChannelSelectionModel(identifier=self.identifier, mode=self.mode)

identifier: str instance-attribute

Identifier for the channel to use for segmentation.

mode: Literal['label', 'wavelength_id', 'index'] = 'label' class-attribute instance-attribute

Specifies how to interpret the identifier for selecting the channel. Can be "label" to select by channel label, "wavelength_id" to select by wavelength ID, or "index" to select by channel index (the identifier must be an integer string).

skip_if_missing: bool = False class-attribute instance-attribute

If True and the specified channel is not found in the image, the segmentation will be skipped instead of raising an error. Defaults to False.

to_channel_selection_models()

Convert to ChannelSelectionModel.

RETURNS DESCRIPTION
ChannelSelectionModel

Channel selection model.

TYPE: ChannelSelectionModel

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
127
128
129
130
131
132
133
def to_channel_selection_models(self) -> ChannelSelectionModel:
    """Convert to ChannelSelectionModel.

    Returns:
        ChannelSelectionModel: Channel selection model.
    """
    return ChannelSelectionModel(identifier=self.identifier, mode=self.mode)

OtsuConfiguration

Bases: BaseModel

Configuration for Otsu threshold-based segmentation.

ATTRIBUTE DESCRIPTION
method

Discriminator for Otsu threshold-based segmentation.

TYPE: Literal['Otsu']

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
class OtsuConfiguration(BaseModel):
    """Configuration for Otsu threshold-based segmentation.

    Attributes:
        method (Literal["Otsu"]): Discriminator for Otsu threshold-based segmentation.
    """

    method: Literal["Otsu"] = "Otsu"
    """
    Otsu's method automatically determines an optimal threshold value by maximizing
    the variance between foreground and background pixel intensities.
    """

    def threshold_value(self, image: np.ndarray) -> float:
        """Calculate Otsu threshold value for the given image."""
        return threshold_otsu(image)

method: Literal['Otsu'] = 'Otsu' class-attribute instance-attribute

Otsu's method automatically determines an optimal threshold value by maximizing the variance between foreground and background pixel intensities.

threshold_value(image)

Calculate Otsu threshold value for the given image.

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
174
175
176
def threshold_value(self, image: np.ndarray) -> float:
    """Calculate Otsu threshold value for the given image."""
    return threshold_otsu(image)

SimpleThresholdConfiguration

Bases: BaseModel

Configuration for threshold-based segmentation.

ATTRIBUTE DESCRIPTION
method

Discriminator for simple threshold-based segmentation.

TYPE: Literal['Simple Threshold']

threshold

Threshold value to apply for segmentation.

TYPE: float

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
class SimpleThresholdConfiguration(BaseModel):
    """Configuration for threshold-based segmentation.

    Attributes:
        method (Literal["Simple Threshold"]): Discriminator for simple
            threshold-based segmentation.
        threshold (float): Threshold value to apply for segmentation.
    """

    method: Literal["Simple Threshold"] = "Simple Threshold"
    """
    Simple threshold-based segmentation using a fixed threshold value.
    """

    threshold: float
    """
    Threshold value to use for segmentation. All pixels with intensity greater
    than this value will be considered foreground.
    """

    def threshold_value(self, image: np.ndarray) -> float:
        """Return the fixed threshold value."""
        return self.threshold

method: Literal['Simple Threshold'] = 'Simple Threshold' class-attribute instance-attribute

Simple threshold-based segmentation using a fixed threshold value.

threshold: float instance-attribute

Threshold value to use for segmentation. All pixels with intensity greater than this value will be considered foreground.

threshold_value(image)

Return the fixed threshold value.

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
156
157
158
def threshold_value(self, image: np.ndarray) -> float:
    """Return the fixed threshold value."""
    return self.threshold

SkipCreateMaskingRoiTable

Bases: BaseModel

Skip Creating Masking ROI Table Configuration.

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
74
75
76
77
78
79
80
81
82
83
84
85
86
class SkipCreateMaskingRoiTable(BaseModel):
    """Skip Creating Masking ROI Table Configuration."""

    mode: Literal["Skip Creating Masking ROI Table"] = "Skip Creating Masking ROI Table"
    """
    Mode to skip creating masking ROI table.
    """

    def create(
        self, ome_zarr: OmeZarrContainer, output_label_name: str, overwrite: bool = True
    ) -> None:
        """No-op create method for skipping masking ROI table creation."""
        pass

mode: Literal['Skip Creating Masking ROI Table'] = 'Skip Creating Masking ROI Table' class-attribute instance-attribute

Mode to skip creating masking ROI table.

create(ome_zarr, output_label_name, overwrite=True)

No-op create method for skipping masking ROI table creation.

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
82
83
84
85
86
def create(
    self, ome_zarr: OmeZarrContainer, output_label_name: str, overwrite: bool = True
) -> None:
    """No-op create method for skipping masking ROI table creation."""
    pass

segmentation_function(input_image, method)

Apply threshold-based segmentation to a single image chunk.

Pre- and post-processing transforms are handled by the segmentation iterator and should be configured via SegmentationTransformConfig.

PARAMETER DESCRIPTION
input_image

Input image data (after pre-processing transforms).

TYPE: ndarray

method

Configuration for the segmentation method.

TYPE: SegmentationConfiguration

RETURNS DESCRIPTION
ndarray

np.ndarray: Segmented label image with a leading channel dimension.

Source code in fractal_tasks_core/_threshold_segmentation_utils.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def segmentation_function(
    input_image: np.ndarray,
    method: SegmentationConfiguration,
) -> np.ndarray:
    """Apply threshold-based segmentation to a single image chunk.

    Pre- and post-processing transforms are handled by the segmentation iterator
    and should be configured via SegmentationTransformConfig.

    Args:
        input_image (np.ndarray): Input image data (after pre-processing transforms).
        method (SegmentationConfiguration): Configuration for the segmentation method.

    Returns:
        np.ndarray: Segmented label image with a leading channel dimension.
    """
    threshold_value = method.threshold_value(input_image)
    logger.info(f"Calculated threshold value: {threshold_value}")
    masks = input_image > threshold_value
    label_img = label(masks)
    if not isinstance(label_img, np.ndarray):
        raise TypeError("Label image must be a numpy array")
    label_img = label_img.astype(np.uint32)
    return label_img