optimap

Modules

optimap.activation

Activation map computation module.

optimap.image

Functions for loading, saving, and displaying images, and for creating masks.

optimap.motion

Motion estimation and compensation functions for optical mapping data.

optimap.phase

Functions for computing, filtering, and analyzing phase maps from videos, and for detecting phase singularities.

optimap.trace

Functions for extracting time-series from videos.

optimap.utils

General utility functions.

optimap.video

Functions for loading, viewing, filtering, saving and exporting videos.

optimap - An open-source Python toolbox for processing optical mapping and fluorescence imaging data.

optimap.load_video(path, start_frame=0, frames=None, step=1, use_mmap=False, **kwargs)[source]

Loads a video from a file or folder, automatically detecting the file type.

If path is a folder, it will load a video from a series of images in the folder.

Supported file types:

  • .tif, .tiff (TIFF stack)

  • .mat (MATLAB), loads the first field in the file

  • .dat (MultiRecorder)

  • .gsd, .gsh (SciMedia MiCAM 05)

  • .rsh, .rsm, .rsd (SciMedia MiCAM ULTIMA)

  • .npy (numpy array)

  • .mp4, .avi, .mov, … (digital video files)

Supported file types when loading a folder:

  • .tif, .tiff images

  • .png images

For some file types read-only memory mapping is used when use_mmap=True. This is useful for large videos, as it does not load the entire video into memory, only loading the frames when they are accessed. However, it is not supported for all file types, and it is not possible to write to the video array. Supported file types for memory mapping:

  • .tif, .tiff (TIFF stack)

  • .dat (MultiRecorder)

  • .npy (numpy array)

Parameters:
  • path (str or pathlib.Path) – Path to video file, or folder containing images

  • start_frame (int, optional) – Index of the starting frame (0-indexed). Defaults to 0.

  • frames (int or None, optional) – Number of frames to load. If None, loads all frames till the end.

  • step (int, optional) – Steps between frames. If greater than 1, it will skip frames. Defaults to 1.

  • use_mmap (bool, optional) – If True, uses memory mapping to load the video in read-only mode, defaults to False. Only supported for some file types.

  • **kwargs (dict) – Additional arguments to pass to the video loader function

Returns:

video – Video array

Return type:

{t, x, y} ndarray

optimap.load_metadata(filename)[source]

Loads metadata information from a recording, automatically detecting the file type.

Supported file types:

  • .mat (MATLAB)

  • .gsd, .gsh (SciMedia MiCAM 05)

  • .rsh, .rsm, .rsd (SciMedia MiCAM ULTIMA)

  • .dat (MultiRecorder)

Parameters:

filename (str or pathlib.Path) – Path to video file

Returns:

Dictionary containing the metadata

Return type:

dict

optimap.load_image(filename, as_gray=False, **kwargs)[source]

Load an image from a file. Eg. PNG, TIFF, NPY, …

Uses numpy.load() internally if the file extension is .npy. Uses cv2.imread() internally otherwise.

Parameters:
  • filename (str or pathlib.Path) – Filename of image file to load (e.g. PNG, TIFF, …)

  • as_gray (bool, optional) – If True, convert color images to gray-scale. By default False.

  • **kwargs (dict, optional) – passed to cv2.imread() or numpy.load()

Returns:

Image array, color images are in RGB(A) format

Return type:

np.ndarray

optimap.load_mask(filename, **kwargs)[source]

Load a mask from an image file.

Supports NPY, PNG, TIFF, … files.

If the image is grayscale or RGB, half of the maximum value is used as a threshold. Values below the threshold are set to False, values above to True.

If the image is RGBA, then the alpha channel is used as mask using the same threshold.

See save_mask() to save a mask to a file.

Parameters:
  • filename (str) – Filename of image file to load (e.g. NPY, PNG, TIFF, …)

  • **kwargs (dict, optional) – passed to load_image()

Returns:

Mask array

Return type:

np.ndarray of bool

optimap.show_image(image, title='', vmin=None, vmax=None, cmap='gray', show_colorbar=False, colorbar_title='', ax=None, **kwargs)[source]

Show an image.

Parameters:
  • image (2D ndarray) – Image to show.

  • title (str, optional) – Title of the image, by default “”

  • vmin (float, optional) – Minimum value for the colorbar, by default None

  • vmax (float, optional) – Maximum value for the colorbar, by default None

  • cmap (str, optional) – Colormap to use, by default “gray”

  • show_colorbar (bool, optional) – Show colorbar on the side of the image, by default False

  • colorbar_title (str, optional) – Label of the colorbar, by default “”

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure and axes is created.

  • **kwargs (dict, optional) – passed to matplotlib.pyplot.imshow()

Return type:

matplotlib.axes.Axes

optimap.show_mask(mask, image=None, title='', alpha=0.3, color='red', cmap='gray', ax=None)[source]

Show an mask overlayed on an image. If no image is given, only the mask is shown.

Parameters:
  • mask (2D ndarray) – Mask to overlay.

  • image (2D ndarray) – Image to show.

  • title (str, optional) – Title of the image, by default “”

  • alpha (float, optional) – Alpha value of the mask, by default 0.5

  • color (str, optional) – Color of the True values of the mask, by default ‘red’

  • cmap (str, optional) – Colormap of the image, by default “gray”

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure and axes is created.

Returns:

Axes object with image and mask plotted.

Return type:

matplotlib.axes.Axes

optimap.show_positions(positions, image=None, size=None, color=None, cmap='gray', vmin=None, vmax=None, ax=None, **kwargs)[source]

Overlay positions on an image.

