pycroglia.core package
Subpackages
- pycroglia.core.compute package
- pycroglia.core.errors package
- pycroglia.core.io package
- Subpackages
- Submodules
AnalysisSummaryAnalysisSummary.fileAnalysisSummary.avg_centroid_distanceAnalysisSummary.total_territorial_volumeAnalysisSummary.total_unoccupied_volumeAnalysisSummary.percent_occupied_volumeAnalysisSummary.avg_centroid_distanceAnalysisSummary.fileAnalysisSummary.percent_occupied_volumeAnalysisSummary.total_territorial_volumeAnalysisSummary.total_unoccupied_volume
AnalysisSummaryConfigAnalysisSummaryConfig.file_txtAnalysisSummaryConfig.avg_centroid_distance_txtAnalysisSummaryConfig.total_territorial_volume_txtAnalysisSummaryConfig.total_unoccupied_volume_txtAnalysisSummaryConfig.percent_occupied_volume_txtAnalysisSummaryConfig.avg_centroid_distance_txtAnalysisSummaryConfig.default()AnalysisSummaryConfig.file_txtAnalysisSummaryConfig.percent_occupied_volume_txtAnalysisSummaryConfig.total_territorial_volume_txtAnalysisSummaryConfig.total_unoccupied_volume_txt
CellAnalysisCellAnalysis.cell_territory_volumeCellAnalysis.cell_volumeCellAnalysis.ramification_indexCellAnalysis.number_of_endpointsCellAnalysis.number_of_branchesCellAnalysis.avg_branch_lengthCellAnalysis.max_branch_lengthCellAnalysis.min_branch_lengthCellAnalysis.avg_branch_lengthCellAnalysis.branch_analysisCellAnalysis.cell_territory_volumeCellAnalysis.cell_volumeCellAnalysis.full_cell_analysisCellAnalysis.max_branch_lengthCellAnalysis.min_branch_lengthCellAnalysis.number_of_branchesCellAnalysis.number_of_endpointsCellAnalysis.ramification_index
CellAnalysisConfigCellAnalysisConfig.cell_territory_volume_txtCellAnalysisConfig.cell_volume_txtCellAnalysisConfig.ramification_index_txtCellAnalysisConfig.number_of_endpoints_txtCellAnalysisConfig.number_of_branches_txtCellAnalysisConfig.avg_branch_length_txtCellAnalysisConfig.max_branch_length_txtCellAnalysisConfig.min_branch_length_txtCellAnalysisConfig.avg_branch_length_txtCellAnalysisConfig.cell_territory_volume_txtCellAnalysisConfig.cell_volume_txtCellAnalysisConfig.default()CellAnalysisConfig.max_branch_length_txtCellAnalysisConfig.min_branch_length_txtCellAnalysisConfig.number_of_branches_txtCellAnalysisConfig.number_of_endpoints_txtCellAnalysisConfig.ramification_index_txt
ExcelOutputFullAnalysisJSONOutputOutputWriterLsmReaderMultiChReaderTiffReadercreate_channeled_reader()
- Module contents
- pycroglia.core.plot package
- pycroglia.core.skeletonize package
- pycroglia.core.slimskel3d package
- pycroglia.core.tests package
Submodules
- class pycroglia.core.arclength.InterpolationMethod(value)[source]
Bases:
EnumSupported 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:
objectContainer for arc length results.
- segment_lengths
Array of arc lengths for each segment.
- Type:
NDArray
- 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:
- 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:
- 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:
- class pycroglia.core.branch_analysis.BranchAnalysis(cell, centroid, scale, zscale, zslices)[source]
Bases:
objectAnalyze 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
- compute()[source]
Perform 3D branch analysis on the input cell skeleton.
- This method:
Skeletonizes the cell volume using slimskel3d.
Computes a bounding box around the skeleton.
Identifies all endpoints via 3×3×3 convolution.
Connects each endpoint to the centroid using connect_points_along_path (26-connected BFS).
Reorders the resulting voxel list using reorder_pixel_list for spatial continuity.
Calculates each branch’s physical arc length in microns.
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:
- exception pycroglia.core.branch_analysis.EmptySkeleton[source]
Bases:
ExceptionRaised when a skeleton or image has no nonzero voxels (i.e., is empty).
- 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
int32with ones in all positions except the center, which is zero.- Return type:
NDArray
- class pycroglia.core.centroid.Centroids(masks, scale, zscale)[source]
Bases:
objectCompute 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]
- 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:
- 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.
- 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:
img (NDArray) – 3D binary image.
connectivity (SkimageCellConnectivity) – Connectivity type for labeling.
- Returns:
Number of detected nuclei (returns 2 if only one nucleus is found).
- Return type:
- Raises:
PycrogliaException – If no nuclei are detected (error_code=2001).
- class pycroglia.core.connection.Point(x, y, z)[source]
Bases:
objectA 3D voxel coordinate in (x, y, z).
- 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:
- 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:
EnumDefines connectivity options for labeling connected cell components in 3D images.
- CORNERS = 3
- EDGES = 2
- FACES = 1
- class pycroglia.core.erosion.Ball3DFootprint(r)[source]
Bases:
FootprintShapeBall-shaped structuring element in 3D.
- Parameters:
r (int)
- class pycroglia.core.erosion.Diamond2DFootprint(r)[source]
Bases:
FootprintShapeDiamond-shaped structuring element.
- Parameters:
r (int)
- class pycroglia.core.erosion.Disk2DFootprint(r)[source]
Bases:
FootprintShapeDisk-shaped structuring element.
- Parameters:
r (int)
- class pycroglia.core.erosion.FootprintShape[source]
Bases:
ABCAbstract base class for structuring element shapes.
- class pycroglia.core.erosion.Octahedron3DFootprint(r)[source]
Bases:
FootprintShapeOctahedron-shaped structuring element in 3D.
- Parameters:
r (int)
- class pycroglia.core.erosion.Rectangle2DFootprint(x, y)[source]
Bases:
FootprintShapeRectangle-shaped structuring element.
- class pycroglia.core.erosion.Rectangle3DFootprint(x, y, z)[source]
Bases:
FootprintShape3D rectangular structuring element for binary erosion.
- Parameters:
- 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:
objectCompute convex hulls, volumes, and complexity metrics for segmented cells.
Given a list of 3D binary masks (segmented cells), this class computes:
Raw voxel-based cell volume (scaled to physical units by
voxscale).Convex hull of voxel coordinates and its volume.
Cell complexity: ratio of convex hull volume to cell volume.
Maximum cell volume across all masks.
Convex hull vertices and simplices for visualization.
- voxscale
Scaling factor to convert voxel counts/volumes into physical units (e.g., µm³ per voxel).
- Type:
- 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:
objectRepresents labeled connected cell components in a 3D image.
Provides methods to access individual cells, their sizes, and 2D projections.
- Parameters:
labeling_strategy (LabelingStrategy)
- 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:
- Raises:
PycrogliaException – If the index is invalid (error_code=2000).
- 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:
- 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:
ABCAbstract base class for labeling strategies.
Subclasses must implement the label method to generate labeled arrays from input images.
- ARRAY_ELEMENTS_TYPE
alias of
uint8
- class pycroglia.core.labeled_cells.MaskListLabeling(masks)[source]
Bases:
LabelingStrategyLabeling strategy using a list of binary masks.
Each mask should have the same shape as the target image.
- class pycroglia.core.labeled_cells.SkimageImgLabeling(connectivity)[source]
Bases:
LabelingStrategyLabeling strategy using skimage.measure.label.
- Parameters:
connectivity (SkimageCellConnectivity)
- connectivity
Connectivity rule for labeling.
- class pycroglia.core.nearest_pixel.Coordinates(x, y, z)[source]
Bases:
objectContainer for 3D voxel coordinates.
- pycroglia.core.nearest_pixel.compute(img, starting_pixel, scale)[source]
Find the nearest foreground voxel (value=1) in a 3D binary image.
- Parameters:
- Returns:
Dataclass containing (x, y, z) of the closest foreground voxel.
- Return type:
- 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:
objectConfiguration for cell segmentation.
- Parameters:
cut_off_size (int)
min_size (int)
connectivity (SkimageCellConnectivity)
min_nucleus_fraction (int)
gmm_n_init (int)
- connectivity
Connectivity rule for labeling.
- Type:
- connectivity: SkimageCellConnectivity
- 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:
cells (LabeledCells) – LabeledCells object containing labeled cell regions.
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]
- 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:
objectCompute 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:
- compute()[source]
Computes convex hull volumes for all segmented cells.
- For each mask:
Extract voxel coordinates using np.argwhere. - Returns indices in (z, y, x) order.
Convert coordinates to float64 for numerical stability.
Construct a convex hull enclosing the voxel cloud with scipy.spatial.ConvexHull.
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