zea.visualize

Visualization functions for 2D and 3D ultrasound data.

Functions

pad_or_crop_extent(image, extent, target_extent)

Pads and/or crops the extent of an image to match a target extent.

plot_biplanes(volume[, cmap, resolution, ...])

Plot three intersecting planes from a 3D volume in 3D space.

plot_frustum_vertices(rho_range, ...[, ...])

Plots the vertices of a frustum in spherical coordinates and highlights specified planes.

plot_image_grid(images[, ncols, cmap, vmin, ...])

Plot a batch of images in a grid.

plot_quadrants(ax, array, fixed_coord, cmap, ...)

For a given 3D array, plot a plane with fixed_coord using four individual quadrants.

plot_rectangle_from_mask(ax, mask, **kwargs)

Plots a rectangle box to axis from mask array.

plot_shape_from_mask(ax, mask, **kwargs)

Plots a shape to axis from mask array.

set_mpl_style([style])

Set the matplotlib style.

visualize_matrix(matrix[, font_color])

Visualize a matrix with the values in each cell.

zea.visualize.pad_or_crop_extent(image, extent, target_extent)[source]

Pads and/or crops the extent of an image to match a target extent.

This is useful for side by side comparison of images with different extents.

Parameters:
  • image (np.ndarray) – The input image to be padded and/or cropped. Only 2D images are supported. Image shape must be (grid_size_z, grid_size_x).

  • extent (tuple) – The current extent of the image in the format (x_min, x_max, z_min, z_max).

  • target_extent (tuple) – The target extent to match in the format (x_min, x_max, z_min, z_max).

Returns:

The padded and/or cropped image.

Return type:

np.ndarray

zea.visualize.plot_biplanes(volume, cmap='gray', resolution=1.0, stride=1, slice_x=None, slice_y=None, slice_z=None, show_axes=None, fig=None, ax=None, **kwargs)[source]

Plot three intersecting planes from a 3D volume in 3D space.

Also known as ultrasound biplane visualization.

Parameters:
  • volume (ndarray) – 3D numpy array representing the volume to be plotted.

  • cmap (str, optional) – Colormap to be used for plotting. Defaults to “gray”.

  • resolution (float, optional) – Resolution factor for the volume. Defaults to 1.0.

  • stride (int, optional) – Stride for plotting the quadrants. Defaults to 1.

  • slice_x (int, optional) – Index for the slice in the x-plane. Defaults to None.

  • slice_y (int, optional) – Index for the slice in the y-plane. Defaults to None.

  • slice_z (int, optional) – Index for the slice in the z-plane. Defaults to None.

  • show_axes (dict, optional) – Dictionary to specify axis labels and extents. Defaults to None.

  • fig (matplotlib.figure.Figure, optional) – Matplotlib figure object. Defaults to None. Can be used to reuse the figure in a loop.

  • ax (matplotlib.axes.Axes3DSubplot, optional) – Matplotlib 3D axes object. Defaults to None. Can be used to reuse the axes in a loop.

  • **kwargs – Additional keyword arguments for the plot_surface method.

Returns:

A tuple containing the figure and axes objects (fig, ax).

Return type:

tuple

Raises:

AssertionError – If none of slice_x, slice_y, or slice_z are provided.

zea.visualize.plot_frustum_vertices(rho_range, theta_range, phi_range, num_points=20, phi_plane=None, theta_plane=None, rho_plane=None, fig=None, ax=None, frustum_style=None, phi_style=None, theta_style=None, rho_style=None)[source]

Plots the vertices of a frustum in spherical coordinates and highlights specified planes.

