micro_sam.classical_features

Classical (hand-crafted) image features to add on top of the foundation model features.

The pixel features are an ilastik-like multi-scale filter bank, computed with bioimage_cpp on the image resized to the pixel classification feature grid. The object features are morphology and intensity statistics, computed with bioimage_py on the full resolution segmentation, with scipy and skimage only for the statistics these packages do not provide.

  1"""Classical (hand-crafted) image features to add on top of the foundation model features.
  2
  3The pixel features are an ilastik-like multi-scale filter bank, computed with `bioimage_cpp` on the
  4image resized to the pixel classification feature grid. The object features are morphology and
  5intensity statistics, computed with `bioimage_py` on the full resolution segmentation, with `scipy` and
  6`skimage` only for the statistics these packages do not provide.
  7"""
  8
  9import warnings
 10from multiprocessing import cpu_count
 11from typing import Optional, Sequence, Tuple
 12
 13import numpy as np
 14import pandas as pd
 15from scipy import ndimage
 16from skimage.measure import regionprops_table
 17
 18import bioimage_cpp.filters as bic_filters
 19from bioimage_cpp.transformation import resample
 20
 21from bioimage_py.morphology import morphology, regionprops
 22
 23
 24PIXEL_FEATURES = (
 25    "gaussian_smoothing",
 26    "laplacian_of_gaussian",
 27    "gaussian_gradient_magnitude",
 28    "difference_of_gaussians",
 29    "structure_tensor_eigenvalues",
 30    "hessian_of_gaussian_eigenvalues",
 31)
 32"""The supported classical pixel features. Each one is computed per channel and per sigma."""
 33
 34OBJECT_FEATURES = (
 35    "size",
 36    "intensity_mean",
 37    "intensity_std",
 38    "intensity_min",
 39    "intensity_max",
 40    "extent",
 41    "equivalent_diameter",
 42    "axis_major_length",
 43    "axis_minor_length",
 44    "eccentricity",
 45    "solidity",
 46)
 47"""The supported classical object features. The intensity features are computed per channel."""
 48
 49DEFAULT_SIGMAS = (0.5, 1.0, 2.0, 4.0)
 50"""The default filter scales, in pixels of the pixel classification feature grid."""
 51
 52# The ratio between the two scales of the difference of Gaussians.
 53DOG_RATIO = 1.6
 54
 55INTENSITY_FEATURES = {
 56    "intensity_mean": ndimage.mean,
 57    "intensity_std": ndimage.standard_deviation,
 58    "intensity_min": ndimage.minimum,
 59    "intensity_max": ndimage.maximum,
 60}
 61SHAPE_FEATURES = ("extent", "equivalent_diameter", "axis_major_length", "axis_minor_length", "eccentricity")
 62
 63
 64def _validate(features: Sequence[str], supported: Sequence[str], kind: str) -> list:
 65    features = list(features)
 66    if not features:
 67        raise ValueError(f"Expect at least one classical {kind} feature, choose from {list(supported)}.")
 68    invalid = [name for name in features if name not in supported]
 69    if invalid:
 70        raise ValueError(f"Invalid classical {kind} features {invalid}, choose from {list(supported)}.")
 71    # Use the canonical order, so that the feature columns do not depend on the order of the selection.
 72    return [name for name in supported if name in features]
 73
 74
 75def _to_channels(image: np.ndarray, ndim: int) -> np.ndarray:
 76    """Bring the image to float32 with a trailing channel axis, normalized to [0, 1] per channel."""
 77    image = np.asarray(image)
 78    if image.ndim == ndim:
 79        image = image[..., None]
 80    elif image.ndim != ndim + 1:
 81        raise ValueError(f"Expect an image with {ndim} spatial dimensions and optional channels, got {image.shape}.")
 82    image = image.astype("float32")
 83    axes = tuple(range(ndim))
 84    minval, maxval = image.min(axis=axes), image.max(axis=axes)
 85    return (image - minval) / np.maximum(maxval - minval, 1e-7)
 86
 87
 88def _resize_plane(plane: np.ndarray, target_hw: Tuple[int, int]) -> np.ndarray:
 89    # Anti-aliased resize with pixel-center alignment, matching 'skimage.transform.resize'.
 90    scale = [s / t for s, t in zip(plane.shape, target_hw)]
 91    matrix = np.array([[scale[0], 0.0, (scale[0] - 1) / 2], [0.0, scale[1], (scale[1] - 1) / 2]])
 92    return resample(
 93        np.ascontiguousarray(plane), matrix, bounding_box=tuple(slice(0, t) for t in target_hw)
 94    )
 95
 96
 97def _filter_plane(plane: np.ndarray, features: Sequence[str], sigmas: Sequence[float]) -> list:
 98    responses = []
 99    for sigma in sigmas:
100        for name in features:
101            if name == "gaussian_smoothing":
102                responses.append(bic_filters.gaussian_smoothing(plane, sigma))
103            elif name == "laplacian_of_gaussian":
104                responses.append(bic_filters.laplacian_of_gaussian(plane, sigma))
105            elif name == "gaussian_gradient_magnitude":
106                responses.append(bic_filters.gaussian_gradient_magnitude(plane, sigma))
107            elif name == "difference_of_gaussians":
108                smoothed = bic_filters.gaussian_smoothing(plane, sigma)
109                responses.append(smoothed - bic_filters.gaussian_smoothing(plane, DOG_RATIO * sigma))
110            elif name == "structure_tensor_eigenvalues":
111                eigenvalues = bic_filters.structure_tensor_eigenvalues(plane, sigma, sigma)
112                responses.extend(np.moveaxis(eigenvalues, -1, 0))
113            else:
114                eigenvalues = bic_filters.hessian_of_gaussian_eigenvalues(plane, sigma)
115                responses.extend(np.moveaxis(eigenvalues, -1, 0))
116    return responses
117
118
119def compute_classical_pixel_features(
120    image: np.ndarray,
121    grid_shape: Tuple[int, ...],
122    features: Sequence[str] = PIXEL_FEATURES,
123    sigmas: Sequence[float] = DEFAULT_SIGMAS,
124) -> np.ndarray:
125    """Compute classical filter features on the pixel classification feature grid.
126
127    The image is normalized to [0, 1] per channel and resized to the grid, then the filters are applied
128    per channel, per sigma and, for 3d data, per slice. The result is aligned row-wise with the features
129    of `pixel_classification.compute_pixel_features`.
130
131    Args:
132        image: The image, of shape (H, W) or (Z, H, W), with an optional trailing channel axis.
133        grid_shape: The feature grid shape, (gh, gw) for 2d or (Z, gh, gw) for 3d.
134        features: The classical pixel features to compute, a subset of `PIXEL_FEATURES`.
135        sigmas: The filter scales, in pixels of the feature grid.
136
137    Returns:
138        The per-pixel features, of shape (N, F) flattened over the grid in row-major order.
139    """
140    features = _validate(features, PIXEL_FEATURES, "pixel")
141    image = _to_channels(image, len(grid_shape))
142    if len(grid_shape) == 2:
143        image = image[None]
144        grid_shape = (1,) + tuple(grid_shape)
145    if image.shape[0] != grid_shape[0]:
146        raise ValueError(f"The image has {image.shape[0]} slices, but the feature grid has {grid_shape[0]}.")
147
148    planes = []
149    for z in range(grid_shape[0]):
150        responses = []
151        for c in range(image.shape[-1]):
152            plane = _resize_plane(image[z, ..., c], grid_shape[1:])
153            responses.extend(_filter_plane(plane, features, sigmas))
154        planes.append(np.stack(responses, axis=-1))
155    return np.stack(planes).reshape(-1, planes[0].shape[-1]).astype("float32")
156
157
158def compute_classical_object_features(
159    image: np.ndarray,
160    segmentation: np.ndarray,
161    seg_ids: Optional[np.ndarray] = None,
162    features: Sequence[str] = OBJECT_FEATURES,
163) -> np.ndarray:
164    """Compute classical morphology and intensity features per object.
165
166    Args:
167        image: The image, with the spatial shape of the segmentation and an optional trailing channel axis.
168        segmentation: The segmentation, of shape (H, W) or (Z, H, W). The background id 0 is ignored.
169        seg_ids: The ids of the objects to compute the features for, e.g. the ids returned by
170            `object_classification.compute_object_features`. By default all objects in the segmentation.
171        features: The classical object features to compute, a subset of `OBJECT_FEATURES`.
172
173    Returns:
174        The object features, of shape (len(seg_ids), F), in the order of `seg_ids`.
175    """
176    features = _validate(features, OBJECT_FEATURES, "object")
177    segmentation = np.asarray(segmentation)
178    if segmentation.dtype not in (np.uint32, np.uint64, np.int32, np.int64):
179        segmentation = segmentation.astype("uint32")
180    image = _to_channels(image, segmentation.ndim)
181    if image.shape[:-1] != segmentation.shape:
182        raise ValueError(f"The image shape {image.shape} does not match the segmentation shape {segmentation.shape}.")
183
184    if seg_ids is None:
185        seg_ids = np.unique(segmentation)
186        seg_ids = seg_ids[seg_ids != 0]
187    seg_ids = np.asarray(seg_ids)
188
189    columns = {}
190    shape_features = [name for name in features if name in SHAPE_FEATURES]
191    if "size" in features or shape_features:
192        table = morphology(segmentation)
193        if "size" in features:
194            columns["size"] = table.set_index("label")["size"]
195        if shape_features:
196            props = regionprops(segmentation, table, num_workers=cpu_count()).set_index("label")
197            major, minor = props["axis_major_length"], props["axis_minor_length"]
198            eccentricity = np.sqrt(1.0 - (minor / major.where(major > 0)) ** 2).fillna(0.0)
199            shape_columns = {
200                "extent": props["extent"], "equivalent_diameter": props["equivalent_diameter_area"],
201                "axis_major_length": major, "axis_minor_length": minor, "eccentricity": eccentricity,
202            }
203            columns.update({name: shape_columns[name] for name in shape_features})
204
205    if "solidity" in features:
206        # Flat or tiny objects have no convex hull, we treat them as fully convex.
207        with warnings.catch_warnings(), np.errstate(divide="ignore", invalid="ignore"):
208            warnings.simplefilter("ignore")
209            props = regionprops_table(segmentation, properties=("label", "solidity"))
210        solidity = np.where(np.isfinite(props["solidity"]), props["solidity"], 1.0)
211        columns["solidity"] = pd.Series(solidity, index=props["label"])
212
213    ordered = {}
214    for name in features:
215        if name in INTENSITY_FEATURES:
216            for c in range(image.shape[-1]):
217                values = INTENSITY_FEATURES[name](image[..., c], labels=segmentation, index=seg_ids)
218                ordered[f"{name}_{c}"] = pd.Series(np.asarray(values), index=seg_ids)
219        else:
220            ordered[name] = columns[name]
221
222    # Objects that are missing from the segmentation get zero features.
223    result = pd.DataFrame(ordered).reindex(seg_ids).fillna(0.0)
224    return result.to_numpy(dtype="float32")
PIXEL_FEATURES = ('gaussian_smoothing', 'laplacian_of_gaussian', 'gaussian_gradient_magnitude', 'difference_of_gaussians', 'structure_tensor_eigenvalues', 'hessian_of_gaussian_eigenvalues')

