pycroglia.core package

Subpackages

Submodules

class pycroglia.core.arclength.InterpolationMethod(value)[source]

Bases: Enum

Supported interpolation methods for arc length computation.

LINEAR

Straight-line (chordal) distances between successive points. Fastest and simplest, but less accurate for curved data.

PCHIP

Piecewise Cubic Hermite Interpolating Polynomial (PCHIP). Provides smoother parametric curves. Arc length is computed by numerically integrating the curve’s derivative.

SPLINE

Cubic spline interpolation. Produces smooth curves and can give higher accuracy than PCHIP for smooth data, at higher computational cost.

LINEAR = 'linear'
PCHIP = 'pchip'
SPLINE = 'spline'
class pycroglia.core.arclength.Result(arclength, segment_lengths)[source]

Bases: object

Container for arc length results.

Parameters:
arclength

Total arc length of the curve.

Type:

float

segment_lengths

Array of arc lengths for each segment.

Type:

NDArray

arclength: float
segment_lengths: ndarray[tuple[int, ...], dtype[_ScalarType_co]]
pycroglia.core.arclength.arclength(p, method=InterpolationMethod.LINEAR, assert_length=True)[source]

Compute the arc length of a curve represented by discrete points.

This function supports chordal (linear) approximation or smooth interpolation via PCHIP or cubic splines, with numerical integration.

Parameters:
  • p (NDArray) – A 2D array of shape (n_points, n_dims), representing a sequence of points along a curve. Each row is a point in n-dimensional space.

  • method (InterpolationMethod, optional) – Interpolation method for arc length computation. Options: - InterpolationMethod.LINEAR: straight-line distances between points. - InterpolationMethod.PCHIP: smooth PCHIP interpolation with integration. - InterpolationMethod.SPLINE: smooth cubic spline interpolation with integration. Defaults to InterpolationMethod.LINEAR.

  • assert_length (bool, optional) – If True, asserts that all rows of p have the same length (to catch ragged arrays). Defaults to True.

Returns:

Dataclass with fields: - arclength (float): total arc length of the curve. - segment_lengths (NDArray): arc length of each segment.

Return type:

Result

Raises:
  • AssertionError – If input dimensions are invalid or rows of p have inconsistent lengths.

  • ValueError – If no valid interpolation method is provided.

class pycroglia.core.bounding_box.ComputeResult(bounded_img: numpy.ndarray[tuple[int, ...], numpy.dtype[+_ScalarType_co]], right: int, left: int, top: int, bottom: int)[source]

Bases: object

Parameters:
bottom: int
bounded_img: ndarray[tuple[int, ...], dtype[_ScalarType_co]]
left: int
right: int
top: int
pycroglia.core.bounding_box.compute(input_img)[source]

Compute the tight bounding box of a 3D binary image along the X and Y axes.

The function finds the minimum and maximum foreground voxel indices (value == 1 / True) along the Z (rows) and Y (columns) dimensions, crops the input volume accordingly, and keeps the full X (slices) range.

Parameters:

input_img (NDArray) – A 3D boolean or uint8 array with shape (Z, Y, X).

Returns:

A dataclass with the following fields: - bounded_img (NDArray): Cropped sub-volume

[left:right+1, bottom:top+1, :].

  • right (int): Max X index (0-based).

  • left (int): Min X index (0-based).

  • top (int): Max Y index (0-based).

  • bottom (int): Min Y index (0-based).

Return type:

ComputeResult

class pycroglia.core.branch_analysis.BranchAnalysis(cell, centroid, scale, zscale, zslices)[source]

Bases: object

Analyze the morphological properties of 3D skeleton branches.

This class performs quantitative analysis on a 3D skeletonized cell mask, identifying endpoints, branch points, and computing arc lengths for each branch. It replicates the behavior of the MATLAB BranchAnalysis routine, using connected-path reconstruction and distance-based reordering of voxels from endpoints toward the cell centroid.

Parameters:
cell

3D binary mask of the segmented cell volume (Z, Y, X).

Type:

NDArray

centroid

(3,) array with the centroid coordinates (z, y, x) in voxel units.

Type:

NDArray

scale

XY pixel size (µm per voxel).

