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)

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:

  • .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.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, x=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.

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

optimap.select_positions(image, as_integers=True)[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.

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

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

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) – Reference frame of the first video to show

  • 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 to use, by default None which means 'farneback' if a CUDA GPU is available, or 'farneback_cpu' otherwise

Returns:

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

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

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.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.compute_activation_map(video, threshold=0.5, inverted=False, fps=None, set_nan_for_inactive=True, show=True, cmap='jet')[source]ΒΆ

Computes an activation map (or isochrone map) from a given video based on pixel intensity thresholding.

For each pixel in the video, the function determines the time (or frame index) at which the pixel’s intensity first surpasses (or falls below, if inverted is set to True) the specified threshold.

If fps is specified, time is giving in milliseconds, otherwise, it is given in frames.

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

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

  • inverted (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.

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

  • set_nan_for_inactive (bool, optional) – If True, pixels that never reach the activation threshold will be set to NaN. Defaults to True.

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

  • cmap (str, optional) – Colormap to use for displaying the activation map. Defaults to β€˜jet’.

Returns:

activation_map – 2D image

Return type:

ndarray

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

Download example data if not already present.

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

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