Parameters:
  • positions (list of tuples) – List of positions to overlay

  • image (2D array) – Image to overlay positions on, optional

  • size (float or array-like, shape (n, ), optional) – Size of the points, see s parameter in matplotlib.pyplot.scatter() for more information

  • color (str or list of str, optional) – Color of the points, by default None

  • cmap (str, optional) – Colormap to use for image, by default ‘gray’

  • vmin (float, optional) – Minimum value for the colormap, by default None

  • vmax (float, optional) – Maximum value for the colormap, by default None

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure is created.

  • kwargs (dict, optional) – Additional arguments to pass to matplotlib.pyplot.scatter()

Return type:

matplotlib.axes.Axes

optimap.show_traces(traces, x=None, fps=None, colors=None, labels=None, ax=None, **kwargs)[source]

Plot one or more traces.

Parameters:
  • traces (1D or 2D array) – Traces to plot

  • x (1D array, optional) – X-axis values, by default None

  • fps (float, optional) – Sampling rate of the traces (frames per second), by default None. If passed x-axis is shown in seconds. x and fps cannot be passed at the same time.

  • colors (list of colors, optional) – Colors for the traces, by default None

  • labels (list of str, optional) – Labels for the traces, by default None

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on

  • kwargs (dict, optional) – Additional arguments to pass to matplotlib.pyplot.plot()

Return type:

matplotlib.axes.Axes

optimap.show_positions_and_traces(video_or_traces, positions, image=0, size=5, colors=None, figsize=(10, 2.5), fps=None, vmin=None, vmax=None, cmap='gray', **kwargs)[source]

Show positions and traces of a video.

Parameters:
  • video_or_traces (3D video array or 2D/1D trace array) – Video to extract traces from or traces to plot

  • positions (list of tuples) – List of positions to overlay

  • image (2D array or int, optional) – Image to overlay positions on, by default 0 If an integer is passed, the image is taken from the video.

  • size (float or array-like, shape (n, ), optional) – Size parameter for extract_traces(), by default 5

  • colors (list of str, optional) – Colors for the positions/traces, by default None

  • figsize (tuple, optional) – Size of the figure, by default (10, 2.5)

  • fps (float, optional) – Show traces in seconds, see show_traces()

  • vmin (float, optional) – Minimum value for the colormap, by default None

  • vmax (float, optional) – Maximum value for the colormap, by default None

  • cmap (str, optional) – Colormap to use for image, by default ‘gray’

  • kwargs (dict, optional) – Additional arguments to pass to show_traces()

optimap.play_video(video, skip_frame=1, title='', vmin=None, vmax=None, cmap='gray', interval=10, **kwargs)

Deprecated alias for optimap.video.show_video().

optimap.show_video(video, skip_frame=1, title='', vmin=None, vmax=None, cmap='gray', interval=10, **kwargs)[source]

Simple video player based on matplotlib’s animate function.

See optimap.video.show_video_pair() for a player for two videos side-by-side, and optimap.video.show_videos() for a player for n videos side-by-side.

Note

Using Monochrome is an alternative to this function, which allows for more control over the video player.

See monochrome.show_array() for more information.

>>> import monochrome as mc
>>> mc.show_array(video)
Parameters:
  • video ({t, x, y} np.ndarray) – Video to play.

  • skip_frame (int, optional) – Skip every n-th frame, by default 1

  • title (str, optional) – Title of the video, by default “”

  • vmin (float, optional) – Minimum value for the colorbar, by default None

  • vmax (float, optional) – Maximum value for the colorbar, by default None

  • cmap (str, optional) – Colormap to use, by default “gray”

  • interval (int, optional) – Delay between frames in ms, by default 10. This is not the actual framerate, but the delay between frames.

  • **kwargs – Additional keyword arguments passed to matplotlib.pyplot.subplots()

Return type:

InteractivePlayer

optimap.show_video_pair(video1, video2, skip_frame=1, title1='video1', title2='video2', cmap1='gray', cmap2='gray', interval=10, vmin1=None, vmax1=None, vmin2=None, vmax2=None, **kwargs)[source]

Video player for two videos side-by-side based on matplotlib’s animate function.

Parameters:
  • video1 ({t, x, y} np.ndarray) – First video to play.

  • video2 ({t, x, y} np.ndarray) – Second video to play.

  • skip_frame (int, optional) – Skip every n-th frame, by default 1

  • title1 (str, optional) – Title of the first video, by default “video1”

  • title2 (str, optional) – Title of the second video, by default “video2”

  • cmap1 (str, optional) – Colormap to use for the first video, by default “gray”

  • cmap2 (str, optional) – Colormap to use for the second video, by default “gray”

  • vmin1 (float, optional) – Minimum value for the colorbar of the first video, by default None

  • vmax1 (float, optional) – Maximum value for the colorbar of the first video, by default None

  • vmin2 (float, optional) – Minimum value for the colorbar of the second video, by default None

  • vmax2 (float, optional) – Maximum value for the colorbar of the second video, by default None

  • interval (int, optional) – Delay between frames in ms, by default 10. This is not the actual framerate, but the delay between frames.

  • **kwargs – Additional keyword arguments passed to matplotlib.pyplot.subplots()

Return type:

InteractivePlayer

optimap.show_videos(videos, skip_frame=1, titles=None, cmaps='gray', vmins=None, vmaxs=None, interval=10, **kwargs)[source]

Video player for n side-by-side videos based on matplotlib’s animate function.

Parameters:
  • videos (list of {t, x, y} np.ndarray) – Videos to play.

  • skip_frame (int, optional) – Skip every n-th frame, by default 1

  • titles (list of str, optional) – Titles of the videos, by default None

  • cmaps (str or list of str, optional) – Colormaps to use for the videos, by default “gray”

  • vmins (float or list of floats, optional) – Minimum values for the colorbars, by default None

  • vmaxs (float or list of floats, optional) – Maximum values for the colorbars, by default None

  • interval (int, optional) – Delay between frames in ms, by default 10. This is not the actual framerate, but the delay between frames.

  • **kwargs – Additional keyword arguments passed to matplotlib.pyplot.subplots()