Type:

float

zscale

Z pixel size (µm per slice).

Type:

float

zslices

Number of Z-slices in the image stack.

Type:

int

compute()[source]

Perform 3D branch analysis on the input cell skeleton.

This method:
  1. Skeletonizes the cell volume using slimskel3d.

  2. Computes a bounding box around the skeleton.

  3. Identifies all endpoints via 3×3×3 convolution.

  4. Connects each endpoint to the centroid using connect_points_along_path (26-connected BFS).

  5. Reorders the resulting voxel list using reorder_pixel_list for spatial continuity.

  6. Calculates each branch’s physical arc length in microns.

  7. Aggregates results to find branch point counts and connectivity classifications (primary to quaternary).

Returns:

A dictionary containing:
  • endpoints (NDArray): 3D boolean mask of detected endpoints.

  • num_branchpoints (int): Number of detected branch points.

  • max_branch_length (float): Maximum branch length (µm).

  • min_branch_length (float): Minimum branch length (µm).

  • avg_branch_length (float): Mean branch length (µm).

  • branch_points (NDArray): (N, 3) array of branch-point coordinates (z, y, x).

Return type:

dict[str, Any]

exception pycroglia.core.branch_analysis.EmptySkeleton[source]

Bases: Exception

Raised when a skeleton or image has no nonzero voxels (i.e., is empty).

pycroglia.core.branch_analysis.get_empty_branch_analysis()[source]
Return type:

dict[str, Any]

pycroglia.core.branch_analysis.init_kernel()[source]

Initialize a 3×3×3 26-connected neighborhood kernel.

This function creates a 3D binary convolution kernel used for neighborhood analysis in volumetric skeletonization and branch detection. The kernel represents a 26-connected neighborhood, where all voxels in a 3×3×3 cube are considered neighbors except the central voxel itself.

Returns:

A 3×3×3 NumPy array of type int32 with ones in all positions except the center, which is zero.

Return type:

NDArray

class pycroglia.core.centroid.Centroids(masks, scale, zscale)[source]

Bases: object

Compute centroids of 3D cell masks and their mean spatial separation.

This class extracts the geometric centroids of multiple 3D binary masks, representing individual segmented cells, and computes the average pairwise Euclidean distance between all centroids in physical units (micrometers).

The computation accounts for anisotropic voxel scaling along the Z and XY axes, allowing accurate physical distance measurements in microscopy data.

Parameters:
centroids

Array of shape (N, 3) containing the centroids of non-empty masks, where each row represents a centroid in (z, y, x) voxel coordinates.

Type:

NDArray[np.float64]

scale

Pixel size in the XY plane, expressed in micrometers per voxel.

Type:

float

zscale

Z-step size (slice spacing) in micrometers per voxel.

Type:

float

compute()[source]

Compute the mean pairwise centroid distance in micrometers.

The method scales voxel coordinates to physical space using the provided pixel and z-step sizes, then computes all pairwise Euclidean distances between centroids and reports the mean.

Returns:

Dictionary containing:
  • average_distance (float): Mean pairwise distance between all centroids, expressed in micrometers.

Return type:

dict[str, Any]

Raises:

ValueError – If fewer than two centroids are available to compute distances.

pycroglia.core.clustering.gaussian_mixture_predict(img, n_clusters, n_init)[source]

Applies a Gaussian Mixture Model (GMM) to segment a 3D binary image into clusters.

Parameters:
  • img (NDArray) – 3D binary image.

  • n_clusters (int) – Number of clusters to segment.

  • n_init (int) – Number of initializations for the GMM.

Returns:

List of 3D binary masks, one for each cluster.

Return type:

list[NDArray[np.uint8]]

pycroglia.core.clustering.get_number_of_nuclei(img, connectivity)[source]

Gets the number of nuclei in a 3D binary image using SkimageImgLabeling strategy.

This function uses the SkimageImgLabeling strategy to label connected components according to the specified connectivity.

Parameters:
Returns:

Number of detected nuclei (returns 2 if only one nucleus is found).

Return type:

int

Raises:

PycrogliaException – If no nuclei are detected (error_code=2001).