The supported classical pixel features. Each one is computed per channel and per sigma.

OBJECT_FEATURES = ('size', 'intensity_mean', 'intensity_std', 'intensity_min', 'intensity_max', 'extent', 'equivalent_diameter', 'axis_major_length', 'axis_minor_length', 'eccentricity', 'solidity')

The supported classical object features. The intensity features are computed per channel.

DEFAULT_SIGMAS = (0.5, 1.0, 2.0, 4.0)

The default filter scales, in pixels of the pixel classification feature grid.

DOG_RATIO = 1.6
INTENSITY_FEATURES = {'intensity_mean': <function mean>, 'intensity_std': <function standard_deviation>, 'intensity_min': <function minimum>, 'intensity_max': <function maximum>}
SHAPE_FEATURES = ('extent', 'equivalent_diameter', 'axis_major_length', 'axis_minor_length', 'eccentricity')
def compute_classical_pixel_features( image: numpy.ndarray, grid_shape: Tuple[int, ...], features: Sequence[str] = ('gaussian_smoothing', 'laplacian_of_gaussian', 'gaussian_gradient_magnitude', 'difference_of_gaussians', 'structure_tensor_eigenvalues', 'hessian_of_gaussian_eigenvalues'), sigmas: Sequence[float] = (0.5, 1.0, 2.0, 4.0)) -> numpy.ndarray:
120def compute_classical_pixel_features(
121    image: np.ndarray,
122    grid_shape: Tuple[int, ...],
123    features: Sequence[str] = PIXEL_FEATURES,
124    sigmas: Sequence[float] = DEFAULT_SIGMAS,
125) -> np.ndarray:
126    """Compute classical filter features on the pixel classification feature grid.
127
128    The image is normalized to [0, 1] per channel and resized to the grid, then the filters are applied
129    per channel, per sigma and, for 3d data, per slice. The result is aligned row-wise with the features
130    of `pixel_classification.compute_pixel_features`.
131
132    Args:
133        image: The image, of shape (H, W) or (Z, H, W), with an optional trailing channel axis.
134        grid_shape: The feature grid shape, (gh, gw) for 2d or (Z, gh, gw) for 3d.
135        features: The classical pixel features to compute, a subset of `PIXEL_FEATURES`.
136        sigmas: The filter scales, in pixels of the feature grid.
137
138    Returns:
139        The per-pixel features, of shape (N, F) flattened over the grid in row-major order.
140    """
141    features = _validate(features, PIXEL_FEATURES, "pixel")
142    image = _to_channels(image, len(grid_shape))
143    if len(grid_shape) == 2:
144        image = image[None]
145        grid_shape = (1,) + tuple(grid_shape)
146    if image.shape[0] != grid_shape[0]:
147        raise ValueError(f"The image has {image.shape[0]} slices, but the feature grid has {grid_shape[0]}.")
148
149    planes = []
150    for z in range(grid_shape[0]):
151        responses = []
152        for c in range(image.shape[-1]):
153            plane = _resize_plane(image[z, ..., c], grid_shape[1:])
154            responses.extend(_filter_plane(plane, features, sigmas))
155        planes.append(np.stack(responses, axis=-1))
156    return np.stack(planes).reshape(-1, planes[0].shape[-1]).astype("float32")

