zea.tools.selection_tool

Interactive region-of-interest (ROI) selection.

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

Key features

  • Interactive selection with a rectangle or lasso tool, via matplotlib widgets.

  • Selecting and confirming both happen in the plot window; no tkinter required.

  • Cropping, masking and extracting the selected regions from images.

  • Polygon and rectangle extraction, interpolation and mask reconstruction.

  • Mask interpolation across the frames of a sequence, plus animation of the result.

  • Metric computation (e.g. gCNR) between two selected patches.

  • Reading and writing zea HDF5 files, storing the annotations as a Segmentation map alongside the images.

Command line interface

The module is exposed through the zea CLI as zea tools select:

zea tools select                              # ask for the file paths on the terminal
zea tools select frame.png other.png          # compare two images with gCNR
zea tools select clip.mp4 --num-selections 3  # annotate a video and interpolate

Run zea tools select --help for all options. Any option that is omitted is asked for interactively, so the command can be used without arguments as well.

Annotating a zea dataset

Any zea file with image data (data/image) can be annotated directly, including files on the Hugging Face Hub. For example, on a CAMUS recording:

zea tools select \
    hf://zeahub/camus/val/patient0409/patient0409_4CH_half_sequence.hdf5 \
    --selector lasso --title lv_endo --num-selections 3 --fps 20

Draw the left-ventricle border in each of the three key frames and press enter to keep it. The masks are interpolated across all frames and written to patient0409_4CH_half_sequence_lv_endo_annotations.hdf5 (plus a .gif preview) in the working directory. The result is a regular zea file, so it reads back like any other dataset:

from zea import File

with File("patient0409_4CH_half_sequence_lv_endo_annotations.hdf5") as file:
    images = file.data.image.values[:]              # (n_frames, H, W)
    masks = file.data.segmentation.values[..., 0]   # (n_frames, H, W), bool
    labels = file.data.segmentation.labels[:]       # ["lv_endo"]

Since the tool only produces images and segmentations, the warnings about the acquisition fields it cannot fill in (scan parameters, probe geometry, …) are suppressed when saving.

Python API

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from zea.tools.selection_tool import interactive_selector

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

Module Attributes

SELECTORS

Selection tools that can be used to draw a region of interest.

DEFAULT_KEY

Data key annotated in a zea file when none is given.

ACCEPT_KEYS

Keys that accept what is currently shown.

REDO_KEYS

Keys that discard the current selection and start over.

Functions

annotate_sequence(images[, selector, ...])

Annotate evenly spaced key frames of a sequence and interpolate in between.

ask_for_files()

Ask for the input file paths on the terminal, one per line.

ask_for_num_selections()

Ask the user how many key frames to annotate.

ask_for_selection_tool()

Ask the user which selection tool to use.

ask_for_title()

Ask the user for a title describing what is being selected.

ask_save_animation_with_fps()

Ask the user for the frame rate to save the preview animation with.

compare_images(images, file_names[, ...])

Select two regions in one image and compare them across all images.

confirm_in_figure(fig, num_selections)

Ask, in the plot window, whether to keep the selection that is drawn on it.

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 the largest contour in a binary mask and fit a polygon to it.

extract_rectangle_from_mask(image)

Find the corner points of the rectangle in a binary mask.

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

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

interactive_selector_with_plot_and_metric(data)

Select two regions in one image and compare them across a list of images.

interpolate_masks(masks, num_frames[, ...])

Interpolate between an arbitrary number of masks.

interpolate_polygons(polygon1, polygon2, t)

Interpolate between two polygons.

interpolate_rectangles(rectangles, ...)

Interpolate between an arbitrary number of rectangles.

load_input_files(files[, track, key])

Load a set of images, the frames of a single video / gif, or a zea file.

main()

Entry point for python -m , equivalent to zea tools select.

match_polygon_chain(polygons)

Align a run of polygons so that consecutive ones share a vertex correspondence.

