optimapΒΆ
Modules
Activation map computation module. |
|
Functions for loading, saving, and displaying images, and for creating masks. |
|
Motion estimation and compensation functions for optical mapping data. |
|
Functions for computing, filtering, and analyzing phase maps from videos, and for detecting phase singularities. |
|
Functions for extracting time-series from videos. |
|
General utility functions. |
|
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:
- 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
. Usescv2.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()
ornumpy.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 toTrue
.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:
- 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:
- 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 informationcolor (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:
- 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
andfps
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:
- 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, andoptimap.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:
- 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:
- 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:
- 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()
anditer_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:
- 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
andcv2.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 asmy_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()
ortifffile.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) orcv2.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 1cmap (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'
. Seeset_default_ffmpeg_encoder()
andset_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 1cmaps (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'
. Seeset_default_ffmpeg_encoder()
andset_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). IfNone
, 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 1cmap_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'
. Seeset_default_ffmpeg_encoder()
andset_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, seeset_default_trace_window()
to change the default. Note that ifsize
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 Falsewindow (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
andfps
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.
- 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()
andmotion.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.
ΒΆ Key
Action
Scroll
Zoom in/out
ctrl+z
orcmd+z
Undo
ctrl+y
orcmd+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
orerase
.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.
- optimap.set_verbose(state=True)[source]ΒΆ
Set verbosity of optimap.
- Parameters:
state (bool) β If True, optimap will print more information.