Parameters:
  • rho_range (tuple) – Range of rho values (min, max).

  • theta_range (tuple) – Range of theta values (min, max).

  • phi_range (tuple) – Range of phi values (min, max).

  • num_points (int, optional) – Number of points to generate along each edge. Defaults to 20.

  • phi_plane (float or list, optional) – Value(s) of phi at which to plot plane(s). Defaults to None.

  • theta_plane (float or list, optional) – Value(s) of theta at which to plot plane(s). Defaults to None.

  • rho_plane (float or list, optional) – Value(s) of rho at which to plot plane(s). Defaults to None.

  • fig (matplotlib.figure.Figure, optional) – Figure object to plot on. Defaults to None. Can be used to reuse the figure in a loop.

  • ax (matplotlib.axes.Axes3DSubplot, optional) – Axes object to plot on. Defaults to None. Can be used to reuse the axes in a loop.

  • frustum_style (dict, optional) – Style dictionary for frustum edges. Can include ‘color’, ‘linestyle’, ‘linewidth’, ‘alpha’, etc. Defaults to {‘color’: ‘blue’, ‘linestyle’: ‘-’, ‘linewidth’: 2}.

  • phi_style (dict, optional) – Style dictionary for phi plane(s). Can include ‘color’, ‘linestyle’, ‘linewidth’, ‘alpha’, etc. Defaults to {‘color’: ‘yellow’, ‘linestyle’: ‘-‘}.

  • theta_style (dict, optional) – Style dictionary for theta plane(s). Can include ‘color’, ‘linestyle’, ‘linewidth’, ‘alpha’, etc. Defaults to {‘color’: ‘green’, ‘linestyle’: ‘–‘}.

  • rho_style (dict, optional) – Style dictionary for rho plane(s). Can include ‘color’, ‘linestyle’, ‘linewidth’, ‘alpha’, etc. Defaults to {‘color’: ‘red’, ‘linestyle’: ‘–‘}.

Returns:

A tuple containing the figure and axes objects (fig, ax).

Return type:

tuple

Raises:

ValueError – If no plane is specified (phi_plane, theta_plane, or rho_plane).

Example

>>> from zea.visualize import plot_frustum_vertices
>>> rho_range = [0.1, 10]  # in mm
>>> theta_range = [-0.6, 0.6]  # in rad
>>> phi_range = [-0.6, 0.6]  # in rad
>>> fig, ax = plot_frustum_vertices(
...     rho_range,
...     theta_range=theta_range,
...     phi_range=phi_range,
...     phi_plane=0,
...     phi_style={"color": "red", "linestyle": "--", "linewidth": 2},
...     theta_plane=0.2,
...     theta_style={"color": "green", "linestyle": ":", "alpha": 0.7},
...     frustum_style={"color": "blue", "linewidth": 1.5},
... )
zea.visualize.plot_image_grid(images, ncols=None, cmap='gray', vmin=None, vmax=None, interpolation='auto', titles=None, suptitle=None, aspect=None, figsize=None, fig=None, fig_contents=None, remove_axis=True, background_color=None, text_color=None, axes_pad=0.1, **kwargs)[source]

Plot a batch of images in a grid.

Parameters:
  • images (List[ndarray]) – batch of images.

  • ncols (Optional[int]) – Number of columns. Defaults to None.

  • cmap (Union[str, List[str], None]) – Colormap. Defaults to ‘gray’. If list, cmap must be of same length as images and is set for each axis.

  • vmin (Union[float, List[float], None]) – Minimum plot value. Defaults to None. if list vmin must be of same length as images and is set for each axis.

  • vmax (Union[float, List[float], None]) – Maximum plot value. Defaults to None. if list vmax must be of same length as images and is set for each axis.

  • interpolation (Optional[str]) – Interpolation method that mpl uses. Defaults to ‘auto’.

  • titles (Optional[List[str]]) – List of titles for subplots. Defaults to None.

  • suptitle (Optional[str]) – Title for the plot. Defaults to None.

  • aspect (Union[str, int, float, List[Union[str, int, float]], None]) – Aspect ratio for imshow.

  • figsize (Optional[Tuple[float, float]]) – Figure size. Defaults to None.

  • fig (Optional[Figure]) – Matplotlib figure object. Defaults to None. Can be used to plot on an existing figure.

  • fig_contents (Optional[List]) – List of matplotlib image objects. Defaults to None.

  • remove_axis (Optional[bool]) – Whether to remove axis. Defaults to True. If False, axes r emain but spines are colored to background and ticks/labels are hidden, allowing later label drawing to remain visible.

  • background_color (Optional[str]) – Background color. Defaults to None. (Matplotlib default)

  • text_color (Optional[str]) – Text color. Defaults to None. (Matplotlib default)

  • axes_pad (float) – Padding between axes. Defaults to 0.1.

  • **kwargs – arguments for plt.Figure.