Return type:

InteractivePlayer

optimap.show_video_overlay(base: ndarray, overlay: ndarray, alpha: ndarray = None, skip_frames: int = 1, cmap_base='gray', cmap_overlay='Purples', vmin_base=None, vmax_base=None, vmin_overlay=None, vmax_overlay=None, interval=10, **kwargs)[source]

Play a video with an overlay. See export_video_with_overlay() and iter_alpha_blend_videos() for more information.

Parameters:
  • base (np.ndarray) – Base video to play.

  • overlay (np.ndarray) – Video to overlay on the base video.

  • alpha (np.ndarray, optional) – Alpha channel for the overlay, by default None

  • skip_frames (int, optional) – Show every n-th frame, by default 1

  • cmap_base (str or matplotlib.colors.Colormap, optional) – Colormap to use for the base video, by default “gray”

  • cmap_overlay (str or matplotlib.colors.Colormap, optional) – Colormap to use for the overlay video, by default “Purples”

  • vmin_base (float, optional) – Minimum value for the colorbar of the base video, by default None

  • vmax_base (float, optional) – Maximum value for the colorbar of the base video, by default None

  • vmin_overlay (float, optional) – Minimum value for the colorbar of the overlay video, by default None

  • vmax_overlay (float, optional) – Maximum value for the colorbar of the overlay video, by default None

  • interval (int, optional) – Delay between frames in ms, by default 10. This is not the actual framerate, but the delay between frames.

  • **kwargs – Additional keyword arguments passed to matplotlib.pyplot.subplots()

Return type:

matplotlib.animation.FuncAnimation

optimap.save_image(filename, image: ndarray, compat=False, **kwargs)[source]

Save an image to a file. Makes best effort to avoid data precision loss, use export_image() to export images for publications.

The image data is saved as it is, without any normalization or scaling.

The following file formats and image data types are supported: * NumPy: .npy, all data types * PNG: .png, 8-bit or 16-bit unsigned per image channel * TIFF: .tif/.tiff, 8-bit unsigned, 16-bit unsigned, 32-bit float, or 64-bit float images * JPEG: .jpeg/.jpg, 8-bit unsigned * Windows bitmaps: .bmp, 8-bit unsigned

The file format is inferred from the filename extension.

Uses numpy.save() internally if the file extension is .npy and cv2.imwrite() otherwise.

Parameters:
  • filename (str or pathlib.Path) – Path to save image to

  • image (np.ndarray) – Image to save

  • compat (bool, optional) – If True, convert the image to a standard 8-bit format before saving. This can prevent issues where high-bitrate images appear black in some viewers. Defaults to False.

  • **kwargs (dict, optional) – passed to cv2.imwrite()

optimap.export_image(filename, image: ndarray, cmap='gray', vmin: float = None, vmax: float = None)[source]

Export an image to a file for publications, use save_image() to save an image if it will be reimported later.

Images will be converted to uint8, colormap will be applied to grayscale images.

The file format is inferred from the filename extension.

Parameters:
  • filename (str or pathlib.Path) – Path to save image to

  • image (np.ndarray) – Image to save HxW or HxWxC

  • cmap (str or matplotlib.colors.Colormap, optional) – Colormap to use for grayscale images, by default “gray”

  • vmin (float, optional) – Minimum value for the colormap, by default None

  • vmax (float, optional) – Maximum value for the colormap, by default None

optimap.save_image_sequence(directory: str | Path, video: ndarray, filepattern: str = 'frame_{:03d}', format='.png', **kwargs)[source]

Save a video as a sequence of images.

This function will create a directory if it does not exist, and save each frame of the video as an image. The images are named according to the provided file pattern and format.

Example

import numpy as np
import optimap as om

video = np.random.rand(100, 100, 100)
om.save_image_sequence("my_folder", video, filepattern="frame_{:03d}", format=".png")

Will create a folder my_folder and save the images as my_folder/frame_000.png, my_folder/frame_001.png, etc.

Parameters:
  • directory (str or pathlib.Path) – Directory to save to

  • video (np.ndarray or list of np.ndarray) – The video to save as a sequence of images

  • filepattern (str) – The pattern to use for the filenames. The pattern should include a placeholder for the frame number, e.g., ‘frame_{:03d}’. Default is ‘frame_{:03d}’.

  • format (str) – Image format to save as, e.g., ‘.png’, ‘.jpg’, .tiff etc. Default is ‘.png’.

  • **kwargs (dict) – Additional arguments to pass to skimage.io.imsave() or tifffile.imwrite() (for .tiff files)

optimap.save_mask(filename, mask, image=None, **kwargs)[source]

Save a mask to a file.

Supports NPY, PNG, TIFF, … files.

For NPY files, the mask is saved as a boolean array. For image files (PNG, TIFF, …), the mask is saved as the alpha channel of the image (if given). If no image is given, the mask is saved as a grayscale image.

See load_mask() to load the mask again.

Parameters:
  • filename (str or pathlib.Path) – Path to save mask to

  • mask (np.ndarray) – 2D bool mask to save

  • image (np.ndarray, optional) – Image to save. If given, the mask will be saved as the alpha channel of the image. Only supported for .png and .tif files.

  • **kwargs (dict, optional) – passed to np.save() (for .npy) or cv2.imwrite() (else)

optimap.save_video(filename, video, **kwargs)[source]

Save a video to a file. Supported file formats are .npy, .tif/.tiff, and .mat.

See save_tiff_folder() for saving a video as a folder of .tiff images.

See export_video() for exporting a video to a movie file (e.g. .mp4).

Parameters:
  • filename (str or pathlib.Path) – Filename to save to

  • video (np.ndarray) – Video to save

  • **kwargs (dict) – Additional arguments to pass to the respective save function