class pycroglia.core.connection.Point(x, y, z)[source]

Bases: object

A 3D voxel coordinate in (x, y, z).

Parameters:
x: int
y: int
z: int
pycroglia.core.connection.connect_points_along_path(img, start, end)[source]

Compute the shortest 3D path connecting two voxels within a binary skeleton mask.

This function performs a two-front breadth-first search (BFS) expansion from both start and end voxels simultaneously through a 3D binary volume. Expansion proceeds only through foreground voxels (True), and stops once both fronts meet, marking all voxels that belong to the minimal connecting region.

The method mirrors MATLAB’s ConnectPointsAlongPath behavior: it iteratively dilates both fronts (start and end) through a 26-connected neighborhood until they overlap, at which point the minimal connecting path is extracted.

Parameters:
  • img (NDArray) – 3D binary array of shape (Z, Y, X). Foreground voxels (path-eligible) must have value True.

  • start (Point) – Starting voxel coordinates as (x, y, z). Must lie inside the foreground.

  • end (Point) – Ending voxel coordinates as (x, y, z). Must lie inside the foreground.

Returns:

A 3D binary mask of the same shape as img, where 1 (True) marks voxels belonging to the shortest connection between start and end. If no connection exists, raises a ValueError.

Return type:

NDArray

Raises:

ValueError – If no continuous path of foreground voxels connects start and end.

class pycroglia.core.enums.SkimageCellConnectivity(value)[source]

Bases: Enum

Defines connectivity options for labeling connected cell components in 3D images.

FACES

6-connectivity (voxels connected by faces).

Type:

int

EDGES

18-connectivity (voxels connected by faces and edges).

Type:

int

CORNERS

26-connectivity (voxels connected by faces, edges, and corners).

Type:

int

CORNERS = 3
EDGES = 2
FACES = 1
class pycroglia.core.erosion.Ball3DFootprint(r)[source]

Bases: FootprintShape

Ball-shaped structuring element in 3D.

Parameters:

r (int)

get_shape()[source]

Returns the ball-shaped structuring element.

Returns:

Structuring element.

Return type:

tuple

class pycroglia.core.erosion.Diamond2DFootprint(r)[source]

Bases: FootprintShape

Diamond-shaped structuring element.

Parameters:

r (int)

get_shape()[source]

Returns the diamond-shaped structuring element.

Returns:

Structuring element.

Return type:

tuple

class pycroglia.core.erosion.Disk2DFootprint(r)[source]

Bases: FootprintShape

Disk-shaped structuring element.

Parameters:

r (int)

get_shape()[source]

Returns the disk-shaped structuring element.

Returns:

Structuring element.

Return type:

tuple

class pycroglia.core.erosion.FootprintShape[source]

Bases: ABC

Abstract base class for structuring element shapes.

abstract get_shape()[source]

Returns the structuring element shape.

Returns:

Structuring element for morphological operations.

Return type:

tuple

class pycroglia.core.erosion.Octahedron3DFootprint(r)[source]

Bases: FootprintShape

Octahedron-shaped structuring element in 3D.

Parameters:

r (int)

get_shape()[source]

Returns the octahedron-shaped structuring element.

Returns:

Structuring element.

Return type:

tuple

class pycroglia.core.erosion.Rectangle2DFootprint(x, y)[source]

Bases: FootprintShape

Rectangle-shaped structuring element.

Parameters:
get_shape()[source]

Returns the rectangle-shaped structuring element.

Returns:

Structuring element.

Return type:

tuple

class pycroglia.core.erosion.Rectangle3DFootprint(x, y, z)[source]

Bases: FootprintShape

3D rectangular structuring element for binary erosion.

Parameters:
  • x (int) – Size along the x-axis.

  • y (int) – Size along the y-axis.

  • z (int) – Size along the z-axis.

x

Size along the x-axis.

Type:

int

y

Size along the y-axis.

Type:

int

z

Size along the z-axis.

Type:

int

get_shape()[source]

Returns a 3D rectangular footprint.

Returns:

3D array of ones with shape (z*2+1, y*2+1, x*2+1).

Return type:

NDArray

pycroglia.core.erosion.apply_binary_erosion(img, footprint)[source]