Returns:

Matplotlib figure object fig_contents (list): List of matplotlib image objects.

Return type:

Tuple[Figure, List]

Example

>>> from zea.visualize import plot_image_grid
>>> import numpy as np

>>> images = [np.random.rand(128, 128) for _ in range(6)]

>>> fig, fig_contents = plot_image_grid(
...     images,
...     ncols=3,
...     cmap="gray",
...     vmin=0,
...     vmax=1,
... )
zea.visualize.plot_quadrants(ax, array, fixed_coord, cmap, slice_index, stride=1, centroid=None, **kwargs)[source]

For a given 3D array, plot a plane with fixed_coord using four individual quadrants.

Parameters:
  • ax (matplotlib.axes.Axes3DSubplot) – The 3D axis to plot on.

  • array (numpy.ndarray) – The 3D array to be plotted.

  • fixed_coord (str) – The coordinate to be fixed (‘x’, ‘y’, or ‘z’).

  • cmap (str) – The colormap to be used for plotting.

  • slice_index (int or None) – The index of the slice to be plotted. If None, the middle slice is used.

  • stride (int, optional) – The stride step for plotting. Defaults to 1.

  • centroid (tuple, optional) – centroid around which to break the quadrants. If None, the middle of the image is used.

  • **kwargs – Additional keyword arguments for the plot_surface method.

Returns:

The axis with the plotted quadrants.

Return type:

matplotlib.axes.Axes3DSubplot

zea.visualize.plot_rectangle_from_mask(ax, mask, **kwargs)[source]

Plots a rectangle box to axis from mask array.

Is a simplified version of plot_shape_from_mask for rectangles. Useful for displaying bounding boxes on top of images.

Parameters:
  • ax (plt.ax) – matplotlib axis

  • mask (ndarray) – numpy array with rectangle non-zero box defining the region of interest.

Kwargs:

edgecolor (str): color of the shape’s edge facecolor (str): color of the shape’s face linewidth (int): width of the shape’s edge

Returns:

the added rectangle patch, or None if mask is empty.

Return type:

matplotlib.patches.Rectangle

zea.visualize.plot_shape_from_mask(ax, mask, **kwargs)[source]

Plots a shape to axis from mask array.

Is useful for displaying irregular shapes such as segmentations on top of images.

Parameters:
  • ax (plt.ax) – matplotlib axis

  • mask (ndarray) – numpy array with non-zero shape defining the region of interest.

Kwargs:

edgecolor (str): color of the shape’s edge facecolor (str): color of the shape’s face linewidth (int): width of the shape’s edge

Returns:

list of matplotlib patch objects

added to the axis.

Return type:

list[matplotlib.patches.PathPatch]

Example

import matplotlib.pyplot as plt
import numpy as np

from zea.visualize import plot_shape_from_mask

y, x = np.ogrid[-50:50, -50:50]
mask = x**2 + y**2 <= 30**2
fig, ax = plt.subplots()
ax.imshow(np.random.rand(100, 100), cmap="gray")
plot_shape_from_mask(ax, mask, edgecolor="red", alpha=0.5)
zea.visualize.set_mpl_style(style=None)[source]

Set the matplotlib style.

Parameters:
  • style (str) – Path to the matplotlib style file.

  • "zea_darkmode.mplstyle" (Defaults to)

  • default (which is the)

  • toolbox. (darkmode style used throughout the zea)

Return type:

None

zea.visualize.visualize_matrix(matrix, font_color='white', **kwargs)[source]

Visualize a matrix with the values in each cell.