match_polygons(polygon1, polygon2)

Match two polygons by minimizing the total distance between their vertices.

normalize_title(title)

Normalize a user supplied title to a snake_case name.

plot_mask(ax, mask[, selector])

Draw a mask on an axis the way its selector drew it.

preview_figure(images, masks[, selector, ...])

Open a figure showing one annotated frame, to report progress on.

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 mask patches from the given axes object.

run_selection_tool([files, selector, title, ...])

Run the interactive selection tool.

save_mask_animation(images, masks, filename)

Save an animation of the images with their masks overlaid.

save_masks(masks, filename, images[, label, ...])

Save annotations as a zea HDF5 file with an image and a segmentation map.

show_status(fig, message[, banner])

Show message in a highlighted banner under a figure, and paint it right away.

update_imshow_with_mask(frame_no, axs, ...)

Update an imshow object with one frame and overlay the corresponding mask.

wait_for_key(fig, message[, accept, redo])

Show message under a figure and block until the user presses a listed key.

Classes

SelectionInputs(images, file_names, is_sequence)

The images to annotate, and where they came from.

SourceMetadata(file_fields, map_fields[, ...])

Small, cheap-to-copy fields carried over from a zea input file.

zea.tools.selection_tool.ACCEPT_KEYS = ('enter', 'y')

Keys that accept what is currently shown. Closing the window accepts too.

zea.tools.selection_tool.DEFAULT_KEY = 'data/image'

Data key annotated in a zea file when none is given. Names the map group, whose values are the frames and whose other fields describe the grid they sit on.

zea.tools.selection_tool.REDO_KEYS = ('n', 'escape')

Keys that discard the current selection and start over. Deliberately outside matplotlib’s default keymap (‘r’ is “reset view”, ‘q’ closes the window, …).

zea.tools.selection_tool.SELECTORS = ('rectangle', 'lasso')

Selection tools that can be used to draw a region of interest.

class zea.tools.selection_tool.SelectionInputs(images: list[ndarray], file_names: list[str], is_sequence: bool, source: SourceMetadata | None = None)[source]

Bases: NamedTuple

The images to annotate, and where they came from.

Create new instance of SelectionInputs(images, file_names, is_sequence, source)

file_names: list[str]

Name of the file each image came from.

images: list[ndarray]

The 2D images to annotate.

is_sequence: bool

True when the images are consecutive frames of one recording, annotated by interpolating between key frames. False when they are separate images, compared with a metric.

source: SourceMetadata | None

Fields carried over from a zea input file, so the saved annotations line up with (and describe) the source. None for images, videos and gifs.

class zea.tools.selection_tool.SourceMetadata(file_fields: dict, map_fields: dict, track_label: str | None = None)[source]

Bases: NamedTuple

Small, cheap-to-copy fields carried over from a zea input file.

The bulk arrays (raw data, beamformed data, …) are deliberately left behind: the annotation file holds only the images that were annotated and their masks, so it stays small and can be written without streaming gigabytes back out.

Create new instance of SourceMetadata(file_fields, map_fields, track_label)

file_fields: dict

Keyword arguments for zea.File.create(), e.g. metadata, probe.

map_fields: dict

Extra fields for the copied image map, e.g. coordinates, timestamps.

track_label: str | None

Label of the track the images were read from, for a multi-track source file. None when the source had a single track, so there was nothing to record.

zea.tools.selection_tool.annotate_sequence(images, selector='rectangle', num_selections=2, confirm_selection=True)[source]

Annotate evenly spaced key frames of a sequence and interpolate in between.

Closing the window instead of selecting stops the annotating and keeps the key frames done so far, matching what closing the window means elsewhere in the tool. The masks stay tied to the key frames they were drawn on, and the frames past the last annotated key frame keep its mask.

Parameters:
  • images (Sequence[ndarray]) – Frames of the sequence.

  • selector (str) – Type of selection tool. Defaults to "rectangle".

  • num_selections (int) – Number of key frames to annotate. Defaults to 2.

  • confirm_selection (bool) – Whether to ask (in the plot window) to confirm each key frame’s selection. Defaults to True.