Applies binary erosion to an image using the given structuring element.

Parameters:
  • img (NDArray) – Binary image.

  • footprint (FootprintShape) – Structuring element.

Returns:

Eroded image.

Return type:

NDArray

pycroglia.core.filters.calculate_otsu_threshold(img, adjust)[source]

Calculates a binary mask for each slice of a 3D image using Otsu’s method and a threshold adjustment factor.

Parameters:
  • img (NDArray) – 3D image array with shape (zs, height, width), where zs is the number of slices.

  • adjust (float) – Adjustment factor to modify the threshold computed by Otsu’s method.

Returns:

Boolean 3D array (same shape as input) representing the binary thresholded mask.

Return type:

NDArray

pycroglia.core.filters.remove_small_objects(img, min_size, connectivity=SkimageCellConnectivity.EDGES)[source]

Removes connected components smaller than a given size from a 3D binary mask.

Parameters:
  • img (NDArray) – 3D binary array (dtype=bool or uint8) with shape (zs, height, width).

  • min_size (int) – Minimum number of pixels required to keep a component.

  • connectivity (SkimageCellConnectivity) – Connectivity used by skimage (4 or 8). Defaults to SkimageCellConnectivity.EDGES.

Returns:

3D binary array with small objects removed.

Return type:

NDArray

class pycroglia.core.full_cell_analysis.FullCellAnalysis(masks, voxscale)[source]

Bases: object

Compute convex hulls, volumes, and complexity metrics for segmented cells.

Given a list of 3D binary masks (segmented cells), this class computes:

  1. Raw voxel-based cell volume (scaled to physical units by voxscale).

  2. Convex hull of voxel coordinates and its volume.

  3. Cell complexity: ratio of convex hull volume to cell volume.

  4. Maximum cell volume across all masks.

  5. Convex hull vertices and simplices for visualization.

Parameters:
masks

List of 3D binary arrays where True or 1 indicates cell voxels.

Type:

list[np.ndarray]

voxscale

Scaling factor to convert voxel counts/volumes into physical units (e.g., µm³ per voxel).

Type:

float

compute()[source]

Perform convex hull and complexity analysis for all cells.

For each cell:
  • Counts voxels and converts to volume using voxscale.

  • Builds a convex hull from voxel coordinates.

  • Computes convex hull volume and stores vertices/simplices.

  • Computes complexity as convex_volume / cell_volume.

Returns:

Dict containing convex hulls, volumes, complexities, cell volumes and maximum cell volume.

Return type:

Dict[str, Any]

class pycroglia.core.labeled_cells.LabeledCells(img, labeling_strategy)[source]

Bases: object

Represents labeled connected cell components in a 3D image.

Provides methods to access individual cells, their sizes, and 2D projections.

Parameters:
ARRAY_ELEMENTS_TYPE

Data type for output arrays.

Type:

type

z

Depth of the image.

Type:

int

y

Height of the image.

Type:

int

x

Width of the image.

Type:

int

labels

Labeled 3D array.

Type:

NDArray

ARRAY_ELEMENTS_TYPE

alias of uint8

all_cells_to_2d()[source]

Projects all labeled cells to 2D and stacks them along a new axis.

Returns:

3D array where each slice is the 2D projection of a cell.

Return type:

NDArray

cell_to_2d(index)[source]

Projects a 3D cell to 2D by summing along the z-axis.

Parameters:

index (int) – Cell label index.

Returns:

2D projection of the cell.

Return type:

NDArray

Raises:

PycrogliaException – If the index is invalid (error_code=2000).

get_border_cells()[source]

Detects cells that touch the image borders in any Z slice.

Identifies cells whose labels appear on any edge of the 3D image volume. A cell is considered a border cell if any of its voxels touch the top, bottom, left, or right edges of any Z slice.

Returns:

Set of cell IDs that touch the image borders.

Return type:

Set[int]

get_cell(index)[source]

Returns a binary mask for the specified cell.

Parameters:

index (int) – Cell label index.

Returns:

3D binary mask for the cell.

Return type:

NDArray

Raises:

PycrogliaException – If the index is invalid (error_code=2000).

get_cell_size(index)[source]