Compute classical filter features on the pixel classification feature grid.

The image is normalized to [0, 1] per channel and resized to the grid, then the filters are applied per channel, per sigma and, for 3d data, per slice. The result is aligned row-wise with the features of pixel_classification.compute_pixel_features.

Arguments:
  • image: The image, of shape (H, W) or (Z, H, W), with an optional trailing channel axis.
  • grid_shape: The feature grid shape, (gh, gw) for 2d or (Z, gh, gw) for 3d.
  • features: The classical pixel features to compute, a subset of PIXEL_FEATURES.
  • sigmas: The filter scales, in pixels of the feature grid.
Returns:

The per-pixel features, of shape (N, F) flattened over the grid in row-major order.

def compute_classical_object_features( image: numpy.ndarray, segmentation: numpy.ndarray, seg_ids: Optional[numpy.ndarray] = None, features: Sequence[str] = ('size', 'intensity_mean', 'intensity_std', 'intensity_min', 'intensity_max', 'extent', 'equivalent_diameter', 'axis_major_length', 'axis_minor_length', 'eccentricity', 'solidity')) -> numpy.ndarray:
159def compute_classical_object_features(
160    image: np.ndarray,
161    segmentation: np.ndarray,
162    seg_ids: Optional[np.ndarray] = None,
163    features: Sequence[str] = OBJECT_FEATURES,
164) -> np.ndarray:
165    """Compute classical morphology and intensity features per object.
166
167    Args:
168        image: The image, with the spatial shape of the segmentation and an optional trailing channel axis.
169        segmentation: The segmentation, of shape (H, W) or (Z, H, W). The background id 0 is ignored.
170        seg_ids: The ids of the objects to compute the features for, e.g. the ids returned by
171            `object_classification.compute_object_features`. By default all objects in the segmentation.
172        features: The classical object features to compute, a subset of `OBJECT_FEATURES`.
173
174    Returns:
175        The object features, of shape (len(seg_ids), F), in the order of `seg_ids`.
176    """
177    features = _validate(features, OBJECT_FEATURES, "object")
178    segmentation = np.asarray(segmentation)
179    if segmentation.dtype not in (np.uint32, np.uint64, np.int32, np.int64):
180        segmentation = segmentation.astype("uint32")
181    image = _to_channels(image, segmentation.ndim)
182    if image.shape[:-1] != segmentation.shape:
183        raise ValueError(f"The image shape {image.shape} does not match the segmentation shape {segmentation.shape}.")
184
185    if seg_ids is None:
186        seg_ids = np.unique(segmentation)
187        seg_ids = seg_ids[seg_ids != 0]
188    seg_ids = np.asarray(seg_ids)
189
190    columns = {}
191    shape_features = [name for name in features if name in SHAPE_FEATURES]
192    if "size" in features or shape_features:
193        table = morphology(segmentation)
194        if "size" in features:
195            columns["size"] = table.set_index("label")["size"]
196        if shape_features:
197            props = regionprops(segmentation, table, num_workers=cpu_count()).set_index("label")
198            major, minor = props["axis_major_length"], props["axis_minor_length"]
199            eccentricity = np.sqrt(1.0 - (minor / major.where(major > 0)) ** 2).fillna(0.0)
200            shape_columns = {
201                "extent": props["extent"], "equivalent_diameter": props["equivalent_diameter_area"],
202                "axis_major_length": major, "axis_minor_length": minor, "eccentricity": eccentricity,
203            }
204            columns.update({name: shape_columns[name] for name in shape_features})
205
206    if "solidity" in features:
207        # Flat or tiny objects have no convex hull, we treat them as fully convex.
208        with warnings.catch_warnings(), np.errstate(divide="ignore", invalid="ignore"):
209            warnings.simplefilter("ignore")
210            props = regionprops_table(segmentation, properties=("label", "solidity"))
211        solidity = np.where(np.isfinite(props["solidity"]), props["solidity"], 1.0)
212        columns["solidity"] = pd.Series(solidity, index=props["label"])
213
214    ordered = {}
215    for name in features:
216        if name in INTENSITY_FEATURES:
217            for c in range(image.shape[-1]):
218                values = INTENSITY_FEATURES[name](image[..., c], labels=segmentation, index=seg_ids)
219                ordered[f"{name}_{c}"] = pd.Series(np.asarray(values), index=seg_ids)
220        else:
221            ordered[name] = columns[name]
222
223    # Objects that are missing from the segmentation get zero features.
224    result = pd.DataFrame(ordered).reindex(seg_ids).fillna(0.0)
225    return result.to_numpy(dtype="float32")

Compute classical morphology and intensity features per object.

Arguments:
  • image: The image, with the spatial shape of the segmentation and an optional trailing channel axis.
  • segmentation: The segmentation, of shape (H, W) or (Z, H, W). The background id 0 is ignored.
  • seg_ids: The ids of the objects to compute the features for, e.g. the ids returned by object_classification.compute_object_features. By default all objects in the segmentation.
  • features: The classical object features to compute, a subset of OBJECT_FEATURES.
Returns:

The object features, of shape (len(seg_ids), F), in the order of seg_ids.