Returns:

One interpolated mask per frame in images.

Return type:

list[ndarray]

Raises:

ValueError – If num_selections is not positive, or if no key frame was annotated at all.

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

Ask for the input file paths on the terminal, one per line.

Only reached when no paths were passed on the command line. Typing a video, gif or zea file ends the loop right away, since a sequence is annotated on its own.

Returns:

The chosen paths, local or hf://.

Return type:

list[str]

Raises:

ValueError – If no file was given.

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

Ask the user how many key frames to annotate.

Return type:

int

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

Ask the user which selection tool to use.

Return type:

str

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

Ask the user for a title describing what is being selected.

Return type:

str

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

Ask the user for the frame rate to save the preview animation with.

Return type:

int

zea.tools.selection_tool.compare_images(images, file_names, selector='rectangle', metric='gcnr', confirm_selection=True)[source]

Select two regions in one image and compare them across all images.

Every image is plotted in its own figure; the selection is made in the first one. Nothing is written to disk, so the comparison is held on screen until dismissed, the way sequence mode holds its preview open after saving.

Parameters:
  • images (Sequence[ndarray]) – The images to compare.

  • file_names (Sequence[str]) – Names shown as the title of each figure.

  • selector (str) – Type of selection tool. Defaults to "rectangle".

  • metric (str | None) – Metric to compute between the two patches. Defaults to "gcnr".

  • confirm_selection (bool) – Whether to confirm the selection and hold the comparison open, both in the plot window. Defaults to True.

Returns:

The computed metric scores, one per image.

Return type:

list

zea.tools.selection_tool.confirm_in_figure(fig, num_selections)[source]

Ask, in the plot window, whether to keep the selection that is drawn on it.

Parameters:
  • fig (matplotlib.figure.Figure) – Figure showing the selection.

  • num_selections (int) – Number of selections that were made.

Returns:

True to keep the selection, False to redo it.

Return type:

bool

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

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

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

  • value – Value that marks a row/column as empty. With the default (None) nothing matches and the array is returned unchanged.

Returns:

The cropped 2D array.

Return type:

np.ndarray

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" (match the polygon with the most vertices, by interpolation) or "min" (match the polygon with the fewest vertices, by subsampling). Defaults to "max".

Returns:

The polygons, all with the same number of vertices.

Return type:

list

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

Find the largest contour in a binary mask and fit a polygon to it.

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

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

  • tolerance (float) – Approximation tolerance for the polygonal contour. Defaults to 0.01.

  • verbose (bool) – Whether to warn when zero or multiple contours are found. Defaults to True.

Returns:

Array of shape (N, 2) with the vertices of the polygon, or None when the mask contains no contour.

Return type:

np.ndarray | None

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

Find the corner points of the rectangle in a binary mask.

Parameters:

image (np.ndarray) – 2D binary mask.

Returns:

((x1, y1), (x2, y2)) with the corner points of the rectangle, or None when the mask is empty.

Return type:

tuple | None

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, must be 2D.

  • ax (matplotlib.axes.Axes) – Existing matplotlib axis to select a region on.

  • selector (str) – Type of selector, one of SELECTORS. Defaults to "rectangle". "lasso" uses matplotlib’s LassoSelector, "rectangle" its RectangleSelector.

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

  • verbose (bool) – Whether to log progress messages. Defaults to True.

  • num_selections (int | None) – Number of selections to make. When omitted the user presses Enter in the plot window to signal they are done.

  • confirm_selection (bool) – Whether to ask (in the plot window) to confirm the selection before returning. Defaults to True.

Returns:

(patches, masks), where patches is a list of the selected parts of data and masks a list of the corresponding boolean masks.

Return type:

tuple

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]

Select two regions in one image and compare them across a list of images.

