gridgene.get_masks module#
- class gridgene.get_masks.GetMasks(logger=None, image_shape=None)[source]#
Bases:
objectClass to handle mask processing operations such as filtering, creation, morphology, subtraction, saving, and plotting.
- Parameters:
logger (logging.Logger, optional) – Logger instance for logging messages. If None, a default logger is configured.
image_shape (tuple of int, optional) – Tuple representing the shape of the image (height, width).
- filter_binary_mask_by_area(mask, min_area)[source]#
Remove small connected components from a binary mask.
- Parameters:
mask (np.ndarray) – Binary mask (0 or 1).
min_area (int) – Minimum area threshold.
- Returns:
Filtered binary mask.
- Return type:
np.ndarray
- filter_labeled_mask_by_area(mask, min_area)[source]#
Filter a labeled mask by keeping only components with area >= min_area.
- Parameters:
mask (np.ndarray) – Input labeled mask (integer labels).
min_area (int) – Minimum area threshold.
- Returns:
Filtered labeled mask preserving label IDs.
- Return type:
np.ndarray
- create_mask(contours)[source]#
Create a binary mask from contours.
- Parameters:
contours (list of np.ndarray) – List of contours.
- Returns:
Binary mask.
- Return type:
np.ndarray
- Raises:
ValueError – If image shape is not defined.
- fill_holes(mask)[source]#
Fill holes inside a binary mask.
- Parameters:
mask (np.ndarray) – Binary mask.
- Returns:
Hole-filled binary mask.
- Return type:
np.ndarray
- apply_morphology(mask, operation='open', kernel_size=3)[source]#
Apply morphological operations to a binary mask.
- Parameters:
mask (np.ndarray) – Binary mask to process.
operation (str, optional) – Morphological operation: “open”, “close”, “erode”, or “dilate” (default is “open”).
kernel_size (int, optional) – Size of the structuring element (default is 3).
- Returns:
Processed binary mask.
- Return type:
np.ndarray
- subtract_masks(base_mask, *masks)[source]#
Subtract one or more masks from a base mask.
- Parameters:
base_mask (np.ndarray) – Initial binary mask.
*masks (np.ndarray) – Masks to subtract from the base mask.
- Returns:
Resulting mask after subtraction.
- Return type:
np.ndarray
- save_masks_npy(mask, save_path)[source]#
Save mask as a .npy file.
- Parameters:
mask (np.ndarray) – Mask to save.
save_path (str) – Path to save the .npy file.
- Return type:
None
- save_masks(mask, path)[source]#
Save mask as an image file.
- Parameters:
mask (np.ndarray) – Binary mask to save.
path (str) – Path to save the image file.
- Return type:
None
- plot_masks(masks, mask_names, background_color=(0, 0, 0), mask_colors=None, path=None, show=True, ax=None, figsize=(10, 10))[source]#
Plot multiple masks with their corresponding names.
- Parameters:
masks (list of np.ndarray) – List of masks to plot.
mask_names (list of str) – Names corresponding to each mask.
background_color (tuple of int, optional) – RGB color tuple for background areas (default (0, 0, 0)).
mask_colors (dict, optional) – Mapping of mask names to RGB colors.
path (str, optional) – Directory path to save the plot image.
show (bool, optional) – Whether to display the plot (default True).
ax (matplotlib.axes.Axes, optional) – Matplotlib axis to plot on. Creates new figure if None.
figsize (tuple of int, optional) – Size of the figure in inches (width, height).
- Return type:
None
- class gridgene.get_masks.ConstrainedMaskExpansion(seed_mask, constraint_mask=None, logger=None)[source]#
Bases:
GetMasksClass for expanding a seed mask with constraints, generating binary, labeled, and referenced expansions.
- expand_mask(expansion_pixels, min_area=None, restrict_to_limit=True)[source]#
Expand the seed mask outward by specified pixel distances with optional area filtering and constraints.
- Parameters:
expansion_pixels (list of int) – List of expansion distances (in pixels) from the seed mask.
min_area (int, optional) – Minimum area threshold for keeping connected components in each expansion ring.
restrict_to_limit (bool, optional) – If True, limit the expansion within the constraint mask.
- Return type:
None
- propagate_labels(seed_labeled, expansion_mask)[source]#
Propagate labels from the seed labeled mask into the expansion region using nearest-neighbor distance transform.
- Parameters:
seed_labeled (np.ndarray) – Labeled seed mask where non-zero values indicate components.
expansion_mask (np.ndarray) – Binary mask indicating the expansion region to propagate labels into.
- Returns:
Labeled mask with propagated labels in the expansion area.
- Return type:
np.ndarray
- class gridgene.get_masks.SingleClassObjectAnalysis(get_masks_instance, contours_object, contour_name='')[source]#
Bases:
GetMasksAnalyze and expand a single binary object mask using distance-based ring expansion.
This class computes concentric ring-based expansions of a binary mask, assigns unique labels to each expanded region, and tracks mask lineage through label propagation.
- mask#
Binary mask of the object to be expanded.
- Type:
np.ndarray
- expansion_distances#
List of expansion radii in pixels.
- Type:
List[int]
- labelled_mask#
Resulting labeled mask with original and expanded areas.
- Type:
np.ndarray
- binary_masks#
Dictionary of binary masks keyed by expansion distance.
- Type:
Dict[str, np.ndarray]
- labelled_masks#
Dictionary of labeled masks keyed by expansion distance.
- Type:
Dict[str, np.ndarray]
- reference_masks#
Masks encoding reference to original object.
- Type:
Dict[str, np.ndarray]
- get_mask_objects(exclude_masks=None, filter_area=None)[source]#
Generate binary mask from object contours, optionally subtract other masks, and apply area-based filtering.
- Parameters:
exclude_masks (list of np.ndarray, optional) – List of masks to subtract from the generated object mask.
filter_area (int, optional) – Minimum area threshold to retain connected components in the object mask.
- Return type:
None
- get_objects_expansion(expansions_pixels=None, filter_area=None)[source]#
Expand the object mask using distance-based rings and optionally filter each ring by minimum area. Generates binary, labeled, and propagated-label expansion masks.
- Parameters:
expansions_pixels (list of int, optional) – List of pixel distances for expansion.
filter_area (int, optional) – Minimum area threshold to retain connected components in each expansion ring.
- Return type:
None
- propagate_labels(seed_labeled, expansion_mask)[source]#
Propagate labeled regions from a seed mask into the expansion area using iterative dilation.
- Parameters:
seed_labeled (np.ndarray) – Input labeled mask where each connected component has a unique integer label.
expansion_mask (np.ndarray) – Binary mask indicating the region where labels should expand.
- Returns:
Labeled mask with labels propagated into the expansion region.
- Return type:
np.ndarray
- class gridgene.get_masks.MultiClassObjectAnalysis(get_masks_instance, multiple_contours, save_path=None)[source]#
Bases:
GetMasksAnalyze and expand multiple object contours across different classes using Voronoi constraints.
Constructs Voronoi diagrams to limit spatial expansion, assigns unique labels to each object, and tracks class-wise and parent-wise mask lineage for downstream analysis.
- multiple_contours#
Input contours grouped by class.
- Type:
dict[str, list[np.ndarray]]
- height#
Image height.
- Type:
int
- width#
Image width.
- Type:
int
- save_path#
Optional path to save outputs.
- Type:
str or None
- vor#
Computed Voronoi diagram.
- Type:
scipy.spatial.Voronoi or None
- all_centroids#
Coordinates of centroids of input objects.
- Type:
np.ndarray or None
- class_labels#
Class label for each object.
- Type:
list[str] or None
- binary_masks#
Output binary masks by class and expansions.
- Type:
dict[str, np.ndarray]
- labeled_masks#
Output labeled masks by class and expansions.
- Type:
dict[str, np.ndarray]
- referenced_masks#
Output referenced masks mapping pixels back to parent objects.
- Type:
dict[str, np.ndarray]
- static voronoi_finite_polygons_2d(vor, radius=None)[source]#
Reconstruct finite Voronoi polygons in 2D by clipping infinite regions.
- Parameters:
vor (scipy.spatial.Voronoi) – The original Voronoi diagram from scipy.spatial.
radius (float, optional) – Distance to extend infinite edges (default is twice the maximum image dimension).
- Returns:
regions (list[list[int]]) – List of polygon regions as indices of vertices.
vertices (np.ndarray) – Array of Voronoi vertices coordinates.
- get_polygons_from_contours(contours)[source]#
Convert contours into Shapely polygons.
- Parameters:
contours (list[np.ndarray]) – List of contour arrays of shape (N, 2).
- Returns:
polygons – List of valid Shapely Polygon objects.
- Return type:
list[Polygon]
- derive_voronoi_from_contours()[source]#
Compute a Voronoi diagram from centroids of contours.
Computes Voronoi regions and finite polygons clipped to a large radius. Stores regions, vertices, class labels, and centroids for further processing.
- Raises:
ValueError – If no contours are available to derive the Voronoi diagram.
- Return type:
None
- get_voronoi_mask(category_name)[source]#
Get a binary mask for the Voronoi region of a given category.
If Voronoi regions are not computed (e.g. too few centroids), returns a full mask.
- Parameters:
category_name (str) – The category/class name for which the mask is requested.
- Returns:
mask – Binary mask of shape (height, width) with Voronoi regions for the category.
- Return type:
np.ndarray
- expand_mask(mask, expansion_distance)[source]#
Expand a binary mask by a given pixel distance using distance transform.
The returned mask corresponds to the expansion region excluding the original mask.
- Parameters:
mask (np.ndarray) – Binary input mask to expand.
expansion_distance (int) – Number of pixels to expand the mask by.
- Returns:
Binary mask representing the expansion area only.
- Return type:
np.ndarray
- generate_expanded_masks_limited_by_voronoi(expansion_distances)[source]#
Generate expanded masks for each object limited by their Voronoi regions.
For each class and its contours, original masks are created and then expanded by the specified distances, clipped to the corresponding Voronoi region. All expansions are labeled and tracked with parent IDs.
- Parameters:
expansion_distances (list[int]) – List of pixel distances for mask expansion rings.
- Returns:
binary_masks: dict mapping mask names to binary masks.
labeled_masks: dict mapping mask names to labeled masks with unique IDs.
referenced_masks: dict mapping mask names to masks referencing parent object IDs.
- Return type:
tuple of dict
- plot_masks_with_voronoi(mask_colors, background_color=(255, 255, 255), show=True, axes=None, figsize=(8, 8))[source]#
Plots the generated masks overlaid with Voronoi edges.
- Parameters:
mask_colors (Dict[str, Tuple[int, int, int]]) – Mapping from class name to RGB color.
background_color (Tuple[int, int, int], optional) – RGB color for background. Defaults to white.
show (bool, optional) – If True, displays the plot. Defaults to True.
axes (matplotlib.axes.Axes, optional) – Existing axes to plot on.
figsize (Tuple[int, int], optional) – Figure size for new plot.
- Returns:
The plot axes (if axes was provided).
- Return type:
matplotlib.axes.Axes