optimap.export_video(filename: str | Path, video: ndarray | Iterable[ndarray], fps: int = 60, skip_frames: int = 1, cmap='gray', vmin: float = None, vmax: float = None, progress_bar: bool = True, ffmpeg_encoder: str = None, pad_mode: str = 'edge')[source]

Export a video numpy array to a video file (e.g. .mp4) using ffmpeg.

Downloads pre-built ffmpeg automatically if ffmpeg is not installed.

Example

import optimap as om
import numpy as np

video = np.random.rand(100, 100, 100)
om.export_video("video.mp4", video, fps=30, cmap="viridis")
Parameters:
  • filename (str or Path) – Video file path for writing.

  • video (np.ndarray or Iterable[np.ndarray]) – The video to export. Should be of shape (frames, height, width, channels) or (frames, height, width). If the video is grayscale, the colormap will be applied. If it’s an RGB video, its values should range [0, 1] or [0, 255] (np.uint8).

  • fps (int, optional) – The framerate of the output video, by default 60

  • skip_frames (int, optional) – Only export every skip_frames frames, by default 1

  • cmap (str, optional) – The matplotlib colormap to use, by default “gray”

  • vmin (float, optional) – The minimum value for the colormap, by default None

  • vmax (float, optional) – The maximum value for the colormap, by default None

  • progress_bar (bool, optional) – Whether to show a progress bar, by default True

  • ffmpeg_encoder (str, optional) – The ffmpeg encoder to use, by default 'libx264'. See set_default_ffmpeg_encoder() and set_ffmpeg_defaults() for more information.

  • pad_mode (str, optional) – Odd-sized videos need to be padded to even dimensions, otherwise ffmpeg will error. The padding mode to use, by default “edge”. See numpy.pad() for more information.

optimap.export_videos(filename: str | Path, videos: ndarray | List[ndarray], ncols: int = 6, padding: int = 0, padding_color='black', fps: int = 60, skip_frames: int = 1, cmaps: str | List[str] = 'gray', vmins: float | List[float] = None, vmaxs: float | List[float] = None, ffmpeg_encoder: str = None, progress_bar: bool = True)[source]

Export a list of videos to a video file (e.g. .mp4) by arranging them side by side in a grid.

Uses optimap.image.collage() to arrange the video frames in a grid.

Example

import optimap as om
import numpy as np

videos = [
    np.random.rand(100, 100, 100),
    np.random.rand(100, 100, 100),
    np.random.rand(100, 100, 100),
    np.random.rand(100, 100, 100),
]

cmaps = ["gray", "viridis", "plasma", "inferno"]
om.export_videos("collage.mp4", videos, ncols=2, padding=10,
                        padding_color="white", cmaps=cmaps)
Parameters:
  • filename (str or Path) – Video file path for writing.

  • videos (np.ndarray or List[np.ndarray]) – The videos to export. Should be of shape (frames, height, width, channels) or (frames, height, width). If the video is grayscale, the colormap will be applied. If it’s an RGB video, its values should range [0, 1] or [0, 255] (np.uint8).

  • ncols (int, optional) – The number of columns in the collage, by default 6

  • padding (int, optional) – The padding between the videos in pixels, by default 0

  • padding_color (str or np.ndarray (np.uint8), optional) – The color of the padding, by default ‘black’

  • fps (int, optional) – The framerate of the output video, by default 60

  • skip_frames (int, optional) – Only export every skip_frames frame, by default 1

  • cmaps (str or List[str], optional) – The matplotlib colormap to use, by default “gray”

  • vmins (float or List[float], optional) – The minimum value for the colormap, by default None

  • vmaxs (float or List[float], optional) – The maximum value for the colormap, by default None

  • ffmpeg_encoder (str, optional) – The ffmpeg encoder to use, by default 'libx264'. See set_default_ffmpeg_encoder() and set_ffmpeg_defaults() for more information.

  • progress_bar (bool, optional) – Whether to show a progress bar, by default True

optimap.export_video_with_overlay(filename: str | Path, base: ndarray, overlay: ndarray, alpha: ndarray = None, fps: int = 60, skip_frames: int = 1, cmap_base='gray', cmap_overlay='Purples', vmin_base=None, vmax_base=None, vmin_overlay=None, vmax_overlay=None, ffmpeg_encoder=None, progress_bar: bool = True)[source]

Blends two videos together using alpha blending and exports it to a video file (e.g. .mp4).

The base video is blended with the overlay video using an alpha channel. If no alpha channel is provided, the overlay array is used as alpha channel (if it is grayscale) or the alpha channel of the overlay video is used (if it is RGBA). The alpha channel is expected to be in the range [0, 1], a value of 0 means that the base video is used, a value of 1 means that the overlay video is used.

Parameters:
  • filename (str or Path) – Video file path for writing.

  • base (np.ndarray) – The base video. Should be of shape (frames, height, width) or (frames, height, width, channels). Either uint8 or float32 (expected to be in the range [0, 1]).

  • overlay (np.ndarray) – The overlay video. Should be of shape (frames, height, width) or(frames, height, width, channels). Either uint8 or float32 (expected to be in the range [0, 1]).

  • alpha (np.ndarray, optional) – The alpha channel to use for blending, by default None. Expected to be in range [0, 1], and of shape (T, X, Y) or (X, Y). If None, the overlay array is used (if grayscale) or the alpha channel of the overlay video is used (if RGBA).

  • fps (int, optional) – The framerate of the output video, by default 60

  • skip_frames (int, optional) – Only export every skip_frames frames, by default 1

  • cmap_base (str or matplotlib.colors.Colormap, optional) – The colormap to use for the base video, by default 'gray'

  • cmap_overlay (str or matplotlib.colors.Colormap, optional) – The colormap to use for the overlay video, by default 'Purples'

  • vmin_base (float, optional) – The minimum value for the base video, by default None

  • vmax_base (float, optional) – The maximum value for the base video, by default None

  • vmin_overlay (float, optional) – The minimum value for the overlay video, by default None

  • vmax_overlay (float, optional) – The maximum value for the overlay video, by default None

  • ffmpeg_encoder (str, optional) – The ffmpeg encoder to use, by default 'libx264'. See set_default_ffmpeg_encoder() and set_ffmpeg_defaults() for more information.

  • progress_bar (bool, optional) – Whether to show a progress bar, by default True