The selection is made on a single image (data[selection_axis]) and the resulting masks are applied to every image in data, so the same two regions are compared in each of them.

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

  • ax (matplotlib.axes.Axes or list, optional) – Axis (or axes) corresponding to the input data. Defaults to None, in which case the data is plotted first to create the axes.

  • selector (str) – Type of selection tool, one of SELECTORS. Defaults to "rectangle".

  • metric (str | None) – Name of a metric in zea.metrics to compute between the two patches (e.g. "gcnr"). Defaults to None, i.e. no metric.

  • cmap (str) – Colormap to display the data in. Defaults to "gray".

  • plot (bool) – Whether to plot the selections / metrics on top of the axes. Defaults to True.

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

  • selection_axis (int) – Index of the image the selection is made on. Defaults to 0.

  • **kwargs – Forwarded to interactive_selector().

Returns:

The computed metric scores, one per image in data. Empty when metric is None.

Return type:

list

Raises:

ValueError – If the user did not make exactly two selections. More or fewer patches don’t make sense in this context.

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

Interpolate between an arbitrary number of masks.

Parameters:
  • masks (list | ndarray) – At least two binary masks of equal shape.

  • num_frames (int) – Number of masks to interpolate to.

  • rectangle (bool) – Whether the masks are rectangular, in which case the faster rectangle interpolation is used instead of polygon interpolation. Defaults to False.

  • positions (Sequence[int] | None) – Frame index each mask belongs to, strictly increasing. Defaults to None, i.e. spread the masks evenly over the frames. Frames outside the range hold on to the nearest mask.

Returns:

num_frames interpolated masks.

Return type:

list

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

Interpolate between two polygons.

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).

  • t (float) – Interpolation parameter, where 0 <= t <= 1.

Returns:

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

Return type:

np.ndarray

Raises:

ValueError – If the polygons do not have the same number of vertices.

zea.tools.selection_tool.interpolate_rectangles(rectangles, positions, frames)[source]

Interpolate between an arbitrary number of rectangles.

Parameters:
  • rectangles (list) – List with any number of rectangles as tuples of the form ((x1, y1), (x2, y2)). Its length must equal the number of positions.

  • positions (np.ndarray) – Frame index each rectangle sits on.

  • frames (np.ndarray) – Frame indices to interpolate onto.

Returns:

Interpolated rectangles as tuples of the form ((x1, y1), (x2, y2)), one per entry in frames.

Return type:

list

zea.tools.selection_tool.load_input_files(files, track=None, key='data/image')[source]

Load a set of images, the frames of a single video / gif, or a zea file.

Parameters:
  • files (Sequence[str | Path]) – Image files, or a single video / gif or zea HDF5 file. zea files also accept an hf:// URI.

  • track (str | int | None) – Label or index of the track to annotate, for zea files holding more than one.

  • key (str) – Data key of the map to annotate in a zea file. Defaults to DEFAULT_KEY.

Returns:

The loaded images and where they came from.

Return type:

SelectionInputs

Raises:

ValueError – If no files were given, if a file type is unsupported, or if a video / zea file was combined with other files.

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

Entry point for python -m , equivalent to zea tools select.

Return type:

None

zea.tools.selection_tool.match_polygon_chain(polygons)[source]

Align a run of polygons so that consecutive ones share a vertex correspondence.

Each polygon is rolled onto its predecessor, which is never touched again. Matching every pair in both directions instead would re-roll the polygon in the middle and undo the alignment of the segment before it.

Parameters:

polygons (Sequence[ndarray]) – Polygons of shape (N, 2), all with the same number of vertices.

Returns:

The polygons, aligned to their predecessor.

Return type:

list[ndarray]

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

Match two polygons by minimizing the total distance between their vertices.

The vertices of the first polygon are shifted circularly to find the best match. The order of the 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:

(poly1, poly2), the matched polygons.

Return type:

tuple

zea.tools.selection_tool.normalize_title(title)[source]

