skimage.util
Generic utilities.
This module contains a number of utility functions to work with images in general.
Map a function in parallel across an array. | |
Return an image showing the differences between two images. |
Generic utilities.
This module contains a number of utility functions to work with images in general.
Map a function in parallel across an array. | |
Return an image showing the differences between two images. |
Crop array |
Return intensity limits, i.e. (min, max) tuple, of the image's dtype. |
Convert an image to boolean format. |
Convert an image to floating point format. |
Convert an image to single-precision (32-bit) floating point format. |
Convert an image to double-precision (64-bit) floating point format. |
Convert an image to 16-bit signed integer format. |
Convert an image to 8-bit unsigned integer format. |
Convert an image to 16-bit unsigned integer format. |
Invert an image. |
Assign unique integer labels to coordinates on an image mask |
Do a keyword search on scikit-image docstrings and print results. |
Map values from input array from input_vals to output_vals. |
Create a montage of several single- or multichannel images. |
Function to add random noise of various types to a floating-point image. |
Find |
Return an image with ~`n_points` regularly-spaced nonzero pixels. |
Slice an image along given axes. |
Remove repeated rows from a 2D array. |
Block view of the input n-dimensional array (using re-striding). |
Rolling window view of the input n-dimensional array. |
Error from use of failed estimation instance |
A warning about API usage that will silently change or break in skimage2. |
Map a function in parallel across an array.
Split an array into possibly overlapping chunks of a given depth and boundary type, call the given function in parallel on the chunks, combine the chunks and return the resulting array.
Function to be mapped which takes an array as an argument.
Array which the function will be applied to.
A single integer is interpreted as the length of one side of a square
chunk that should be tiled across the array. One tuple of length
array.ndim represents the shape of a chunk, and it is tiled across
the array. A list of tuples of length ndim, where each sub-tuple
is a sequence of chunk sizes along the corresponding dimension. If
None, the array is broken up into chunks based on the number of
available cpus. More information about chunks is in the documentation
here. When
is not None, the tuples can be length and
a single chunk will be used along the channel axis.
Return an image showing the differences between two images.
Images to process, must be of the same shape.
Method used for the comparison. Details are provided in the note section.
Used only for the checkerboard method. Specifies the number
of tiles (row, column) to divide the image.
Image showing the differences.
'diff' computes the absolute difference between the two images.
'blend' computes the mean value.
'checkerboard' makes tiles of dimension n_tiles that display
alternatively the first and the second image. Note that images must be
2-dimensional to be compared with the checkerboard method.
Crop array ar by crop_width along each dimension.
Input array.
Number of values to remove from the edges of each axis.
((before_1, after_1), … (before_N, after_N)) specifies
unique crop widths at the start and end of each axis.
((before, after),) or (before, after) specifies
a fixed start and end crop for every axis.
(n,) or n for integer n is a shortcut for
before = after = n for all axes.
If True, ensure the returned array is a contiguous copy. Normally,
a crop operation will return a discontiguous view of the underlying
input array.
If copy==True, control the memory layout of the copy. See
np.copy.
The cropped array. If copy=False (default), this is a sliced
view of the input array.
Return intensity limits, i.e. (min, max) tuple, of the image’s dtype.
Input image.
If True, clip the negative range (i.e. return 0 for min intensity) even if the image dtype allows negative values.
Lower and upper intensity limits.
Convert an image to boolean format.
Input image.
Force a copy of the data, irrespective of its current dtype.
bool_)Output image.
The upper half of the input dtype’s positive range is True, and the lower half is False. All negative values (if present) are False.
Convert an image to floating point format.
This function is similar to img_as_float64, but will not convert
lower-precision floating point arrays to float64.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
Convert an image to single-precision (32-bit) floating point format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
Convert an image to double-precision (64-bit) floating point format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
Convert an image to 16-bit signed integer format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The values are scaled between -32768 and 32767. If the input data-type is positive-only (e.g., uint8), then the output image will still only have positive values.
Convert an image to 8-bit unsigned integer format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
Negative input values will be clipped. Positive values are scaled between 0 and 255.
Convert an image to 16-bit unsigned integer format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
Negative input values will be clipped. Positive values are scaled between 0 and 65535.
Invert an image.
Invert the intensity range of the input image, so that the dtype maximum is now the dtype minimum, and vice-versa. This operation is slightly different depending on the input dtype:
unsigned integers: subtract the image from the dtype maximum
signed integers: subtract the image from -1 (see Notes)
floats: subtract the image from 1 (if signed_float is False, so we assume the image is unsigned), or from 0 (if signed_float is True).
See the examples for clarification.
Input image.
If True and the image is of type float, the range is assumed to be [-1, 1]. If False and the image is of type float, the range is assumed to be [0, 1].
Inverted image.
Ideally, for signed integers we would simply multiply by -1. However, signed integer ranges are asymmetric. For example, for np.int8, the range of possible values is [-128, 127], so that -128 * -1 equals -128! By subtracting from -1, we correctly map the maximum dtype value to the minimum.
>>> img = np.array([[100, 0, 200],
... [ 0, 50, 0],
... [ 30, 0, 255]], np.uint8)
>>> invert(
Use rolling-ball algorithm for estimating background intensity
Assign unique integer labels to coordinates on an image mask
An array of N coordinates with dimension D
The shape of the mask on which coords are labelled
A mask of zeroes containing unique integer labels at the coords
The labels are assigned to coordinates that are converted to integer and considered to start from 0.
Coordinates that are out of range of the mask raise an IndexError.
Negative coordinates raise a ValueError
>>> import numpy as np
>>> from skimage.util._label import label_points
>>> coords = np.array([[0, 1], [2, 2]])
>>> output_shape = (5, 5
Do a keyword search on scikit-image docstrings and print results.
Words to look for.
>>> import skimage as ski
>>> ski.util.lookfor('regular_grid')
Search results for 'regular_grid'
---------------------------------
skimage.util.regular_grid
Find `n_points` regularly spaced along `ar_shape`.
skimage.util.lookfor
Do a keyword search on scikit-image docstrings and print results.
Map values from input array from input_vals to output_vals.
The input label image.
The values to map from.
The values to map to.
input_arrThe output array. Will be created if not provided. It should
have the same dtype as output_vals.
input_arrThe array of mapped values.
If input_arr contains values that aren’t covered by input_vals, they
are set to 0.
>>> import numpy as np
>>> import skimage as ski
>>> ski.util.map_array(
... input_arr=np.array([[0, 2, 2, 0], [
Create a montage of several single- or multichannel images.
Create a rectangular montage from an input array representing an ensemble of equally shaped single- (gray) or multichannel (color) images.
For example, montage(arr_in) called with the following arr_in
1 | 2 | 3 |
will return
1 | 2 |
3 |
where the ‘*’ patch will be determined by the fill parameter.
An array representing an ensemble of K images of equal shape.
Value to fill the padding areas and/or the extra tiles in
the output array. Has to be float for single channel collections.
For multichannel collections has to be an array-like of shape of
number of channels. If mean, uses the mean value over all images.
Whether to rescale the intensity of each image to [0, 1].
>>> import numpy as np
>>> from skimage.util import montage
>>> arr_in = np.arange(3 * 2 * 2).reshape(3, 2, 2)
>>>
Gabors / Primary Visual Cortex “Simple Cells” from an Image
Function to add random noise of various types to a floating-point image.
Input image data. Will be converted to float.
One of the following strings, selecting the type of noise to add:
Gaussian-distributed additive noise.
Gaussian-distributed additive noise, with specified local variance
at each point of image.
Poisson-distributed noise generated from the data.
Replaces random pixels with 1.
Replaces random pixels with 0 (for unsigned images) or -1 (for signed images).
Replaces random pixels with either 1 or low_val, where low_val
is 0 for unsigned images or -1 for signed images.
Multiplicative noise using out = , where
is Gaussian noise with specified mean & variance.
numpy.random.Generator, int}, optionalPseudo-random number generator.
By default, a PCG64 generator is used (see numpy.random.default_rng()).
If rng is an int, it is used to seed the generator.
If True (default), the output will be clipped after noise is applied. This may be needed to maintain the proper image data range. If False, clipping is not applied, and the output may extend beyond the range [-1, 1].
Mean of random distribution. Used in ‘gaussian’ and ‘speckle’. Default : 0.
Variance of random distribution. Used in ‘gaussian’ and ‘speckle’. Note: variance = (standard deviation) ** 2. Default : 0.01
Array of positive floats, same shape as image, defining the local
variance at every image point. Used in ‘localvar’.
Proportion of image pixels to replace with noise on range [0, 1]. Used in ‘salt’, ‘pepper’, and ‘salt & pepper’. Default : 0.05
Proportion of salt vs. pepper noise for ‘s&p’ on range [0, 1]. Higher values represent more salt. Default : 0.5 (equal amounts)
Output floating-point image data on range [0, 1] or [-1, 1] if the
input image was unsigned or signed, respectively.
Speckle, Poisson, Localvar, and Gaussian noise may generate noise outside
the valid image range. The default is to clip (not alias) these values,
but they may be preserved by setting clip=False. Note that in this case
the output may contain values outside the ranges [0, 1] or [-1, 1].
Use this option with care.
Because of the prevalence of exclusively positive floating-point images in
intermediate calculations, it is not possible to intuit if an input is
signed based on dtype alone. Instead, negative values are explicitly
searched for. Only if found does this function assume signed input.
Unexpected results only occur in rare, poorly exposes cases (e.g. if all
values are above 50 percent gray in a signed image). In this event,
manually scaling the input to the positive domain will solve the problem.
The Poisson distribution is only defined for positive integers. To apply this noise type, the number of unique values in the image is found and the next round power of two is used to scale up the floating-point result, after which it is scaled back down to the floating-point image range.
To generate Poisson noise against a signed image, the signed image is temporarily converted to an unsigned image in the floating point domain, Poisson noise is generated, then it is returned to the original range.
Find n_points regularly spaced along ar_shape.
The returned points (as slices) should be as close to cubically-spaced as possible. Essentially, the points are spaced by the Nth root of the input array size, where N is the number of dimensions. However, if an array dimension cannot fit a full step size, it is “discarded”, and the computation is done for only the remaining dimensions.
The shape of the space embedding the grid. len(ar_shape) is the
number of dimensions.
The (approximate) number of points to embed in the space.
A slice along each dimension of ar_shape, such that the intersection
of all the slices give the coordinates of regularly spaced points.
>>> ar = np.zeros((20, 40))
>>> g = regular_grid(ar.shape, 8)
>>> g
(slice(5, None, 10), slice(5, None, 10))
>>> ar[g] = 1
>>> ar.sum()
Return an image with ~`n_points` regularly-spaced nonzero pixels.
The shape of the desired output image.
The desired number of nonzero points.
The desired data type of the output.
The desired image.
>>> regular_seeds((5, 5), 4)
array([[0, 0, 0, 0, 0],
[0, 1, 0, 2, 0],
[0, 0, 0, 0, 0],
[0, 3, 0, 4, 0],
[0, 0, 0, 0, 0]])
Slice an image along given axes.
Input image.
For each axis in axes, a corresponding 2-tuple
(min_val, max_val) to slice with (as with Python slices,
max_val is non-inclusive).
Axes corresponding to the limits given in slices. If None,
axes are in ascending order, up to the length of slices.
If True, ensure that the output is not a view of image.
The region of image corresponding to the given slices and axes.
>>> from skimage import data
>>> img = data.camera()
>>> img.shape
(512, 512)
>>> cropped_img = slice_along_axes(img, [(0, 100)])
>>> cropped_img.shape
(100, 512)
>>>
Remove repeated rows from a 2D array.
In particular, if given an array of coordinates of shape (Npoints, Ndim), it will remove repeated points.
The input array.
A copy of the input array with repeated rows removed.
ar is not two-dimensional.The function will generate a copy of ar if it is not
C-contiguous, which will negatively affect performance for large
input arrays.
>>> ar = np.array([[1, 0, 1],
... [0, 1, 0],
... [1, 0, 1]], np.uint8)
>>> unique_rows(
Block view of the input n-dimensional array (using re-striding).
Blocks are non-overlapping views of the input array.
Input array.
The shape of the block. Each dimension must divide evenly into the
corresponding dimensions of arr_in.
Block view of the input array.
>>> import numpy as np
>>> from skimage.util.shape import view_as_blocks
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
>>> A = np.arange(4*4*6).reshape(4,4,6)
>>> A
array([[[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]],
[[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41],
[42, 43, 44, 45, 46, 47]],
[[48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59],
Rolling window view of the input n-dimensional array.
Windows are overlapping views of the input array, with adjacent windows shifted by a single row or column (or an index of a higher dimension).
Input array.
Defines the shape of the elementary n-dimensional orthotope (better know as hyperrectangle [1]) of the rolling window view. If an integer is given, the shape will be a hypercube of sidelength given by its value.
Indicates step size at which extraction shall be performed. If integer is given, then the step is uniform in all dimensions.
(rolling) window view of the input array.
One should be very careful with rolling views when it comes to memory usage. Indeed, although a ‘view’ has the same memory footprint as its base array, the actual array that emerges when this ‘view’ is used in a computation is generally a (much) larger array than the original, especially for 2-dimensional arrays and above.
For example, let us consider a 3 dimensional array of size (100,
100, 100) of float64. This array takes about 8*100**3 Bytes for
storage which is just 8 MB. If one decides to build a rolling view
on this array with a window of (3, 3, 3) the hypothetical size of
the rolling view (if one was to reshape the view for example) would
be 8*(100-3+1)**3*3**3 which is about 203 MB! The scaling becomes
even worse as the dimension of the input array becomes larger.
>>> import numpy as np
>>> from skimage.util.shape import view_as_windows
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
>>> A = np.arange(10)
>>> A
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> window_shape = (3,)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(8, 3)
>>> B
array([[0, 1, 2],
>>> A = np.arange(5*4).reshape(5, 4)
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
>>> window_shape = (4, 3)
>>> B
Gabors / Primary Visual Cortex “Simple Cells” from an Image
Bases: AttributeError
Error from use of failed estimation instance
This error arises from attempts to use an instance of
FailedEstimation.
Exception.add_note(note) – add a note to the exception
attribute name
object
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
Bases: PendingDeprecationWarning
A warning about API usage that will silently change or break in skimage2.
As a subclass of PendingDeprecationWarning, this warning isn’t
shown by default. But it can be enabled with a warnings filter to prepare
for code changes related to skimage2 early on:
import warnings
import skimage as ski
warnings.filterwarnings(
action="default", category=ski.util.PendingSkimage2Change
)
Exception.add_note(note) – add a note to the exception
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
channel_axisndim - 1The depth of the added boundary cells. A tuple can be used to specify a
different depth per array axis. Defaults to zero. When channel_axis
is not None, and a tuple of length ndim - 1 is provided, a depth of
0 will be used along the channel axis.
Type of external boundary padding.
Tuple of arguments to be passed to the function.
Dictionary of keyword arguments to be passed to the function.
The data-type of the function output. If None, Dask will attempt to
infer this by calling the function on data of shape (1,) * ndim.
For functions expecting RGB or multichannel data this may be
problematic. In such cases, the user should manually specify this dtype
argument instead.
If True, compute eagerly returning a NumPy Array.
If False, compute lazily returning a Dask Array.
If None (default), compute based on array type provided
(eagerly for NumPy Arrays and lazily for Dask Arrays).
If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels.
Returns the result of the applying the operation.
Type is dependent on the compute argument.
Numpy edge modes ‘symmetric’, ‘wrap’, and ‘edge’ are converted to the
equivalent dask boundary modes ‘reflect’, ‘periodic’ and ‘nearest’,
respectively.
Setting compute=False can be useful for chaining later operations.
For example region selection to preview a result or storing large data
to disk instead of loading in memory.
The desired grid shape for the montage (ntiles_row, ntiles_column).
The default aspect ratio is square.
The size of the spacing between the tiles and between the tiles and the borders. If non-zero, makes the boundaries of individual images easier to perceive.
If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels.
Output array with input images glued together (including padding p).
nFull tutorial on calibrating Denoisers Using J-Invariance