zea.tools.selection_tool

Interactive selection tools.

This module provides interactive tools for selecting regions of interest (ROIs) from 2D arrays or images displayed with matplotlib. It is designed for use in ultrasound and image processing workflows where manual or semi-automatic selection of regions is required.

Key Features

  • Interactive selection using rectangle or lasso tools via matplotlib widgets.

  • Support for cropping, masking, and extracting selected regions from images.

  • Polygon and rectangle extraction, interpolation, and mask reconstruction.

  • Utilities for batch selection, mask interpolation across frames, and animation.

  • Integration with tkinter dialogs for user-friendly selection and confirmation.

  • Metric computation (e.g., GCNR) on selected patches.

Example

import matplotlib.pyplot as plt
from zea.tools.selection_tool import interactive_selector

image = ...  # Load your 2D image array
fig, ax = plt.subplots()
ax.imshow(image, cmap="gray")
patches, masks = interactive_selector(image, ax, selector="rectangle")

Functions

add_rectangle_from_mask(ax, mask, **kwargs)

add a rectangle box to axis from mask array.

add_shape_from_mask(ax, mask, **kwargs)

add a shape to axis from mask array.

ask_for_num_selections()

Ask user for number of selections to make.

ask_for_selection_tool()

Ask user for which selection tool to use.

ask_for_title()

ask_save_animation_with_fps()

Ask user for fps to save animation with.

crop_array(array[, value])

Crop an array to remove all rows and columns containing only a given value.

equalize_polygons(polygons[, mode])

Make sure all polygons have the same number of vertices.

extract_polygon_from_mask(mask[, tolerance, ...])

Find largest contour in a binary mask and fit polygon.

extract_rectangle_from_mask(image)

Find corner points of rectangle in binary mask.

interactive_selector(data, ax[, selector, ...])

Interactively select part of an array displayed as an image with matplotlib.

interactive_selector_for_dataset()

To be added.

interactive_selector_with_plot_and_metric(data)

Wrapper for interactive_selector to plot the selected regions.

interpolate_masks(masks, num_frames[, rectangle])

Interpolate between arbitrary number of masks.

interpolate_polygons(polygon1, polygon2, t)

Interpolate between two polygons.

interpolate_rectangles(rectangles, ...)

Interpolate between arbitrary number of rectangles.

main()

Main function for interactive selector on multiple images.

match_polygons(polygon1, polygon2)

Match two polygons by minimizing the total distance between vertices.

reconstruct_mask_from_polygon(vertices, ...)

Reconstruct a binary mask from a polygon.

reconstruct_mask_from_rectangle(...)

Reconstruct a binary mask from corner points of a rectangle.

remove_masks_from_axs(axs)

Remove all masks from the given axes object.

update_imshow_with_mask(frame_no, axs, ...)

Updates the imshow object with the image from the given frame and overlays a mask on top of it.

zea.tools.selection_tool.add_rectangle_from_mask(ax, mask, **kwargs)[source]

add a rectangle box to axis from mask array.

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:

matplotlib axis with rectangle added

Return type:

plt.ax

zea.tools.selection_tool.add_shape_from_mask(ax, mask, **kwargs)[source]

add a shape to axis from mask array.

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:

matplotlib axis with shape added

Return type:

plt.ax

zea.tools.selection_tool.ask_for_num_selections()[source]

Ask user for number of selections to make.

zea.tools.selection_tool.ask_for_selection_tool()[source]

Ask user for which selection tool to use.

zea.tools.selection_tool.ask_for_title()[source]
zea.tools.selection_tool.ask_save_animation_with_fps()[source]

Ask user for fps to save animation with.

zea.tools.selection_tool.crop_array(array, value=None)[source]

Crop an array to remove all rows and columns containing only a given value.

zea.tools.selection_tool.equalize_polygons(polygons, mode='max')[source]

Make sure all polygons have the same number of vertices.

Parameters:
  • polygons (list) – List with any number of polygons as arrays of shape (N, 2).

  • mode (str) – Method for equalizing the number of vertices. Either ‘max’ or ‘min’. with ‘max’ the number of vertices is equal to the polygon with the most vertices. with ‘min’ the number of vertices is equal to the polygon with the least vertices.

Returns:

A tuple of the form (poly1, poly2, …), where poly1, poly2, …

are the trimmed polygons with the same number of vertices as the polygon with the fewest / most vertices, depending on the mode.

zea.tools.selection_tool.extract_polygon_from_mask(mask, tolerance=0.01, verbose=True)[source]

Find largest contour in a binary mask and fit polygon.

Polygon approximation will reduce contour points, unless tolerance is 0.

Parameters:
  • mask (np.ndarray) – 2D binary mask

  • tolerance (float) – Approximation tolerance for polygonal contour

Returns:

Numpy array of shape (N, 2) with vertices of the polygon.

zea.tools.selection_tool.extract_rectangle_from_mask(image)[source]

Find corner points of rectangle in binary mask. :type image: :param image: 2D binary mask :type image: np.ndarray

Returns:

Tuple of the form ((x1, y1), (x2, y2)) with the corner points of the rectangle.

zea.tools.selection_tool.interactive_selector(data, ax, selector='rectangle', extent=None, verbose=True, num_selections=None, confirm_selection=True)[source]

Interactively select part of an array displayed as an image with matplotlib.