optimap.extract_traces(video, coords, size=5, show=False, window=None, **kwargs)[source]

Extract trace or traces from a video at specified coordinates.

Multiple coordinates can be provided, and the averaging method for trace extraction can be selected.

Warning

Coordinates are given as (y, x) tuples, not (x, y) tuples to be consistent with matplotlib convention (origin of image in the top left corner). E.g. the coordinate (5, 10) is equivalent to img[10, 5] in numpy.

Different averaging window types of traces:

  • ‘rect’ - rectangle around the coordinates of size (size, size). This is the default option, see set_default_trace_window() to change the default. Note that if size is even the rectangle is shifted by one pixel to the top left, as there is no center pixel.

  • ‘disc’ - disc around the coordinates with diameter size

  • ‘pixel’ - only the pixel at the coordinates (equivalent to size=1)

Parameters:
  • video (3D array) – Video to extract traces from

  • coords (tuple or list of tuples) – Coordinates of the traces

  • size (int, optional) – Size parameter for selection mask, by default 5px. If 0, only the pixel trace is returned.

  • show (bool, optional) – Whether to show the traces using show_traces(), by default False

  • window (str, optional) – Type of trace, by default ‘rect’ ‘rect’ - rectangle around the coordinates ‘disc’ - disc around the coordinates ‘pixel’ - only the pixel at the coordinates (equivalent to size=0)

  • **kwargs (dict) – Extra arguments for show_traces()

Returns:

2D array containing the extracted traces.

Return type:

ndarray

optimap.compare_traces(videos, coords=None, labels=None, colors=None, size=5, ref_frame=0, fps=None, title=None, legend_loc='outside upper center', x=None, axs=None)[source]

Compare traces of multiple videos.

If coords is given, traces are plotted at the given coordinates. Otherwise, an interactive window is opened to select coordinates by clicking on the image. Close the interactive window to finish.

Parameters:
  • videos (list of 3D arrays) – List of videos to compare

  • coords (tuple or list of tuples) – Coordinates of the traces

  • labels (list of strings, optional) – List of labels for the videos, by default None

  • colors (list of colors, optional) – Colors for the traces, has to be the same length as videos, by default None

  • size (int, optional) – Size parameter of the trace, by default 5

  • ref_frame (int, optional) – Reference frame of the first video to show, by default 0 Only used if coords is None

  • fps (float, optional) – Sampling rate of the traces (frames per second), by default None. If passed x-axis is shown in seconds. x and fps cannot be passed at the same time.

  • title (str, optional) – Title of the plot, by default None

  • legend_loc (str, optional) – Location of the legend, by default “outside upper center”

  • x (1D array, optional) – X-axis values, by default None

  • axs (list of matplotlib.axes.Axes, optional) – Axes to plot on, by default None If not passed, a new figure is created. Only used if coords is not None.

optimap.select_positions(image, title='Click to select positions', num_points=None, as_integers=True, **kwargs)[source]

Interactive selection of positions on an image. Click on the image to select a position. Right click to remove a position. Close the window to finish.

If num_points is specified, the window will close automatically once that many points have been selected.

Parameters:
  • image (2D array) – Image to select positions from

  • title (str, optional) – Title for the figure, by default “Click to select positions”

  • num_points (int, optional) – Number of points to select before automatically closing, by default None

  • as_integers (bool, optional) – Return pixel coordinates if True, by default True

  • kwargs (dict, optional) – Additional keyword arguments for optimap.show_image()

Returns:

List of selected positions

Return type:

list of tuples

optimap.select_traces(video, size=5, ref_frame=0, x=None, fps=None)[source]

Interactive selection/plotting of traces from a video. Click on the image to select a position. Right click to remove a position. Close the window to finish.

Parameters:
  • video (3D np.ndarray) – Video to select traces from

  • size (int) – Size parameter for trace

  • ref_frame (int or np.ndarray) – Reference frame of the first video to show. If an integer, the frame is taken from the video. If an array, the array is used.

  • x (1D array, optional) – X-axis values, by default None. See show_traces() for details.

  • fps (float, optional) – Frames per second, by default None. See show_traces() for details.

Returns:

  • traces (2D np.ndarray) – Traces of the selected positions

  • positions (list of tuples) – List of selected positions

optimap.motion_compensate(video, contrast_kernel=7, ref_frame=0, presmooth_temporal=0.8, presmooth_spatial=0.8, postsmooth=None, method=None)[source]

Typical motion compensation pipeline for a optical mapping video.

First, the video is smoothed in space and time using a Gaussian kernel. Then, local contrast is enhanced to remove fluorescence signal. Finally, optical flow is estimated between every frame and a reference frame, and the video is warped to the reference frame using the estimated optical flow.

See motion.contrast_enhancement() and motion.estimate_displacements() for further details.

