optimap.imageΒΆ

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

optimap.image.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.image.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.image.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.image.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.image.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.image.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.image.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.image.resize(image, shape=None, scale=None, interpolation='cubic')[source]ΒΆ

Resize image.

Either shape or scale parameter must be specified.

Interpolation methods:
  • nearest: nearest neighbor interpolation

  • linear: bilinear interpolation

  • cubic: bicubic interpolation

  • area: resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the β€œnearest” method.

  • lanczos: a Lanczos interpolation over 8x8 neighborhood

Parameters:
  • image (image_like) – Image to resize. Either grayscale or RGB(A)

  • shape ((new_x, new_y) tuple) – Shape of the desired image

  • scale (float) – Scale factor to apply to image, e.g. 0.5 for half the size

  • interpolation (str, optional) – Interpolation method to use, by default β€œcubic”. See above for available methods.

Returns:

Resized image.

Return type:

2D np.ndarray

optimap.image.rotate_left(image, k=1)[source]ΒΆ

Rotate image by 90Β° counter-clockwise (left).

Parameters:
  • image ({x, y} ndarray) – Image to rotate.

  • k (int, optional) – Number of times to rotate by 90Β°, by default 1

Returns:

Rotated image.

Return type:

{y, x} ndarray

optimap.image.rotate_right(image, k=1)[source]ΒΆ

Rotate image by 90Β° clockwise (right).

Parameters:
  • image ({x, y} ndarray) – Image to rotate.

  • k (int, optional) – Number of times to rotate by 90Β°, by default 1

Returns:

Rotated image.

Return type:

{y, x} ndarray

optimap.image.flip_left_right(image)[source]ΒΆ

Flip image left-right.

Parameters:

image ({x, y} ndarray) – Image to flip.

Returns:

Flipped image.

Return type:

{x, y} ndarray

optimap.image.flip_up_down(image)[source]ΒΆ

Flip image up-down.

Parameters:

image ({x, y} ndarray) – Image to flip.

Returns:

Flipped image.

Return type:

{x, y} ndarray

optimap.image.crop(image, width)[source]ΒΆ

Crop image by width pixels on each side.

Parameters:
  • image ({x, y} ndarray) – Image to crop.

  • width (int) – Width of crop.

Return type:

{x-2*width, y-2*width} ndarray

optimap.image.pad(image, width, mode='constant', **kwargs)[source]ΒΆ

Pad image by width pixels on each side.

Parameters:
  • image ({x, y} ndarray) – Image to pad.

  • width (int) – Width of padding.

  • mode (str, optional) – Padding mode, by default β€˜constant’. See numpy.pad() for details and additional keyword arguments.

  • **kwargs (dict, optional) – Additional keyword arguments passed to numpy.pad().

Return type:

{x+2*width, y+2*width} ndarray

optimap.image.normalize(array: ~numpy.ndarray, ymin=0, ymax=None, vmin=None, vmax=None, dtype=<class 'numpy.float32'>, clip=True)[source]ΒΆ

Normalize an array (video, image, …) to a specified range and data type.

By default, the input will be normalized to the interval [0, 1] with type np.float32 based on the minumum and maximum value of the input array.

If parameters vmin or vmax are specified, the normalization is performed using these values and the resulting array will be clipped.

The parameters ymin and ymax specify the minimum and maximum values of the resulting array, by default 0 and 1 if dtype is a floating point type, or the maximum value of the data type if dtype is an integer type.

Examples

import optimap as om
import numpy as np

filepath = om.download_example_data("Sinus_Rabbit_1.npy")
video = om.load_video(filepath)

# normalize video to interval [0, 1] using the minimum and maximum values of the video
video_normalized = om.video.normalize(video)

# normalize video to interval [0, 255] by converting the video to uint8
video_normalized_uint8 = om.video.normalize(video, ymin=0, ymax=255, dtype=np.uint8)
Parameters:
  • array (ndarray) – The input array to be normalized.

  • ymin (float, optional) – Minimum value of the resulting video, by default 0

  • ymax (float, optional) – Maximum value of the resulting video, by default 1 for floating point arrays, or the maximum value of the data type for integer arrays.

  • vmin (float, optional) – Minimum value of the input video, by default None If None, the minimum value of the input video is calculated.

  • vmax (float, optional) – Maximum value of the input video, by default None If None, the maximum value of the input video is calculated.

  • dtype (type, optional) – Data type of the resulting array, by default np.float32

  • clip (bool, optional) – If True, the resulting video will be clipped to [ymin, ymax], by default True Only applies if vmin or vmax are specified.

Returns:

Normalized array/video/image.

Return type:

ndarray

optimap.image.collage(images, ncols=6, padding=0, padding_value=0)[source]ΒΆ

Create a collage from a list or array of images/masks that have the same shape.

Creates a numpy array with the images arranged in a grid, with a specified number of images per row. Optionally, padding can be added between the images.

See export_videos() to save a video collage to a video file.

