phenotypic.Image.rgb#

property Image.rgb: ImageRGB#

Returns the ImageArray accessor; An image rgb represents the multichannel information

Note

  • rgb/gray element data is synced

  • change image shape by changing the image being represented with Image.set_image()

  • Raises an error if the arr image has no rgb form

Returns:

A class that can be accessed like a numpy rgb, but has extra methods to streamline development, or None if not set

Return type:

ImageRGB

Raises:

NoArrayError – If no multichannel image data is set as arr.

Example

Image.rgb
from phenotypic import Image
from phenotypic.data import load_colony

image = Image(load_colony())

# get the rgb data
arr = image.rgb[:]
print(type(arr))

# set the rgb data
# the shape of the new rgb must be the same shape as the original rgb
image.rgb[:] = arr

# without the bracket indexing the accessor is returned instead
sprint(image.rgb[:])

See Also: ImageArray

ImageRGB API#

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

Bases: MultiChannelAccessor

Accessor for interacting with RGB multichannel image data.

ImageRGB provides a comprehensive interface for accessing, modifying, visualizing, and analyzing RGB image arrays. It acts as a bridge to the underlying RGB data stored in the parent Image object, exposing the data through intuitive indexing operations and utility methods.

This accessor supports advanced visualization capabilities including display of individual channels or composite images, overlays with segmentation maps, and channel-specific histograms. Users can seamlessly manipulate image arrays, explore geometric and structural attributes, and analyze segmented objects.

The class inherits from MultiChannelAccessor and extends functionality for 3-channel (RGB) images specifically. All visualization and analysis methods from the base class are available and can handle 3-channel color data.

_accessor_property_name

Property name on Image that returns this accessor. Set to “rgb” to identify this as the RGB accessor.

Type:

str

Raises:
  • EmptyImageError – If attempting to access data when no image is loaded.

  • NoArrayError – If attempting to access RGB data when the image is 2D (no RGB array form exists).

Parameters:

root_image (Image)

Examples

Access RGB data from an Image object
rgb_accessor = image.rgb
# Get a copy of the full RGB array
rgb_data = rgb_accessor[:]
# Modify a region
rgb_accessor[10:20, 10:20] = [255, 0, 0]
# Display the image
fig, ax = rgb_accessor.show()
__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) ndarray[source]

Return a read-only view of the RGB subregion specified by the given key.

This method supports NumPy-style indexing and slicing to extract subregions from the RGB image array. The returned array is read-only to prevent accidental modifications outside of the __setitem__ interface.

Parameters:

key – Index or slice specifying the subregion to extract. Supports standard NumPy indexing (e.g., integer indices, slices, boolean masks, advanced indexing). For 3D RGB data, can use notation like [:, :, channel] to select specific channels.

Returns:

A read-only NumPy array containing the extracted subregion

with shape matching the selected region.

Return type:

np.ndarray

Raises:
  • EmptyImageError – If the image contains no RGB data and no grayscale fallback is available.

  • NoArrayError – If the image is 2D (grayscale only) and no RGB array form exists.

Examples

Extract the full RGB array
full_rgb = image.rgb[:]
Extract a rectangular region
region = image.rgb[10:50, 20:60, :]
Extract a specific channel
red_channel = image.rgb[:, :, 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:

int

__setitem__(key, value)[source]

Modify a subregion of the RGB image array.

This method allows in-place modification of the underlying RGB image data using NumPy-style indexing. The provided value must either be a numeric scalar or a NumPy array with shape matching the indexed subregion.

Parameters:
  • key – Index or slice specifying the subregion to modify. Supports standard NumPy indexing (e.g., integer indices, slices, boolean masks, advanced indexing).

  • value (int | float | np.number | np.ndarray) – The new value(s) to assign. Can be a numeric scalar (int, float, or np.number) which will be broadcast to all elements in the indexed region, or a NumPy array with dtype compatible with the image array. If an array, its shape must exactly match the shape of the indexed subregion.

Raises:
  • TypeError – If value is a scalar that is not numeric (int, float, or np.number).

  • TypeError – If value is an array with non-numeric dtype.

  • TypeError – If value is neither a scalar nor a numpy array.

  • ArrayKeyValueShapeMismatchError – If value is an array and its shape does not match the shape of the indexed subregion.

Note

To replace the entire RGB image data, use Image.set_image() instead of this method. This method only modifies specific regions of the existing image array.

After modification, the parent image is updated to reflect changes made through this accessor.

Examples

Set a region to a solid color
image.rgb[10:20, 10:20] = [255, 128, 64]
Set a region from another array
patch = np.ones((10, 10, 3), dtype=np.uint8) * 128
image.rgb[10:20, 10:20] = patch
Modify a single channel
image.rgb[:, :, 0] = 255  # Set red channel to maximum
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(fname: str | Path) None

Save the multichannel 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:

fname (str | Path) – Path to save the image file. Extension determines format.

Raises:

AttributeError – If bit depth is not 8 or 16.

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")
show(figsize: tuple[int, int] | None = None, title: str | None = None, ax: Axes | None = None, channel: int | None = None, foreground_only: bool = False, *, mpl_settings: dict | None = None) tuple[Figure, Axes]

Displays the image data, with the option to customize its visualization and plot settings.

Parameters:
  • figsize (tuple[int, int] | None) – Size of the figure in inches (width, height). If None, a default size is used.

  • title (str | None) – Title of the plot. If None, a default title is generated based on the image and channel.

  • ax (plt.Axes | None) – Matplotlib Axes object. If provided, the image is plotted on this axis. If None, a new axis is created.

  • channel (int | None) – Specific channel index to plot. If None, all channels in the image are displayed.

  • foreground_only (bool) – If True, only the foreground portion of the image is displayed. If False, the entire image is shown.

  • mpl_settings (dict | None) – Optional Matplotlib settings. Allows customization of plot parameters.

Returns:

A tuple containing the Matplotlib Figure and Axes objects used for plotting the image.

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