Parameters:
  • video (np.ndarray) – Video to estimate optical flow for (list of images or 3D array {t, x, y}). Can be any dtype because contrast enhancement will convert it to float32.

  • contrast_kernel (int, optional) – Kernel size for local contrast enhancement (must be odd), by default 7 See contrast_enhancement() for details.

  • ref_frame (int, optional) – Index of reference frame to estimate optical flow to, by default 0

  • presmooth_temporal (float, optional) – Standard deviation of smoothing Gaussian kernel in time, by default 0.8 See optimap.video.smooth_spatiotemporal() for details.

  • presmooth_spatial (float, optional) – Standard deviation of smoothing Gaussian kernel in space, by default 0.8 See optimap.video.smooth_spatiotemporal() for details.

  • postsmooth (tuple, optional) – Tuple of (wx, wy, wt) for Gaussian smoothing kernel in space and time, by default None. If None, no smoothing is applied. See smooth_displacements() for details.

  • show_progress (bool, optional) – Show progress bar, by default None

  • method (str, optional) – Optical flow method, See FlowEstimator class for list of available methods. By default None which means 'farneback' if a CUDA GPU is available and 'farneback_cpu' otherwise.

Returns:

Motion-compensated video of shape {t, x, y}

Return type:

np.ndarray

optimap.reverse_motion_compensate(video_tracking, video_warping, contrast_kernel=7, ref_frame=0, presmooth_temporal=0.8, presmooth_spatial=0.8, postsmooth=None, method=None)[source]

Typical motion tracking pipeline to transform a video back into motion. E.g. we first motion compensated a recording and extracted the fluorescence wave dynamics. We now want to transform the processed, motion-less, video back into motion and e.g. overlay it on-top the original video with video.play_with_overlay().

See motion_compensate() and estimate_reverse_displacements() for explanation of parameters and further details.

Parameters:
  • video_tracking (np.ndarray) – Video to estimate optical flow for (list of images or 3D array {t, x, y}). Can be any dtype.

  • video_warping (np.ndarray) – Video to be warped based on the motion of the video_tracking data.

  • contrast_kernel (int, optional) – Kernel size for local contrast enhancement (must be odd), by default 7 See contrast_enhancement() for details.

  • ref_frame (int, optional) – Index of reference frame to estimate optical flow to, by default 0

  • presmooth_temporal (float, optional) – Standard deviation of smoothing Gaussian kernel in time, by default 0.8 See optimap.video.smooth_spatiotemporal() for details.

  • presmooth_spatial (float, optional) – Standard deviation of smoothing Gaussian kernel in space, by default 0.8 See optimap.video.smooth_spatiotemporal() for details.

  • postsmooth (tuple, optional) – Tuple of (wx, wy, wt) for Gaussian smoothing kernel in space and time, by default None. If None, no smoothing is applied. See smooth_displacements() for details.

  • show_progress (bool, optional) – Show progress bar, by default None

  • method (str, optional) – Optical flow method, See FlowEstimator class for list of available methods. By default None which means 'farneback' if a CUDA GPU is available and 'farneback_cpu' otherwise.

Return type:

np.ndarray

optimap.interactive_mask(image, initial_mask=None, default_tool='draw', cmap='gray', title='', figsize=(7, 7))[source]

Create a mask interactively by drawing on an image.

Keyboard Shortcuts

Key

Action

Scroll

Zoom in/out

ctrl+z or cmd+z

Undo

ctrl+y or cmd+y

Redo

e

Erase mode

d

Draw/Lasso mode

v

Toggle mask visibility

i

Invert mask

q

Quit

Parameters:
  • image (2D ndarray) – Image to draw on.

  • initial_mask (2D ndarray, optional) – Mask to start with, by default None

  • default_tool (str, optional) – Default tool to use, by default “draw”. Can be one of draw or erase.

  • cmap (str, optional) – Colormap of the image, by default “gray”

  • title (str, optional) – Title of the image, by default “”

  • figsize (tuple, optional) – Figure size, by default (7, 7)

Returns:

mask – Created mask.

Return type:

2D ndarray

optimap.background_mask(image, threshold=None, show=True, return_threshold=False, **kwargs)[source]

Create a background mask for an image using a threshold.

If no threshold is given, the background threshold is detected using the GHT algorithm [Barron, 2020].

Parameters:
  • image (2D ndarray) – Image to create background mask for.

  • threshold (float or int, optional) – Background threshold, by default None

  • show (bool, optional) – Show the mask, by default True

  • return_threshold (bool, optional) – If True, return the threshold as well, by default False

  • kwargs (dict, optional) – Additional arguments passed to show_mask().

Returns:

  • mask (2D ndarray) – Background mask.

  • threshold (float or int) – Background threshold, only if return_threshold is True.

optimap.foreground_mask(image, threshold=None, show=True, return_threshold=False, **kwargs)[source]

Create a foreground mask for an image using thresholding.

If no threshold is given, the background threshold is detected using the GHT algorithm [Barron, 2020].

Parameters:
  • image (2D ndarray) – Image to create foreground mask for.

  • threshold (float or int, optional) – Background threshold, by default None

  • show (bool, optional) – Show the mask, by default True

  • return_threshold (bool, optional) – If True, return the threshold as well, by default False

  • kwargs (dict, optional) – Additional arguments passed to show_mask().

Returns:

  • mask (2D ndarray) – Foreground mask.

  • threshold (float or int) – Background threshold, only if return_threshold is True.

optimap.invert_mask(mask)[source]

Invert a binary mask.

Parameters:

mask (2D ndarray) – Binary mask.

Returns:

Inverted mask.

Return type:

2D ndarray

optimap.find_activations(signal, method='maximum_derivative', interpolate=False, falling_edge=False, show=True, fps=None, ax=None, **kwargs)[source]

Computes activation times or detects activation events using different methods.

A versatile function that identifies when activation events occur in time series data.

Two different methods are available:

  1. maximum_derivative: Computes activation times based the peaks in the temporal derivative of the signal \(dV/dt\). See optimap.activation.find_activations_dvdt() for details.

  2. threshold_crossing: Computes activation times based on the signal crossing a specified threshold in desired direction. See optimap.activation.find_activations_threshold() for details.

The function can handle 1D signals, 2D traces (T, N), or 3D videos (averaged over all spatial dimensions to compute 1D signal).