Parameters:
  • images (np.ndarray or list of np.ndarray) – List of grayscale or RGB(A) images to combine

  • ncols (int, optional) – Number of images per row, by default 6

  • padding (int, optional) – Spacing between images in pixels, by default 0

  • padding_value (float or np.ndarray, optional) – Value for the spacing (e.g. color RGB(A) array), by default 0

Returns:

Collage image

Return type:

np.ndarray

Examples

import optimap as om
import numpy as np

# create a collage of 3x3 random images
images = [np.random.rand(100, 100) for _ in range(9)]
collage = om.image.collage(images, ncols=3, padding=10)
om.image.show_image(collage)
optimap.image.smooth_gaussian(image, sigma, **kwargs)[source]ΒΆ

Smooth an image or mask using a Gaussian filter.

Uses scipy.ndimage.gaussian_filter() internally with mode='nearest'.

Parameters:
optimap.image.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.image.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.image.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.image.detect_background_threshold(image)[source]ΒΆ

Detect the background threshold of an image using the GHT algorithm [Barron, 2020].

Parameters:

image (np.ndarray) – Image to detect background threshold for.

Returns:

Background threshold.

Return type:

float or int

optimap.image.invert_mask(mask)[source]ΒΆ

Invert a binary mask.

Parameters:

mask (2D ndarray) – Binary mask.

Returns:

Inverted mask.

Return type:

2D ndarray

optimap.image.erode_mask(binary_mask, iterations=1, border_value=0, structure=None, show=True, **kwargs)[source]ΒΆ

Erode a binary mask.

Parameters:
  • binary_mask (2D ndarray) – Binary mask.

  • iterations (int, optional) – Number of iterations, by default 1

  • border_value (int, optional) – Value of the border, by default 0

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

  • structure (array_like, optional) – Structuring element used for the erosion. See scipy documentation for more information.

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

Returns:

Eroded mask.

Return type:

2D ndarray

optimap.image.dilate_mask(binary_mask, iterations=1, border_value=0, structure=None, show=True, **kwargs)[source]ΒΆ

Dilate a binary mask.

Parameters:
  • binary_mask (2D ndarray) – Binary mask.

  • iterations (int, optional) – Number of iterations, by default 1

  • border_value (int, optional) – Value of the border, by default 0

  • structure (array_like, optional) –

    Structuring element used for the erosion. See scipy documentation for more information.

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

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

Returns:

Dilated mask.

Return type:

2D ndarray

optimap.image.largest_mask_component(mask: ndarray, invert: bool = False, show=True, **kwargs)[source]ΒΆ

Identify and return the largest connected component (island) in a given binary mask.

This function labels distinct unconnected regions (or islands) in a binary mask and returns the largest one in terms of pixel count. Optionally, the mask can be inverted before processing and then inverted back before returning the result.

Parameters:
  • mask (2D ndarray) – Binary mask.

  • invert (bool, optional) – If set to True, the mask is inverted before processing and then inverted back before returning the result. This can be useful if the area of interest is represented by False in the original mask. Default is False.

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

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

Returns:

Largest island.

Return type:

2D ndarray

optimap.image.fill_mask(binary_mask, structure=None, show=True, **kwargs)[source]ΒΆ

Fill holes in a binary mask.

Parameters:
  • binary_mask (2D ndarray) – Binary mask.

  • structure (array_like, optional) –

    Structuring element used for the erosion. See scipy documentation for more information.

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

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

Returns:

Mask with filled holes.

Return type:

2D ndarray

optimap.image.disc_mask(shape, center, radius)[source]ΒΆ

Create a circular/disk shaped mask.

Parameters:
  • shape (tuple) – Shape of the mask.

  • center (tuple) – Center of the circle in (x, y) format. TODO: check if this is correct, or if it should be (y, x)?

  • radius (float) – Radius of the circle.

Returns:

mask – Mask.

Return type:

2D ndarray

optimap.image.open_mask(binary_mask, iterations=1, border_value=0, structure=None, show=True, **kwargs)[source]ΒΆ

Perform binary opening on a binary mask. Consists of an erosion followed by a dilation.

Parameters:
  • binary_mask (2D ndarray) – Binary mask.

  • iterations (int, optional) – Number of iterations, by default 1

  • border_value (int, optional) – Value of the border, by default 0

  • structure (array_like, optional) –

    Structuring element used for the erosion. See scipy documentation for more information.

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

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

Returns:

Mask after binary opening.

Return type:

2D ndarray

optimap.image.close_mask(binary_mask, iterations=1, border_value=0, structure=None, show=True, **kwargs)[source]ΒΆ

Perform binary closing on a binary mask. Consists of a dilation followed by an erosion.

Parameters:
  • binary_mask (2D ndarray) – Binary mask.

  • iterations (int, optional) – Number of iterations, by default 1

  • border_value (int, optional) – Value of the border, by default 0

  • structure (array_like, optional) –

    Structuring element used for the erosion. See scipy documentation for more information.

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

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

Returns:

Mask after binary closing.

Return type:

2D ndarray