Parameters:
  • data (ndarray) – input array. should be 2D.

  • ax (plt.ax) – existing matplotlib figure ax to select region on.

  • selector (str, optional) – type of selector. Defaults to ‘rectangle’. For lasso use LassoSelector; for rectangle, use RectangleSelector.

  • extent (list) – extent of axis where selection is made. Used to transform coordinates back to pixel values. Defaults to None.

  • verbose (bool) – verbosity of print statements. Defaults to False.

  • num_selections (int) – number of selections to make. Defaults to None.

  • confirm_selection (bool) – whether to confirm selection before moving on. Defaults to True.

Returns:

list of selected parts of data masks (list): list of boolean masks for selected parts of data

Return type:

patches (list)

zea.tools.selection_tool.interactive_selector_for_dataset()[source]

To be added. UI for generating and saving masks for entire dataset. In an efficient and user friendly way.

zea.tools.selection_tool.interactive_selector_with_plot_and_metric(data, ax=None, selector='rectangle', metric=None, cmap='gray', plot=True, mask_plot=False, selection_axis=0, **kwargs)[source]

Wrapper for interactive_selector to plot the selected regions.

Parameters:
  • data (ndarray or list of ndarray) – input data.

  • ax (plt.ax or list of plt.ax, optional) – axis corresponding to input data. Defaults to None. In that case function plots data first to create axis.

  • selector (str, optional) – type of selection tool. Defaults to ‘rectangle’.

  • metric (str, optional) – metric to compute. Defaults to None.

  • cmap (str, optional) – color map to display data in. Defaults to ‘gray’.

  • plot (bool, optional) – whether to plot selections / metrics on top of axis. Defaults to True.

  • mask_plot (bool, optional) – whether to also plot the masks in a separate plot. Can be useful to isolate the patches and see the selections more clearly. Defaults to False.

  • selection_axis (int, optional) – axis on which to make selection. Defaults to 0.

Raises:

ValueError – Can only select two patches to compute metric with. More patches don’t make sense in this context.

zea.tools.selection_tool.interpolate_masks(masks, num_frames, rectangle=False)[source]

Interpolate between arbitrary number of masks.

Return type:

list

zea.tools.selection_tool.interpolate_polygons(polygon1, polygon2, t)[source]

Interpolate between two polygons. :type polygon1: :param polygon1: First polygon as an array of shape (N, 2). :type polygon1: np.ndarray :type polygon2: :param polygon2: Second polygon as an array of shape (N, 2). :type polygon2: np.ndarray :type t: :param t: Interpolation parameter, where 0 <= t <= 1. :type t: float

Returns:

Interpolated polygon as an array of shape (N, 2).

zea.tools.selection_tool.interpolate_rectangles(rectangles, x_indices, y_indices)[source]

Interpolate between arbitrary number of rectangles.

Parameters:
  • rectangles (list) – List with any number of rectangles as tuples of the form ((x1, y1), (x2, y2)). Size of the list must be equal to the number of x indices.

  • x_indices (np.ndarray) – Array with x indices for interpolation.

  • y_indices (np.ndarray) – Array with y indices for interpolation.

Returns:

List with interpolated rectangles as tuples of the form ((x1, y1), (x2, y2)).

Size of the list is equal to the number of y indices.

zea.tools.selection_tool.main()[source]

Main function for interactive selector on multiple images.

zea.tools.selection_tool.match_polygons(polygon1, polygon2)[source]

Match two polygons by minimizing the total distance between vertices.

The vertices of the first polygon are shifted circularly to find the best match. Order of vertices is preserved.

Parameters:
  • polygon1 (np.ndarray) – First polygon as an array of shape (N, 2).

  • polygon2 (np.ndarray) – Second polygon as an array of shape (N, 2).

Returns:

Tuple of the form (poly1, poly2), where poly1 and poly2 are the matched polygons.

zea.tools.selection_tool.reconstruct_mask_from_polygon(vertices, image_size)[source]

Reconstruct a binary mask from a polygon.

Fills in regions defined by the polygon contour. :type vertices: :param vertices: Vertices of the polygon as an array of shape (N, 2). :type vertices: np.ndarray :type image_size: :param image_size: Size of the image (height, width). :type image_size: tuple

Returns:

np.ndarray (height, width) with the reconstructed mask.

zea.tools.selection_tool.reconstruct_mask_from_rectangle(corner_points, image_shape)[source]

Reconstruct a binary mask from corner points of a rectangle.

Parameters:
  • corner_points (tuple) – Tuple of the form ((x1, y1), (x2, y2)) with the corner points of the rectangle.

  • image_shape (tuple) – Size of the image (height, width).

Returns:

2D boolean mask of shape (height, width).

Return type:

np.ndarray

zea.tools.selection_tool.remove_masks_from_axs(axs)[source]

Remove all masks from the given axes object.

Return type:

None

zea.tools.selection_tool.update_imshow_with_mask(frame_no, axs, imshow_obj, images, masks, selector)[source]

Updates the imshow object with the image from the given frame and overlays a mask on top of it.

Parameters:
  • frame_no (int) – The index of the frame to display.

  • axs (matplotlib.axes.Axes) – The axes object to display the image on.

  • imshow_obj (matplotlib.image.AxesImage) – The imshow object to update.

  • images (numpy.ndarray) – An array of images to display.

  • masks (numpy.ndarray) – An array of masks to overlay on top of the images.

  • selector (str) – The type of selector to use for the mask. Can be either “rectangle” or “shape”.

Returns:

A tuple containing the updated imshow object and the mask object.

Return type:

tuple