Returns the size (number of voxels) of the specified cell.

Parameters:

index (int) – Cell label index.

Returns:

Number of voxels in the cell.

Return type:

int

Raises:

PycrogliaException – If the index is invalid (error_code=2000).

get_cells_list()[source]
Return type:

list[ndarray[tuple[int, …], dtype[_ScalarType_co]]]

labels_to_2d()[source]

Projects the labeled 3D array to 2D by taking the maximum label along the z-axis.

Returns:

2D array with the maximum label for each (y, x) position.

Return type:

NDArray

len()[source]

Returns the number of labeled cells.

Returns:

Number of labeled cells (excluding background).

Return type:

int

selected_cells_mask(selected_ids)[source]

Return a combined 3D binary mask for the provided cell IDs.

Performs a vectorized single-pass operation using np.isin over the internal labels array to build the combined mask.

Parameters:

selected_ids (Set[int]) – Set of cell label IDs to include.

Returns:

3D binary mask (z, y, x) with 1 where any of the selected cells are present.

Return type:

NDArray

class pycroglia.core.labeled_cells.LabelingStrategy[source]

Bases: ABC

Abstract base class for labeling strategies.

Subclasses must implement the label method to generate labeled arrays from input images.

ARRAY_ELEMENTS_TYPE

Data type for output arrays.

Type:

type

ARRAY_ELEMENTS_TYPE

alias of uint8

abstract label(img)[source]

Labels the input image according to the strategy.

Parameters:

img (NDArray) – Input image to label.

Returns:

Labeled array.

Return type:

NDArray

class pycroglia.core.labeled_cells.MaskListLabeling(masks)[source]

Bases: LabelingStrategy

Labeling strategy using a list of binary masks.

Each mask should have the same shape as the target image.

Parameters:

masks (list[ndarray[tuple[int, ...], dtype[_ScalarType_co]]])

label(img)[source]
Parameters:

img (NDArray) – Reference image to determine output shape.

Returns:

Labeled array.

Return type:

NDArray

class pycroglia.core.labeled_cells.SkimageImgLabeling(connectivity)[source]

Bases: LabelingStrategy

Labeling strategy using skimage.measure.label.

Parameters:

connectivity (SkimageCellConnectivity)

connectivity

Connectivity rule for labeling.

Type:

pycroglia.core.enums.SkimageCellConnectivity

label(img)[source]

Labels the input image using skimage.measure.label.

Parameters:

img (NDArray) – Input image to label.

Returns:

Labeled array.

Return type:

NDArray

class pycroglia.core.nearest_pixel.Coordinates(x, y, z)[source]

Bases: object

Container for 3D voxel coordinates.

Parameters:
x: int
y: int
z: int
pycroglia.core.nearest_pixel.compute(img, starting_pixel, scale)[source]

Find the nearest foreground voxel (value=1) in a 3D binary image.

Parameters:
  • img (NDArray) – 3D binary image of shape (z, y, x). Foreground voxels are 1 or True.

  • starting_pixel (tuple[int,int,int]) – Starting voxel coordinates in (z, y, x) order.

  • scale (float) – Anisotropy scaling factor applied equally to the z and y distances (mimicking the MATLAB implementation).

Returns:

Dataclass containing (x, y, z) of the closest foreground voxel.

Return type:

Coordinates

Raises:

ValueError – If the image contains no foreground voxels.

pycroglia.core.reorder.reorder_pixel_list(pixel_indices, shape, endpoint, centroid)[source]

Order the voxels of a 3D branch mask from the endpoint toward the centroid.

This function takes a list of flattened voxel indices belonging to a single 3D branch (a connected set of True voxels) and reconstructs an ordered path from a known endpoint toward a given centroid. The ordering is computed by iteratively selecting the nearest unvisited voxel to the current one, ensuring spatial continuity along the branch.

The resulting list starts with the endpoint voxel and progresses through adjacent voxels until reaching (or approximating) the centroid region.

