phenotypic.Image.objmask#
- property Image.objmask: ObjectMask#
Returns the ObjectMask Accessor; The object mask is a mutable binary representation of the objects in an image to be analyzed. Changing elements of the mask will reset object_map labeling.
Note
- If the image has not been processed by a detector, the target for analysis is the entire image itself. Accessing the object_mask in this case
will return a 2-D array entirely with other_image 1 that is the same shape as the gray
Changing elements of the mask will relabel of objects in the object_map
- Returns:
A mutable binary representation of the objects in an image to be analyzed.
- Return type:
ObjectMaskErrors
See Also:
ObjectMask
ObjectMask API#
- class phenotypic.core._image_parts.accessors.ObjectMask(root_image: Image)[source]
Bases:
SingleChannelAccessorManages a binary object mask linked to a parent image.
ObjectMask provides array-like access and manipulation of a binary mask indicating object locations in the parent image. It supports slicing, item assignment, copying, and visualization. The mask is backed by a sparse representation stored in the parent image’s sparse_object_map, with automatic relabeling via scikit-image’s label() function to maintain consistent object IDs after modifications.
The object mask distinguishes between foreground (object) pixels (value 1) and background pixels (value 0). Any modification to the mask via __setitem__ triggers automatic relabeling to ensure object label consistency across the parent image’s object map.
- Parameters:
root_image (Image)
- _root_image
The parent Image object containing this mask.
- Type:
Note
Changes to the object mask will trigger automatic relabeling of the object map to maintain consistent object IDs. This ensures data integrity when mask regions are directly modified.
Examples
Basic access and slicing
# Access the mask as a dense array mask_array = np.array(objmask) # Slice operations region = objmask[10:50, 20:60] # Modify mask regions objmask[10:50, 20:60] = np.zeros((40, 40))
Creating foreground images
# Get foreground of a grayscale channel foreground = image.gray.foreground()
- __array__(dtype=None, copy=None)[source]
Implement the NumPy array interface for seamless integration with NumPy.
Converts the sparse binary mask to a dense NumPy array, enabling direct use of NumPy functions and operations on the ObjectMask. The mask is always returned as binary values (0 for background, 1 for foreground).
- Parameters:
- Returns:
- A dense binary array of shape matching the parent image with
int dtype (0 and 1 values), or the specified dtype.
- Return type:
np.ndarray
Examples
Using with NumPy functions and type conversion
# Use with NumPy functions num_foreground_pixels = np.count_nonzero(objmask) total_pixels = np.sum(objmask) # Explicit type conversion mask_float = np.array(objmask, dtype=np.float32)
- __getitem__(key)[source]
Return a slice of the binary object mask with NumPy-compatible indexing.
Supports all standard NumPy slicing operations (integer indexing, slice objects, boolean masks, fancy indexing). The sparse mask is converted to dense form and binary values (0 and 1) are returned.
- Parameters:
key (int, slice, tuple, np.ndarray) – Index or slice to retrieve. Follows NumPy indexing conventions for 2D arrays.
- Returns:
- Binary array (0 and 1 values) representing the sliced region of
the mask, with the same shape as the indexed region.
- Return type:
np.ndarray
Examples
NumPy slicing and indexing operations
# Single row row = objmask[10] # Rectangular region region = objmask[10:50, 20:60] # Column col = objmask[:, 5] # Boolean indexing foreground_indices = objmask > 0
- __len__() int
Returns the length of the subject array.
This method calculates and returns the total number of elements contained in the underlying array.
- Returns:
The number of elements in the underlying array attribute.
- Return type:
- __setitem__(key, value: numpy.ndarray)[source]
Update mask values at specified locations with automatic relabeling.
Sets mask values at the specified indices or slices, then automatically relabels the entire mask using scikit-image’s label() function to ensure object IDs remain consistent across the parent image. This maintains data integrity when mask regions are directly modified.
The operation accepts scalar values (0, 1, bool) or arrays. Non-zero values are converted to 1 (foreground), zero values to 0 (background). The updated mask is then relabeled atomically to avoid inconsistent states.
- Parameters:
- Raises:
InvalidMaskScalarValueError – If a scalar value cannot be converted to a valid binary value (not int, bool, or convertible to these types).
InvalidMaskValueError – If value is not an int, bool, or ndarray.
ArrayKeyValueShapeMismatchError – If an ndarray value’s shape does not match the shape of the indexed mask region.
Examples
Setting mask regions with scalars and arrays
# Set a rectangular region to background (0) objmask[10:50, 20:60] = 0 # Set with a matching array region_mask = np.ones((40, 40)) objmask[10:50, 20:60] = region_mask # Set single pixel objmask[5, 10] = True
Note
The entire mask is relabeled after any modification. This ensures that object IDs in the parent image remain consistent, but may change existing object labels if the relabeling alters connectivity.
- copy() numpy.ndarray[source]
Return an independent copy of the binary object mask.
Creates a new array containing the same binary values (0 and 1) as the current mask. Modifications to the returned array do not affect the original mask or the parent image.
- Returns:
- A dense copy of the binary mask with int dtype, independent
of the original sparse representation.
- Return type:
np.ndarray
Examples
Creating an independent mask copy
# Create a modifiable copy for processing mask_copy = objmask.copy() mask_copy[10:50, 20:60] = 0 # Doesn't affect objmask
- foreground()
Extracts and returns the foreground of the image by masking out the background.
This method generates a foreground image by applying the object mask stored in the Image to the current array representation. Pixels outside the object mask are set to zero in the resulting foreground image. This is useful in image processing tasks to isolate the region of interest in the image, such as microbe colonies on an agar plate.
- Returns:
A numpy array containing only the foreground portion of the image, with all non-foreground pixels set to zero.
- Return type:
- histogram(figsize: Tuple[int, int] = (10, 5), *, cmap='gray', linewidth=1, channel_names: list | None = None) Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
Plots the histogram(s) of an image along with the image itself. The behavior depends on the dimensionality of the image array (2D or 3D). In the case of 2D, a single image and its histogram are produced. For 3D (multi-channel images), histograms for each channel are created alongside the image. This method supports customization such as figure size, colormap, line width of histograms, and labeling of channels.
- Parameters:
figsize (Tuple[int, int]) – The size of the figure to create. Default is (10, 5).
cmap (str) – Colormap used to render the image when the data is single channel. Default is ‘gray’.
linewidth (int) – Line width of the plotted histograms. Default is 1.
channel_names (list | None) – Optional names for the channels in 3D data. These are used as titles for channel-specific histograms. If None, channels are instead labeled numerically.
- Returns:
The Matplotlib figure and axes objects representing the plotted image and its histograms.
- Return type:
Tuple[plt.Figure, plt.Axes]
- Raises:
ValueError – If the dimensionality of the input image array is unsupported.
Notes
This method uses skimage.exposure.histogram for computing the histogram data.
- imsave(filepath: str | Path | None = None) None
Save the image array to a file with PhenoTypic metadata embedded.
Metadata is embedded in format-specific locations: - JPEG: EXIF UserComment tag - PNG: tEXt chunk with key ‘phenotypic’ - TIFF: ImageDescription tag (270)
- Parameters:
filepath (str | Path | None) – Path to save the image file. Extension determines format.
- Raises:
ValueError – If file extension is not supported.
- Return type:
None
- isempty()
- classmethod load(filepath: str | Path) numpy.ndarray
Load an image array from file and verify it was saved from this accessor type.
Checks if the image contains PhenoTypic metadata indicating it was saved from the same accessor type (e.g., Image.gray, Image.rgb). If metadata doesn’t match or is missing, a warning is raised but the array is still loaded.
- Parameters:
- Returns:
The loaded image array.
- Return type:
np.ndarray
- Warns:
UserWarning – If metadata is missing or indicates the image was saved from a different accessor type.
Examples
Load a grayscale image from file
>>> from phenotypic.core._image_parts.accessors import Grayscale >>> arr = Grayscale.load("my_gray_image.png")
- reset()[source]
Reset the object mask and linked object map to a cleared state.
Delegates to the parent image’s object map’s reset method, which clears the mask and resets all object labels and properties. This is useful when re-segmenting the image or clearing previous detection results.
Examples
Resetting the mask to cleared state
# Clear the mask and object map objmask.reset() # Now objmask contains only background (0s)
Note
This operation affects both the object mask and the parent image’s object map and properties. Use with caution as it discards all segmentation data.
- show(ax: plt.Axes | None = None, figsize: tuple[int, int] | None = None, cmap: str = 'gray', title: str | None = None) tuple[plt.Figure, plt.Axes][source]
Display the binary object mask as a Matplotlib image.
Renders the object mask using Matplotlib’s imshow with customizable appearance. The mask is shown as a grayscale image where white represents foreground (objects) and black represents background.
- Parameters:
ax (plt.Axes, optional) – An existing Matplotlib Axes object to plot on. If None, a new figure and axes are created. Defaults to None.
figsize (tuple[int, int], optional) – Size of the figure in inches as (width, height). Only used if ax is None. Defaults to None (uses default size).
cmap (str, optional) – Colormap to apply. Defaults to ‘gray’, which shows foreground pixels in white and background in black.
title (str, optional) – Title for the plot. If None, no title is displayed. Defaults to None.
- Returns:
- Matplotlib Figure and Axes objects containing
the rendered mask.
- Return type:
tuple[plt.Figure, plt.Axes]
Examples
Displaying the mask with various options
# Display with default settings fig, ax = objmask.show() # Display with custom size and title fig, ax = objmask.show(figsize=(8, 8), title='Object Mask') # Display on existing axes fig, (ax1, ax2) = plt.subplots(1, 2) objmask.show(ax=ax1, title='Mask') image.gray.show(ax=ax2, title='Original')
- show_overlay(object_label: int | None = None, figsize: tuple[int, int] | None = None, title: str | None = None, show_labels: bool = False, ax: matplotlib.axes.Axes | None = None, *, label_settings: dict | None = None, overlay_settings: dict | None = None, imshow_settings: dict | None = None) tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
Displays an overlay of the object map on the parent image with optional annotations.
- This method enables visualization by overlaying object regions on the parent image. It
provides options for customization, including the ability to show_labels specific objects
and adjust visual styles like figure size, colors, and annotation properties.
- Parameters:
object_label (None | int) – Specific object label to be highlighted. If None, all objects are displayed.
figsize (tuple[int, int]) – Size of the figure in inches (width, height).
title (None | str) – Title for the plot. If None, the parent image’s name is used.
show_labels (bool) – If True, displays annotations for object labels on the object centroids.
label_settings (None | dict) – Additional parameters for customization of the object annotations. Defaults: size=12, color=’white’, facecolor=’red’. Other kwargs are passed to the matplotlib.axes.text () method.
ax (plt.Axes) – Optional Matplotlib Axes object. If None, a new Axes is created.
overlay_settings (None | dict) – Additional parameters for customization of the overlay.
imshow_settings (None|dict) – Additional Matplotlib imshow configuration parameters for customization. If None, default Matplotlib settings will apply.
- Returns:
Matplotlib Figure and Axes objects containing the generated plot.
- Return type:
tuple[plt.Figure, plt.Axes]
- val_range() pd.Interval
Return the closed interval [min, max] of the subject array values.
- Returns:
A single closed interval including both endpoints.
- Return type:
pd.Interval
- property dtype
- property ndim: int
Returns the number of dimensions of the underlying array.
The ndim property provides access to the dimensionality of the array being encapsulated in the object. This value corresponds to the number of axes or dimensions the underlying array possesses. It can be useful for understanding the structure of the contained data.
- Returns:
The number of dimensions of the underlying array.
- Return type:
- property shape
Return the shape of the object mask.
The shape is always identical to the parent image’s shape, since the mask covers the entire image extent.
- Returns:
- Shape of the mask as (height, width), matching the
parent image dimensions.
- Return type:
Examples
Accessing mask shape
height, width = objmask.shape assert objmask.shape == image.gray.shape