If falling_edge is set to True, it expects negative activation (i.e., the signal falls below the threshold).

By default, the function returns the _closest_ frame index to the condition. If interpolate is set to True, the function will return a fractional frame using interpolation.

Parameters:
  • signal (np.ndarray) – The 1D signal.

  • method (str) – The method to use for finding activations. Options are “maximum_derivative” or “threshold”.

  • falling_edge (bool) – If True, find activations which go negative (falling edge).

  • interpolate (bool) – If True, use linear interpolation to find the exact crossing point.

  • threshold (float) – If method='threshold_crossing', the threshold value.

  • min_duration (int) – If method='threshold_crossing', the minimum duration of the crossing in frames. If set to 0, all crossings are returned.

  • prominence (float) – If method='maximum_derivative', the required prominence of peaks. If None, it will be calculated automatically based on the signal’s derivative statistics.

  • height (float) – If method='maximum_derivative', the minimum height of peaks. Default is None.

  • min_distance (int) – If method='maximum_derivative', the minimum distance between detected peaks in frames. Default is 10.

  • window_size (int) – If method='maximum_derivative', the size of the window used for derivative calculation. Default is 5.

  • show (bool) – If True, the resulting activation times will be displayed.

  • fps (float) – Frames per second for time conversion for plotting.

  • ax (matplotlib.axes.Axes) – Axes on which to plot. If None, a new figure and axes is created.

  • **kwargs (dict) – Additional arguments passed to the underlying activation detection functions.

Returns:

activations – Detected activation times.

Return type:

ndarray

optimap.compute_activation_map(video, method='maximum_derivative', falling_edge=False, interpolate=False, threshold=0.5, normalize_time=True, set_nan_for_inactive=True, show=True, **kwargs)[source]

Computes an activation map (or isochrone map) of local activation times from a video.

The activation map is a 2D image where each pixel represents the time (in terms of frame index) at which the pixel is considered activated.

The activation time is determined by find_activations() based on the specified method, which can be either “threshold_crossing” or “maximum_derivative”.

  • threshold_crossing: The activation time is the first frame where the pixel intensity surpasses a specified threshold.

  • maximum_derivative: The activation time is the where the maximum of the temporal derivative of the pixel intensity occurs.

Note

For the threshold_crossing method the video should be normalized to the range [0, 1]. This is not required for the maximum_derivative method.

For negative polarity signals (i.e. inverted action potentials), set falling_edge=True. The activation map is return in terms of discrete frame indices, if interpolate=True fractions of frames are returned. If normalize_time=True (default), the minimum activation time across all pixels will be subtracted from the activation times.

See find_activations() for further details and show_activation_map() for plotting.

Parameters:
  • video (np.ndarray) – A 3D array representing the video, with dimensions {t (time or frames), x (width), y (height)}.

  • method (str, optional) – Method to compute activation times. Options are “threshold_crossing” or “maximum_derivative”. Defaults to “maximum_derivative”.

  • falling_edge (bool, optional) – If True, the function will compute the time/frame when pixel intensity falls below the threshold, rather than surpassing it. Defaults to False.

  • interpolate (bool, optional) – If True, use linear interpolation to find the exact crossing point between frames. Defaults to False.

  • threshold (float, optional) – Intensity threshold for threshold_crossing method at which a pixel is considered activated. Defaults to 0.5.

  • normalize_time (bool, optional) – If True, the minimum activation time across all pixels will be subtracted from the activation times. Defaults to True.

  • set_nan_for_inactive (bool, optional) – If True, pixels that never reach the activation threshold or meet all the criteria will be set to NaN. If False, set to np.inf. Defaults to True.

  • show (bool, optional) – If True, the resulting activation map will be displayed. Defaults to True.

  • **kwargs (dict, optional) – Additional arguments passed to show_activation_map().

Returns:

activation_map – 2D image of activation times

Return type:

ndarray

optimap.show_activation_map(activation_map, vmin=0, vmax=None, fps=None, cmap='turbo', title='', show_contours=False, show_map=True, show_colorbar=True, colorbar_title=None, ax=None, contour_fmt=None, contour_levels=None, contour_fontsize=None, contour_linestyles=None, contour_args={}, contour_label_args={})[source]

Display an activation/isochrone map with optional contours.

Creates a color-coded visualization of activation timing across a 2D spatial region. Optional contour lines can be added to highlight regions that activate at the same time (isochrones).

Parameters:
  • activation_map (2D ndarray) – The activation map to display. Values represent activation times.

  • vmin (float, optional) – Minimum value for the colormap, by default 0

  • vmax (float, optional) – Maximum value for the colormap, by default None (auto-determined from data)

  • fps (float, optional) – Show activation map times in milliseconds based on this frame rate, otherwise, it will be in frames.

  • cmap (str, optional) – Colormap to use for the activation map, by default “turbo”

  • title (str, optional) – Title for the plot, by default “”

  • show_contours (bool, optional) – Whether to overlay contour lines on the activation map, by default True

  • show_map (bool, optional) – Whether to display the activation map, by default True

  • show_colorbar (bool, optional) – Whether to display a colorbar, by default True

  • colorbar_title (str, optional) – Title for the colorbar, by default “Activation Time [ms]” if fps is provided, otherwise “Activation Time [frames]”

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure and axes is created, by default None

  • contour_fontsize (int or float, optional) – Font size for contour labels, by default None (auto-determined)

  • contour_fmt (str, optional) – Format string for contour labels e.g. ' %1.0f ms ', by default None. See matplotlib.pyplot.clabel() for details.

  • contour_levels (array-like, optional) – Specific contour levels to draw, by default None (auto-determined). See matplotlib.pyplot.contour() for details.

  • contour_linestyles (str or list of str, optional) – Line style(s) for contour lines, by default None. See matplotlib.pyplot.contour() for details.

  • contour_args (dict, optional) – Additional keyword arguments for matplotlib’s contour function, by default {}

  • contour_label_args (dict, optional) – Additional keyword arguments for contour label formatting, by default {}

