phenotypic.Image.enh_gray#

property Image.enh_gray: EnhancedGrayscale#

Returns the image’s enhanced grayscale accessor. Preprocessing steps can be applied to this component to improve detection performance.

The enhanceable gray is a copy of the image’s gray form that can be modified and used to improve detection performance. The original gray data should be left intact in order to preserve image information integrity for measurements.’

Returns:

A mutable container that stores a copy of the image’s gray form

Return type:

EnhancedGrayscale

EnhancedGrayscale API#

class phenotypic.core._image_parts.accessors.EnhancedGrayscale(root_image: Image)[source]

Bases: SingleChannelAccessor

Accessor for manipulating and visualizing enhanced grayscale image data.

EnhancedGrayscale provides access to a mutable copy of the original grayscale matrix that can be modified for enhancement operations without compromising the integrity of the original grayscale data or object detection results. This class enables retrieval and modification of enhanced grayscale data, resetting to original values, and accessing visualization and analysis methods inherited from SingleChannelAccessor.

The enhanced grayscale representation is useful for applying non-destructive filters, adjustments, or transformations that should not affect the parent image’s core data or segmentation results.

Parameters:

root_image (Image)

_accessor_property_name

The property name on the Image object that returns this accessor. Set to “enh_gray”.

Type:

str

__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]

Return a non-writeable view of the enhanced grayscale data for the given index.

Retrieves a portion of the enhanced grayscale array using standard NumPy indexing. The returned view is read-only to prevent unintended modifications outside of the proper __setitem__ interface.

Parameters:

key – Array indexing expression (integer, slice, tuple of indices, or boolean mask). Follows standard NumPy indexing conventions.

Returns:

A non-writeable view of the enhanced grayscale data at the specified

index. The returned array shares memory with the underlying data but cannot be modified.

Return type:

np.ndarray

Raises:

EmptyImageError – If the image has no data loaded (empty shape).

Examples

Retrieve a single pixel value
pixel_value = enh_gray[100, 200]
Retrieve a rectangular region
region = enh_gray[100:200, 50:150]
__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:

int

__setitem__(key, value)[source]

Set enhanced grayscale data at the specified index with validation.

Sets data in the enhanced grayscale array at the specified location. The method validates that the input is either a scalar numeric value (int or float) or a NumPy array with a shape matching the indexed region. After successful assignment, the parent image’s object map is reset to maintain consistency with the modified grayscale data.

Parameters:
  • key – Array indexing expression (integer, slice, tuple of indices, or boolean mask). Follows standard NumPy indexing conventions and must be compatible with the enhanced grayscale array structure.

  • value (int | float | np.ndarray) – The value(s) to assign. Can be: - A scalar (int or float) that will be broadcast to all indexed elements - A NumPy array whose shape must exactly match the indexed region’s shape

Raises:
  • ArrayKeyValueShapeMismatchError – If value is a NumPy array and its shape does not match the shape of the indexed region.

  • TypeError – If value is neither a scalar (int or float) nor a NumPy array.

Examples

Set a single pixel to a scalar value
enh_gray[100, 200] = 128
Set a rectangular region with an array
region_data = np.ones((100, 100), dtype=np.uint8) * 150
enh_gray[100:200, 50:150] = region_data
Broadcast a scalar to a region
enh_gray[0:50, 0:50] = 255  # Set all pixels in region to 255
copy() numpy.ndarray
Return type:

numpy.ndarray

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:

numpy.ndarray

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:

filepath (str | Path) – Path to the image file to load.

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 enhanced grayscale to a copy of the original grayscale data.

Discards all modifications made to the enhanced grayscale and restores it to match the original grayscale representation. This is useful when reverting failed or unwanted enhancement operations. The reset operation creates a fresh copy of the original grayscale data to ensure subsequent modifications do not affect the original.

Examples

Reset after applying unsuccessful enhancement
enh_gray.reset()  # Revert to original grayscale
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:

int

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, …]

property size: int

Gets the size of the subject array.

This property retrieves the total number of elements in the subject array. It is read-only.

Returns:

The total number of elements in the subject array.

Return type:

int