sparrow.utils.RasterAggregator#
- class sparrow.utils.RasterAggregator(mask_dask_array, image_dask_array)#
Helper class to calulate aggregated ‘sum’, ‘mean’, ‘var’, ‘kurtosis’, ‘skew’, ‘area’, ‘min’, ‘max’ ‘quantiles’, ‘center of mass’, ‘radii’ or ‘principal_axes’ of image and labels using Dask.
- Parameters:
mask_dask_array (
Array) – A 3D Dask array of integer labels representing segmented regions. Expected shape is (‘z’, ‘y’, ‘x’). Each unique integer value represents a separate label.image_dask_array (
Array|None) – A 4D Dask array representing the image data with shape (‘c’, ‘z’, ‘y’, ‘x’), where ‘c’ is the number of channels. Can beNoneif only mask-based computations (e.g., count or center of mass) are required.
- Raises:
ValueError – If
mask_dask_arraydoes not contain an integer dtype.AssertionError – If
mask_dask_arrayis not 3D.AssertionError – If
image_dask_arrayis provided but is not 4D.AssertionError – If spatial dimensions of
image_dask_arrayandmask_dask_arraydo not match.AssertionError – If chunk sizes of spatial dimensions do not match between image and mask.
Notes
Unique labels are computed once at initialization for efficiency.
Image and mask must be aligned in spatial dimensions and chunking to ensure accurate and efficient aggregation.
Methods table#
Computes the area (number of pixels) for each labeled region in the mask. |
|
|
Aggregates a custom operation over a masked region of an image, with the option to pass additional parameters to a custom function. |
Computes the kurtosis of pixel values within each labeled region for all image channels. |
|
Computes the maximum pixel value within each labeled region for all image channels. |
|
Computes the mean of pixel values within each labeled region for all image channels. |
|
Computes the minimum pixel value within each labeled region for all image channels. |
|
|
Computes quantiles of pixel values for each label in the mask, across all channels. |
|
Computes and aggregates radii and principal axes for segmented regions in the mask. |
Computes the skewness of pixel values within each labeled region for all image channels. |
|
|
Computes multiple statistical metrics for each label in the mask, across all image channels. |
Computes the sum of pixel values within each labeled region for all image channels. |
|
Computes the variance of pixel values within each labeled region for all image channels. |
|
Computes the center of mass for each labeled region in the mask. |
Methods#
- RasterAggregator.aggregate_area()#
Computes the area (number of pixels) for each labeled region in the mask.
- Return type:
DataFrame- Returns:
: A DataFrame with one column for area and one for label ID.
- RasterAggregator.aggregate_custom_channel(image, mask, depth, fn, fn_kwargs=mappingproxy({}), dtype=<class 'numpy.float32'>, features=1)#
Aggregates a custom operation over a masked region of an image, with the option to pass additional parameters to a custom function.
- Parameters:
image (
Array|None) – The input image array. If None, the function will only process themask. The array is expected to be a dask array. If not None, the function will apply the operation to the image based on the mask regions.mask (
Array) – A dask array representing the mask. Each unique non-zero value in the mask identifies a separate region of interest (ROI), typically a cell. The mask array must have integer values corresponding to different cells in the image.depth (
int) – depth is passed asdepthtodask.array.map_overlap, wheredepthmust be greater than the estimated diameter of the largest region of interest in themask. This value ensures the appropriate neighborhood is considered when applying the functionfn.fn (
Callable[[ndarray[Any,dtype[int64]],ndarray[Any,dtype[int64|float64]] |None],ndarray[Any,dtype[float64]]]) –A custom function that processes a mask and, optionally, an image array. The function must accept either one or two NumPy arrays:
The first argument is the mask, provided as an integer array.
The second argument (optional) is the image, given as a float or integer array.
The function must return a 2D NumPy array of type
np.float, where:The first dimension corresponds to the number of unique labels in the mask (excluding label
0), sorted by label number.The second dimension represents the number of features computed by
fn.
The output of
fnmust not containNaNvalues. User warning: the number of unique labels in the mask passed tofnis not equal to the number of unique labels from the globalmaskdue to the use ofdask.array.map_overlap.fn_kwargs (
Mapping[str,Any] (default:mappingproxy({}))) – Additional keyword arguments to be passed to the functionfn. The default is an emptyMappingProxyType.dtype (
dtype(default:<class 'numpy.float32'>)) – The data type of the output array. By default, this isnp.float32. It can be changed to any valid NumPy data type if necessary.features (
int(default:1)) – The number of featuresfncalculates.
- Return type:
ndarray[Any,dtype[TypeVar(_ScalarType_co, bound=generic, covariant=True)]]- Returns:
: A 2D NumPy array containing the aggregated results of the custom operation
fn, applied to the regions defined by themask. The array has the same number of elements as the unique labels in themaskexcluding0, and the results are ordered based on the ordered labels. The shape of the 2D Numpy array is thus (len( self._labels[[self._labels!=0]]), features), withself._labels = dask.array.unique( mask ).compute().
- RasterAggregator.aggregate_kurtosis()#
Computes the kurtosis of pixel values within each labeled region for all image channels.
- Return type:
DataFrame- Returns:
: DataFrame where rows represent labels and columns represent channels.
- RasterAggregator.aggregate_max()#
Computes the maximum pixel value within each labeled region for all image channels.
- Return type:
DataFrame- Returns:
: DataFrame where rows represent labels and columns represent channels.
- RasterAggregator.aggregate_mean()#
Computes the mean of pixel values within each labeled region for all image channels.
- Return type:
DataFrame- Returns:
: DataFrame where rows represent labels and columns represent channels.
- RasterAggregator.aggregate_min()#
Computes the minimum pixel value within each labeled region for all image channels.
- Return type:
DataFrame- Returns:
: DataFrame where rows represent labels and columns represent channels.
- RasterAggregator.aggregate_quantiles(depth, quantiles=None, quantile_background=False)#
Computes quantiles of pixel values for each label in the mask, across all channels.
- Parameters:
depth (
int) – Depth to apply during Dask’smap_overlapoperation. Set depth > estimated diameter of labels.quantiles (
list[float] |ndarray[Any,dtype[TypeVar(_ScalarType_co, bound=generic, covariant=True)]] |None(default:None)) – List of quantile values to compute (between 0 and 1). Defaults to [0.1, …, 0.9].quantile_background (
bool(default:False)) – Whether to include background label (0) in computation. Defaults to False.
- Return type:
list[DataFrame]- Returns:
: List of DataFrames, one per quantile, with rows as labels and columns as channels.
- RasterAggregator.aggregate_radii_and_axes(depth, calculate_axes=True)#
Computes and aggregates radii and principal axes for segmented regions in the mask.
This method returns a pandas DataFrame where each row represents a segmented cell. The DataFrame includes a column for the cell ID, three columns for the radii (sorted from largest to smallest), and optionally, nine columns (3*3) for the principal axes.
- Parameters:
depth (
int) – The depth at which the aggregation is performed, passed todask.array.map_overlap. Please setdepth> expected diameter of the labels.calculate_axes (
bool(default:True)) – If True, the DataFrame will include the principal axes (default is True).
- Return type:
DataFrame- Returns:
: A DataFrame where: - Each row corresponds to a segmented cell, sorted by cell ID. - The next three columns contain the radii (sorted from highest to lowest). - If
calculate_axesis True, the next nine columns contain the corresponding principal axes (flattened 3*3 matrix). - One column contains the cell ID.
- RasterAggregator.aggregate_skew()#
Computes the skewness of pixel values within each labeled region for all image channels.
- Return type:
DataFrame- Returns:
: DataFrame where rows represent labels and columns represent channels.
- RasterAggregator.aggregate_stats(stats_funcs=('sum', 'mean', 'count', 'var', 'kurtosis', 'skew'))#
Computes multiple statistical metrics for each label in the mask, across all image channels.
- Parameters:
stats_funcs (
tuple[str,...] (default:('sum', 'mean', 'count', 'var', 'kurtosis', 'skew'))) – A tuple of statistical functions to apply. Supported values include: “sum”, “mean”, “count”, “var”, “kurtosis”, and “skew”. Defaults to all.- Return type:
list[DataFrame]- Returns:
: A list of DataFrames, each corresponding to one of the requested statistics. Each DataFrame contains one row per label a column per image channel and a column with the label ID, except for stat “count”, which only contains a column with the counts and a column with the label ID.
- RasterAggregator.aggregate_sum()#
Computes the sum of pixel values within each labeled region for all image channels.
- Return type:
DataFrame- Returns:
: DataFrame where rows represent labels and columns represent channels.
- RasterAggregator.aggregate_var()#
Computes the variance of pixel values within each labeled region for all image channels.
- Return type:
DataFrame- Returns:
: DataFrame where rows represent labels and columns represent channels.
- RasterAggregator.center_of_mass()#
Computes the center of mass for each labeled region in the mask.
Note that we use scipy.ndimage.center_of_mass, which loads the mask into memory.
- Return type:
DataFrame- Returns:
: A DataFrame with columns for spatial coordinates (z,y,x) and label ID.