Returns:

The axes containing the plot

Return type:

matplotlib.axes.Axes

See also

compute_activation_map

For creating activation maps from video data

optimap.compute_cv(activation_map, positions=None, fps=None, space_scale=None, show=True, **kwargs)[source]

Compute conduction velocity (CV) between pairs of positions on an activation map.

The conduction velocity is calculated as the spatial distance between two points divided by the difference in activation times at those points.

Parameters:
  • activation_map (2D array) – Activation map where values represent activation times in frames

  • positions (list or ndarray, optional) –

    Position data in one of the following formats:

    • None: Interactive prompt to select two points (default)

    • List of N pairs of points: [(x1, y1), (x2, y2), (x3, y3), (x4, y4), …]

    • NumPy array with shape (N, 2, 2)

  • fps (float, optional) – Frames per second. If provided, converts time units from frames to seconds

  • space_scale (float, optional) – Spatial scale in mm/px. If provided, converts spatial units from pixels to cm

  • show (bool, optional) – Whether to display a plot showing the activation map and computed CV, by default True

  • **kwargs (dict, optional) – Additional keyword arguments passed to the select_cv_positions function if positions=None

Returns:

Array of N conduction velocities.

Units depend on fps and space_scale:
  • pixels/frame if both fps and space_scale are None

  • pixels/s if only fps is provided

  • cm/s if both fps and space_scale are provided

Return type:

float or ndarray

Examples

>>> # Computing CV with user-selected points
>>> cv = compute_cv(activation_map)
>>>
>>> # Computing CV with specific points in physical units
>>> cv = compute_cv(activation_map,
...                 positions=[(10, 15), (40, 30)],
...                 fps=500,  # 500 frames/s
...                 space_scale=10)  # 10 mm/px
optimap.compute_cv_map(activation_map, method='bayly', fps=None, space_scale=None, show=True, vmin=0, vmax=None, **kwargs)[source]

Computes the local conduction velocity (CV) map from an activation map.

Parameters:
  • activation_map (np.ndarray) – 2D NumPy array where each pixel represents the activation time. NaN values mean no activation.

  • method (str) – The method to use for computing the CV cmp. Currently only ‘bayly’ is supported.

  • fps (float) – Frames per second. If provided, converts time units from frames to seconds.

  • space_scale (float) – Spatial scale in mm/px. If provided, converts spatial units from pixels to cm.

  • show (bool) – Whether to display a plot showing the activation map and computed CV map.

Returns:

Array of shape (rows, cols, 2) where the last dimension contains the x and y components of the local CV at each point.

Return type:

np.ndarray

See also

compute_cv

Computes the conduction velocity between pairs of points.

compute_velocity_field

Computes the velocity field from an activation map.

optimap.compute_velocity_field(activation_map, method='bayly', **kwargs)[source]

Computes the velocity field from an isochronal activation map.

This function serves as a wrapper to call different algorithms for computing the velocity field, which represents the direction and magnitude (speed) of activation wavefront propagation at each point in the map.

Available methods:
  • 'bayly': Uses local second-order polynomial fitting to estimate the gradient of activation time and derive velocity. Use window_size parameter to … See compute_velocity_field_bayly() and Bayly et al. [1998].

  • 'circle': Employs activation time differences across diameters of a local circle to determine velocity. Use radius parameter to … See compute_velocity_field_circle() and Siles-Paredes et al. [2022].

  • 'gradient': Calculates velocity directly from the smoothed spatial gradient of the activation map (\(\\vec{v} = \\nabla T / |\\nabla T|^2\)). Simple and fast, but can be sensitive to noise and sharp gradients. See compute_velocity_field_gradient().

Parameters:
  • activation_map (np.ndarray) – 2D NumPy array where each pixel represents the activation time.

  • method (str) – Method to compute the velocity field. Options are: [‘bayly’, ‘circle’, ‘gradient’].

  • **kwargs (dict) – Additional parameters for the selected method.

  • activation_map – 2D NumPy array where each pixel represents the activation time.

  • method – Method to compute the velocity field. Options are: [‘bayly’, ‘circle’, ‘gradient’].

  • **kwargs – Additional parameters for the selected method.

Returns:

3D NumPy array of shape (rows, cols, 2)

Return type:

np.ndarray

optimap.compute_phase(video, offset=-0.5)[source]

Computes phase using Hilbert transformation, takes a normalized video or time-series as input.

Parameters:
  • video ({t, x, y} ndarray) – normalized video

  • offset (float) – offset to add to video before computing phase, default is -0.5

Returns:

phase in range [-pi, pi]

Return type:

{t, x, y} ndarray

optimap.download_example_data(name, known_hash=None, directory='./optimap_example_data', silent=False)[source]

Download example data if not already present.

See Example Data Files for list of files. Accepts also an URL to a file to download. See pooch.retrieve() for more information.

If file is a zip file, it will be unzipped after download.

Parameters:
  • name (str) – Name of the file to download.

  • known_hash (str, optional) – Hash of the file to download. If None, lookup if file is known in FILE_HASHES.

  • directory (str) – Directory to download the file to.

  • silent (bool) – If True, set logging level to WARNING.

Returns:

Path to the file.

Return type:

str

optimap.set_verbose(state=True)[source]

Set verbosity of optimap.

Parameters:

state (bool) – If True, optimap will print more information.

optimap.is_verbose()[source]

Returns whether optimap is verbose.

Returns:

Whether optimap is verbose.

Return type:

bool

optimap.print_bar(force=False)[source]

Print a bar to separate sections of output.

optimap.print_properties(array: ndarray)[source]

Print properties of an array.