Parameters:
  • pixel_indices (NDArray) – 1D array of flattened voxel indices (0-based) representing the branch.

  • shape (tuple[int, int, int]) – Shape of the 3D binary mask (Z, Y, X) from which the indices were drawn.

  • endpoint (NDArray) – Array of shape (3,) giving the endpoint coordinates (z, y, x). Must be one of the voxels in the branch.

  • centroid (NDArray) – Array of shape (3,) giving the centroid coordinates (z, y, x) used as the stopping target for ordering.

Returns:

Array of shape (N, 3) containing voxel coordinates ordered by connectivity from endpoint to centroid. The first row equals endpoint, and the last row corresponds to the voxel nearest to centroid.

Return type:

NDArray

Raises:

AssertionError – If input shapes are invalid, or if the endpoint voxel is not present in the given branch.

class pycroglia.core.segmentation.SegmentationConfig(cut_off_size, min_size, connectivity, min_nucleus_fraction=50, gmm_n_init=3)[source]

Bases: object

Configuration for cell segmentation.

Parameters:
DEFAULT_MIN_NUCLEUS_FRACTION

Default minimum nucleus fraction.

Type:

int

DEFAULT_GMM_N_INIT

Default number of GMM initializations.

Type:

int

cut_off_size

Minimum size for a cell to be segmented.

Type:

int

min_size

Minimum size for objects to keep after noise removal.

Type:

int

connectivity

Connectivity rule for labeling.

Type:

SkimageCellConnectivity

min_nucleus_fraction

Minimum nucleus fraction for erosion.

Type:

int

gmm_n_init

Number of initializations for Gaussian Mixture Model.

Type:

int

DEFAULT_GMM_N_INIT: ClassVar[int] = 3
DEFAULT_MIN_NUCLEUS_FRACTION: ClassVar[int] = 50
connectivity: SkimageCellConnectivity
cut_off_size: int
gmm_n_init: int = 3
min_nucleus_fraction: int = 50
min_size: int
pycroglia.core.segmentation.segment_cell(cells, footprint, config)[source]

Segments cells using erosion, clustering, and noise removal.

For each cell, if its size is above the cut_off_size, the function applies binary erosion, removes small objects, estimates the number of nuclei, and applies Gaussian Mixture Model clustering. Each resulting cluster is filtered for noise and relabeled. Small cells are returned as is.

Parameters:
Returns:

List of segmented cell masks as 3D arrays.

Return type:

List[NDArray]

pycroglia.core.segmentation.segment_single_cell(cell_matrix, footprint, config)[source]

Segments a single cell mask using erosion, clustering, and noise removal.

If the cell size is above the cut_off_size, applies binary erosion, removes small objects, estimates the number of nuclei, and applies Gaussian Mixture Model clustering. Each resulting cluster is filtered for noise and relabeled. Small cells are returned as is.

Parameters:
  • cell_matrix (NDArray) – 3D binary mask of a single cell.

  • footprint (FootprintShape) – Structuring element for erosion.

  • config (SegmentationConfig) – Configuration parameters for segmentation.

Returns:

List of segmented cell masks as 3D arrays.

Return type:

List[NDArray]

class pycroglia.core.territorial_volume.TerritorialVolume(masks, voxscale, zplanes)[source]

Bases: object

Compute convex hull volumes for segmented 3D cells.

This class takes a list of binary masks, where each mask corresponds to a segmented cell within a 3D image. For each mask, it extracts voxel coordinates, computes the convex hull enclosing those voxels, and returns the hull volume scaled into physical units.

Parameters:
masks

List of 3D boolean arrays. Each array represents the voxel mask of one segmented cell. All masks must share the same shape corresponding to the original image volume.

Type:

list[np.ndarray]

voxscale

Scaling factor for converting voxel-based volumes into physical units (e.g., µm³ per voxel).

Type:

float

compute()[source]

Computes convex hull volumes for all segmented cells.

For each mask:
  1. Extract voxel coordinates using np.argwhere. - Returns indices in (z, y, x) order.

  2. Convert coordinates to float64 for numerical stability.

  3. Construct a convex hull enclosing the voxel cloud with scipy.spatial.ConvexHull.

  4. Multiply the hull volume by voxscale to convert into physical volume.

Returns:

A 1D array of shape (n_cells,) containing the convex hull volume (float64) of each cell in physical units.

Return type:

np.ndarray

Module contents