Normalize a user supplied title to a snake_case name.

The result is used both as a segmentation label and as part of the output filename, so anything outside [a-z0-9_-] is collapsed into underscores.

Parameters:

title (str) – Raw title, e.g. "Left Ventricle".

Returns:

The normalized title, e.g. "left_ventricle".

Return type:

str

Raises:

ValueError – If the title is empty (or contains nothing usable).

zea.tools.selection_tool.plot_mask(ax, mask, selector='rectangle', **kwargs)[source]

Draw a mask on an axis the way its selector drew it.

Parameters:
  • ax (Axes) – Axis to draw on.

  • mask (ndarray) – 2D boolean mask.

  • selector (str) – One of SELECTORS. "rectangle" draws the bounding box, anything else the mask’s own outline. Defaults to "rectangle".

  • **kwargs – Forwarded to the underlying plotting function. alpha defaults to 0.5 so the image stays visible underneath.

Returns:

The matplotlib patch(es) that were added, or None for an empty rectangle mask.

zea.tools.selection_tool.preview_figure(images, masks, selector='rectangle', title='', frame=0)[source]

Open a figure showing one annotated frame, to report progress on.

Parameters:
  • images (Sequence[ndarray]) – Frames of the sequence.

  • masks (Sequence[ndarray]) – One mask per frame.

  • selector (str) – Type of selection tool the masks came from. Defaults to "rectangle".

  • title (str) – Name of what was selected, shown above the frame.

  • frame (int) – Which frame to show. Defaults to 0.

Returns:

The (non-blocking) figure.

Return type:

Figure

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

Reconstruct a binary mask from a polygon.

Fills in the region defined by the polygon contour.

Parameters:
  • vertices (np.ndarray) – Vertices of the polygon as an array of shape (N, 2).

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

Returns:

Array of shape (height, width) with the reconstructed mask.

Return type:

np.ndarray

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 mask patches from the given axes object.

Return type:

None

zea.tools.selection_tool.run_selection_tool(files=None, selector=None, title=None, num_selections=None, fps=None, metric='gcnr', output_dir=None, save_animation=True, confirm_selection=True, overwrite=False, track=None, key='data/image')[source]

Run the interactive selection tool.

This is the entry point behind zea tools select. Depending on the input it runs in one of two modes:

  • Images: two regions are selected in the first image and compared across all images using metric.

  • Sequence (video, gif or a zea file with more than one frame): num_selections key frames are annotated, the masks are interpolated over all frames, written to a zea HDF5 file as a segmentation map next to the images, and optionally previewed as an animated gif.

Any argument left as None is asked for interactively.

