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:
- 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:
- 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
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.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) orcv2.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
. 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.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 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.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
orvmax
are specified, the normalization is performed using these values and the resulting array will be clipped.The parameters
ymin
andymax
specify the minimum and maximum values of the resulting array, by default 0 and 1 ifdtype
is a floating point type, or the maximum value of the data type ifdtype
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 ifvmin
orvmax
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 withmode='nearest'
.- Parameters:
image ({X, Y} np.ndarray) β Image or mask to smooth
sigma (float) β Standard deviation of the Gaussian kernel
**kwargs (dict, optional) β passed to
scipy.ndimage.gaussian_filter()
- 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.
ΒΆ 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.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].
- 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.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