phenotypic.Image.gray#
- property Image.gray: Grayscale#
The image’s grayscale representation. The array form is converted into a gray form since some algorithm’s only handle 2-D
Note
gray elements are not directly mutable in order to preserve image information integrity
Change gray elements by changing the image being represented with Image.set_image()
- Returns:
An immutable container for the image gray that can be accessed like a numpy array, but has extra methods to streamline development.
- Return type:
Grayscale
See Also:
ImageMatrix
Grayscale API#
- class phenotypic.core._image_parts.accessors.Grayscale(root_image: Image)[source]
Bases:
SingleChannelAccessorAccessor for managing and visualizing grayscale image data.
This class provides an interface for interacting with the luminance-based grayscale representation of an image. It supports data access, modification, visualization through histograms, and overlay annotations. The accessor maintains immutability of data at the external interface level while allowing controlled modifications through dedicated methods.
The grayscale data is stored as a 2D floating-point array with normalized values in the range [0.0, 1.0].
- Parameters:
root_image (Image)
- _accessor_property_name
Property name used to access this accessor from the Image object (set to “gray”).
- Type:
Examples
Access and display grayscale data
img = Image("path/to/image.png") gray_array = img.gray[:] fig, ax = img.gray.show()
Modify grayscale data with validation
img.gray[10:20, 10:20] = 0.5 # Set region to mid-gray img.gray[100, 100] = 0.8 # Set single pixel to light gray
Visualize histogram and overlay
fig, axes = img.gray.histogram() fig, ax = img.gray.show_overlay(show_labels=True)
- __array__(dtype=None, copy=None)
Implements the array interface for numpy compatibility.
This allows numpy functions to operate directly on accessor objects. For example: np.sum(accessor), np.mean(accessor), etc.
- Parameters:
dtype – Optional dtype to cast the array to
copy – Optional copy parameter for NumPy 2.0+ compatibility
- Returns:
The underlying array data
- Return type:
np.ndarray
- __getitem__(key) numpy.ndarray[source]
Retrieve a read-only view or slice of the grayscale image data.
Allows array-style indexing and slicing to access subsets of the grayscale data. The returned array is marked read-only to prevent accidental modifications. Use __setitem__ for intentional modifications.
- Parameters:
key – Index or slice specification. Can be an integer for single-row access, tuple of slices for multi-dimensional slicing (e.g., [10:20, 5:15]), or boolean arrays for advanced indexing.
- Returns:
- A read-only view of the requested grayscale data. Values are
normalized floating-point numbers in the range [0.0, 1.0].
- Return type:
np.ndarray
- Raises:
EmptyImageError – If the underlying image data is empty (shape[0] == 0).
Examples
Access grayscale data with various indexing techniques
# Access entire grayscale array full_gray = img.gray[:] # Slice a region region = img.gray[10:20, 5:15] # Access single row row = img.gray[10] # Advanced indexing not recommended but supported mask = img.gray > 0.5
- __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) None[source]
Modify grayscale image data at specified indices with validation.
Allows assignment of new values to grayscale data at specified locations. All values must be normalized to the range [0.0, 1.0]. Modifications trigger automatic reset of dependent data structures (enhanced grayscale and object map) to maintain consistency.
- Parameters:
key – Index or slice specification. Same indexing schemes as __getitem__ (e.g., [10:20, 5:15], [100, 100], [:]).
value (np.ndarray | int | float) – New value(s) to assign. Can be: - A NumPy array with shape matching the indexed region. - A scalar (int or float) to broadcast to the indexed region. Must contain values in the range [0.0, 1.0].
- Raises:
ArrayKeyValueShapeMismatchError – If value is an ndarray and its shape does not match the shape of the indexed region.
TypeError – If value is not an ndarray, int, or float.
AssertionError – If values are outside the valid range [0.0, 1.0].
- Return type:
None
Notes
All grayscale values must be normalized to [0.0, 1.0].
Modifications automatically reset enh_gray and objmap to prevent stale data.
For bulk operations, consider using direct array indexing on a copy.
Examples
Modify grayscale data with different assignment patterns
# Set a region to a specific value img.gray[10:20, 5:15] = 0.5 # Set a single pixel img.gray[100, 100] = 0.8 # Assign from another array region = np.random.rand(10, 10) img.gray[10:20, 5:15] = region
- copy() numpy.ndarray
- Return type:
- 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")
- show(figsize: tuple[int, int] | None = None, title: str | None = None, ax: Axes | None = None, cmap: str | None = 'gray', foreground_only: bool = False, *, mpl_settings: dict | None = None) tuple[Figure, Axes]
Displays a visual representation of the current object using matplotlib.
This method generates and displays an image or a plot of the object’s data using matplotlib. It provides options to customize the figure size, title, color map, and other visual properties. It also allows focusing on specific foreground elements if desired.
- Parameters:
figsize (tuple[int, int] | None) – A tuple specifying the size of the matplotlib figure in inches (width, height). If None, default settings are used.
title (str | None) – The title of the plot. If None, no title is displayed.
ax (plt.Axes | None) – A matplotlib Axes object on which the plot will be drawn. If None, a new Axes object is created.
cmap (str | None) – The name of the colormap to use. Defaults to ‘gray’.
foreground_only (bool) – A flag indicating whether to display only the foreground elements of the data. Defaults to False.
mpl_settings (dict | None) – A dictionary of matplotlib settings to apply to the figure or Axes. If None, no additional settings are applied.
- Returns:
- The matplotlib Figure and Axes objects
containing the generated plot.
- Return type:
tuple[plt.Figure, plt.Axes]
- 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: Tuple[int, ...]
Returns the shape of the current image data.
This method retrieves the dimensions of the array stored in the _main_arr attribute as a tuple, which indicates its size along each axis.
- Returns:
A tuple representing the dimensions of the _main_arr attribute.
- Return type:
Tuple[int, …]