Parameters:
  • files (Sequence[str | Path] | None) – Input images, or a single video / gif or zea HDF5 file (an hf:// URI works too). Defaults to None, i.e. ask for the paths on the terminal.

  • selector (str | None) – Type of selection tool, one of SELECTORS.

  • title (str | None) – Name of what is being selected. Used as the segmentation label and in the output filenames. Only used in sequence mode.

  • num_selections (int | None) – Number of key frames to annotate. Only used in sequence mode.

  • fps (int | None) – Frame rate of the preview animation. Only used in sequence mode, and only when save_animation is True.

  • metric (str | None) – Metric to compute between the two patches. Only used in image mode. Defaults to "gcnr".

  • output_dir (str | Path | None) – Directory to write the annotations and animation to. Defaults to the folder of the input file, or the working directory for hf:// inputs.

  • save_animation (bool) – Whether to save a preview gif in sequence mode. Defaults to True.

  • confirm_selection (bool) – Whether to ask (in the plot window) to confirm each selection. Defaults to True.

  • overwrite (bool) – Whether to overwrite existing output files. Checked before the annotating starts, so no work is lost. Defaults to False.

  • track (str | int | None) – Label or index of the track to annotate, for zea files holding more than one.

  • key (str) – Data key of the map to annotate in a zea file. Defaults to DEFAULT_KEY.

Returns:

The metric scores in image mode, or the interpolated masks in sequence mode.

Return type:

list

Raises:

FileExistsError – If an output file exists and overwrite is False.

zea.tools.selection_tool.save_mask_animation(images, masks, filename, selector='rectangle', fps=20)[source]

Save an animation of the images with their masks overlaid.

Parameters:
  • images (Sequence[ndarray]) – Frames of the sequence.

  • masks (Sequence[ndarray]) – One mask per frame.

  • filename (str | Path) – Output path of the gif.

  • selector (str) – Type of selection tool the masks came from, which determines how they are drawn. Defaults to "rectangle".

  • fps (int) – Frames per second of the animation. Defaults to 20.

Returns:

The path the animation was written to.

Return type:

Path

zea.tools.selection_tool.save_masks(masks, filename, images, label='roi', source=None, description=None, overwrite=False)[source]

Save annotations as a zea HDF5 file with an image and a segmentation map.

The result is a regular zea file (see FileSpec) holding the annotated images under data/image and the masks as a single-label boolean Segmentation under data/segmentation, so it can be read back with zea.File like any other zea dataset.

When the images came from a zea file, source carries its metadata over: the pixel coordinates, frame timing, probe, subject and credit information. The bulk arrays are not copied – the annotation file describes the images that were annotated, not the acquisition they were reconstructed from.

Since the selection tool only produces images and segmentations, the warnings about the acquisition fields it cannot fill in (scan parameters, …) are suppressed.

Parameters:
  • masks (Sequence[ndarray] | ndarray) – One boolean mask per image.

  • filename (str | Path) – Output path; the .hdf5 suffix is enforced.

  • images (Sequence[ndarray] | ndarray) – The annotated images, of equal shape as the masks.

  • label (str) – Name of the segmentation label. Defaults to "roi".

  • source (SourceMetadata | None) – Fields carried over from a zea input file, as returned in SelectionInputs.source. Defaults to None.

  • description (str | None) – Free-text description stored in the file.

  • overwrite (bool) – Whether to overwrite an existing file. Defaults to False.

Returns:

The path the file was written to.

Return type:

Path

zea.tools.selection_tool.show_status(fig, message, banner=None)[source]

Show message in a highlighted banner under a figure, and paint it right away.

Parameters:
  • fig (matplotlib.figure.Figure) – Figure to draw the banner on.

  • message (str) – Text to show.

  • banner (matplotlib.text.Text, optional) – Banner returned by an earlier call, which is replaced. Defaults to None, i.e. draw a new one.

Returns:

The banner, to pass back in or to remove().

Return type:

matplotlib.text.Text

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

Update an imshow object with one frame and overlay the corresponding mask.

This function is designed for animation where each frame has one associated mask. It removes any existing masks from the axes before plotting the new one.

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

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

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

  • images (ndarray) – An array of images with shape (num_frames, height, width).

  • masks (ndarray) – An array of masks with shape (num_frames, height, width), where each mask corresponds to one frame in the images array.

  • selector (str) – The type of selector used, one of SELECTORS. Rectangles are drawn as a bounding box, anything else as an arbitrary shape.

  • **kwargs – Forwarded to the plotting function.

Returns:

The updated imshow object and the mask object (the matplotlib patch that was plotted).

Return type:

tuple

zea.tools.selection_tool.wait_for_key(fig, message, accept=('enter', 'y'), redo=())[source]

Show message under a figure and block until the user presses a listed key.

Parameters:
  • fig (matplotlib.figure.Figure) – Figure to listen on and write the message under.

  • message (str) – Instruction shown to the user, e.g. which keys to press.

  • accept (Sequence[str]) – Keys that return True. Defaults to ACCEPT_KEYS.

  • redo (Sequence[str]) – Keys that return False. Defaults to none, i.e. the prompt can only be accepted.

Returns:

True when an accept key was pressed (or the window was closed), False for a redo key.

Return type:

bool