Mask corresponding to a flood fill.
Starting at a specific seed_point, connected points equal or within tolerance of the seed value are found.
An n-dimensional array.
The point in image used as the starting point for the flood fill. If the image is 1D, this point may be given as an integer.
A structuring element used to determine the neighborhood of each evaluated pixel. It must contain only 1’s and 0’s, have the same number of dimensions as image. If not given, all adjacent pixels are considered as part of the neighborhood (fully connected).
A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is larger or equal to connectivity are considered neighbors. Ignored if selem is not None.
If None (default), adjacent values must be strictly equal to the initial value of image at seed_point. This is fastest. If a value is given, a comparison will be done at every point and if within tolerance of the initial value will also be filled (inclusive).
A Boolean array with the same shape as image is returned, with True values for areas connected to and equal (or within tolerance of) the seed point. All other values are False.
The conceptual analogy of this operation is the ‘paint bucket’ tool in many raster graphics programs. This function returns just the mask representing the fill.
If indices are desired rather than masks for memory reasons, the user can simply run numpy.nonzero on the result, save the indices, and discard this mask.
Fill connected ones with 5, with full connectivity (diagonals included):
Fill connected ones with 5, excluding diagonal points (connectivity 1):
Fill with a tolerance:


Perform flood filling on an image.
Starting at a specific seed_point, connected points equal or within tolerance of the seed value are found, then set to new_value.
An n-dimensional array.
The point in image used as the starting point for the flood fill. If the image is 1D, this point may be given as an integer.
New value to set the entire fill. This must be chosen in agreement with the dtype of image.
A structuring element used to determine the neighborhood of each evaluated pixel. It must contain only 1’s and 0’s, have the same number of dimensions as image. If not given, all adjacent pixels are considered as part of the neighborhood (fully connected).
A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to connectivity are considered neighbors. Ignored if selem is not None.
If None (default), adjacent values must be strictly equal to the value of image at seed_point to be filled. This is fastest. If a tolerance is provided, adjacent points with values within plus or minus tolerance from the seed point are filled (inclusive).
If True, flood filling is applied to image in place. If False, the flood filled result is returned without modifying the input image (default).
This parameter is deprecated and will be removed in version 0.19.0 in favor of in_place. If True, flood filling is applied to image inplace. If False, the flood filled result is returned without modifying the input image (default).
An array with the same shape as image is returned, with values in areas connected to and equal (or within tolerance of) the seed point replaced with new_value.
The conceptual analogy of this operation is the ‘paint bucket’ tool in many raster graphics programs.
Fill connected ones with 5, with full connectivity (diagonals included):
Fill connected ones with 5, excluding diagonal points (connectivity 1):
Fill with a tolerance:


Determine all maxima of the image with height >= h.
The local maxima are defined as connected sets of pixels with equal grey level strictly greater than the grey level of all pixels in direct neighborhood of the set.
A local maximum M of height h is a local maximum for which there is at least one path joining M with an equal or higher local maximum on which the minimal value is f(M) - h (i.e. the values along the path are not decreasing by more than h with respect to the maximum’s value) and no path to an equal or higher local maximum for which the minimal value is greater.
The global maxima of the image are also found by this function.
The input image for which the maxima are to be calculated.
The minimal height of all extracted maxima.
The neighborhood expressed as an n-D array of 1’s and 0’s. Default is the ball of radius 1 according to the maximum norm (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.)
The local maxima of height >= h and the global maxima. The resulting image is a binary image, where pixels belonging to the determined maxima take value 1, the others take value 0.
See also
Soille, P., “Morphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883.
We create an image (quadratic function with a maximum in the center and 4 additional constant maxima. The heights of the maxima are: 1, 21, 41, 61, 81
We can calculate all maxima with a height of at least 40:
The resulting image will contain 3 local maxima.


Determine all minima of the image with depth >= h.
The local minima are defined as connected sets of pixels with equal grey level strictly smaller than the grey levels of all pixels in direct neighborhood of the set.
A local minimum M of depth h is a local minimum for which there is at least one path joining M with an equal or lower local minimum on which the maximal value is f(M) + h (i.e. the values along the path are not increasing by more than h with respect to the minimum’s value) and no path to an equal or lower local minimum for which the maximal value is smaller.
The global minima of the image are also found by this function.
The input image for which the minima are to be calculated.
The minimal depth of all extracted minima.
The neighborhood expressed as an n-D array of 1’s and 0’s. Default is the ball of radius 1 according to the maximum norm (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.)
The local minima of depth >= h and the global minima. The resulting image is a binary image, where pixels belonging to the determined minima take value 1, the others take value 0.
See also
Soille, P., “Morphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883.
We create an image (quadratic function with a minimum in the center and 4 additional constant maxima. The depth of the minima are: 1, 21, 41, 61, 81
We can calculate all minima with a depth of at least 40:
The resulting image will contain 3 local minima.


Label connected regions of an integer array.
Two pixels are connected when they are neighbors and have the same value. In 2D, they can be neighbors either in a 1- or 2-connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor:
Image to label.
Consider all pixels with this value as background pixels, and label them as 0. By default, 0-valued pixels are considered as background pixels.
Whether to return the number of assigned labels.
Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If None, a full connectivity of input.ndim is used.
Labeled array, where all connected regions are assigned the same integer value.
Number of labels, which equals the maximum label index and is only returned if return_num is True.
See also
Christophe Fiorio and Jens Gustedt, “Two linear time Union-Find strategies for image processing”, Theoretical Computer Science 154 (1996), pp. 165-181.
Kensheng Wu, Ekow Otoo and Arie Shoshani, “Optimizing connected component labeling algorithms”, Paper LBNL-56864, 2005, Lawrence Berkeley National Laboratory (University of California), http://repositories.cdlib.org/lbnl/LBNL-56864


Find local maxima of n-dimensional array.
The local maxima are defined as connected sets of pixels with equal gray level (plateaus) strictly greater than the gray levels of all pixels in the neighborhood.
An n-dimensional array.
A structuring element used to determine the neighborhood of each evaluated pixel (True denotes a connected pixel). It must be a boolean array and have the same number of dimensions as image. If neither selem nor connectivity are given, all adjacent pixels are considered as part of the neighborhood.
A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to connectivity are considered neighbors. Ignored if selem is not None.
If True, the output will be a tuple of one-dimensional arrays representing the indices of local maxima in each dimension. If False, the output will be a boolean array with the same shape as image.
If true, plateaus that touch the image border are valid maxima.
If indices is false, a boolean array with the same shape as image is returned with True indicating the position of local maxima (False otherwise). If indices is true, a tuple of one-dimensional arrays containing the coordinates (indices) of all found maxima.
If allow_borders is false and any dimension of the given image is shorter than 3 samples, maxima can’t exist and a warning is shown.
See also
This function operates on the following ideas:
For each candidate:
Find local maxima by comparing to all neighboring pixels (maximal connectivity):
Find local maxima without comparing to diagonal pixels (connectivity 1):
and exclude maxima that border the image edge:


Find local minima of n-dimensional array.
The local minima are defined as connected sets of pixels with equal gray level (plateaus) strictly smaller than the gray levels of all pixels in the neighborhood.
An n-dimensional array.
A structuring element used to determine the neighborhood of each evaluated pixel (True denotes a connected pixel). It must be a boolean array and have the same number of dimensions as image. If neither selem nor connectivity are given, all adjacent pixels are considered as part of the neighborhood.
A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to connectivity are considered neighbors. Ignored if selem is not None.
If True, the output will be a tuple of one-dimensional arrays representing the indices of local minima in each dimension. If False, the output will be a boolean array with the same shape as image.
If true, plateaus that touch the image border are valid minima.
If indices is false, a boolean array with the same shape as image is returned with True indicating the position of local minima (False otherwise). If indices is true, a tuple of one-dimensional arrays containing the coordinates (indices) of all found minima.
See also
This function operates on the following ideas:
For each candidate:
Find local minima by comparing to all neighboring pixels (maximal connectivity):
Find local minima without comparing to diagonal pixels (connectivity 1):
and exclude minima that border the image edge:


Build the max tree from an image.
Component trees represent the hierarchical structure of the connected components resulting from sequential thresholding operations applied to an image. A connected component at one level is parent of a component at a higher level if the latter is included in the first. A max-tree is an efficient representation of a component tree. A connected component at one level is represented by one reference pixel at this level, which is parent to all other pixels at that level and to the reference pixel at the level above. The max-tree is the basis for many morphological operators, namely connected operators.
The input image for which the max-tree is to be calculated. This image can be of any type.
The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
Array of same shape as image. The value of each pixel is the index of its parent in the ravelled array.
The ordered pixel indices (referring to the ravelled array). The pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent).
Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive Connected Operators for Image and Sequence Processing. IEEE Transactions on Image Processing, 7(4), 555-570. DOI:10.1109/83.663500
Berger, C., Geraud, T., Levillain, R., Widynski, N., Baillard, A., Bertin, E. (2007). Effective Component Tree Computation with Application to Pattern Recognition in Astronomical Imaging. In International Conference on Image Processing (ICIP) (pp. 41-44). DOI:10.1109/ICIP.2007.4379949
Najman, L., & Couprie, M. (2006). Building the component tree in quasi-linear time. IEEE Transactions on Image Processing, 15(11), 3531-3539. DOI:10.1109/TIP.2006.877518
Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. DOI:10.1109/TIP.2014.2336551
We create a small sample image (Figure 1 from [4]) and build the max-tree.


Determine all local maxima of the image.
The local maxima are defined as connected sets of pixels with equal gray level strictly greater than the gray levels of all pixels in direct neighborhood of the set. The function labels the local maxima.
Technically, the implementation is based on the max-tree representation of an image. The function is very efficient if the max-tree representation has already been computed. Otherwise, it is preferable to use the function local_maxima.
The input image for which the maxima are to be calculated.
The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
The value of each pixel is the index of its parent in the ravelled array.
The ordered pixel indices (referring to the ravelled array). The pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent).
Labeled local maxima of the image.
See also
Vincent L., Proc. “Grayscale area openings and closings, their efficient implementation and applications”, EURASIP Workshop on Mathematical Morphology and its Applications to Signal Processing, Barcelona, Spain, pp.22-27, May 1993.
Soille, P., “Morphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883. DOI:10.1007/978-3-662-05088-0
Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive Connected Operators for Image and Sequence Processing. IEEE Transactions on Image Processing, 7(4), 555-570. DOI:10.1109/83.663500
Najman, L., & Couprie, M. (2006). Building the component tree in quasi-linear time. IEEE Transactions on Image Processing, 15(11), 3531-3539. DOI:10.1109/TIP.2006.877518
Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. DOI:10.1109/TIP.2014.2336551
We create an image (quadratic function with a maximum in the center and 4 additional constant maxima.
We can calculate all local maxima:
The resulting image contains the labeled local maxima.


Compute the medial axis transform of a binary image
The image of the shape to be skeletonized.
If a mask is given, only those elements in image with a true value in mask are used for computing the medial axis.
If true, the distance transform is returned as well as the skeleton.
Medial axis transform of the image
Distance transform of the image (only returned if return_distance is True)
See also
This algorithm computes the medial axis transform of an image as the ridges of its distance transform.


Generates an octagon shaped structuring element.
For a given size of (m) horizontal and vertical sides and a given (n) height or width of slanted sides octagon is generated. The slanted sides are 45 or 135 degrees to the horizontal axis and hence the widths and heights are equal.
The size of the horizontal and vertical sides.
The height or width of the slanted sides.
The structuring element where elements of the neighborhood are 1 and 0 otherwise.
The data type of the structuring element.


Generates a octahedron-shaped structuring element.
This is the 3D equivalent of a diamond. A pixel is part of the neighborhood (i.e. labeled 1) if the city block/Manhattan distance between it and the center of the neighborhood is no greater than radius.
The radius of the octahedron-shaped structuring element.
The structuring element where elements of the neighborhood are 1 and 0 otherwise.
The data type of the structuring element.


Return greyscale morphological opening of an image.
The morphological opening on an image is defined as an erosion followed by a dilation. Opening can remove small bright spots (i.e. “salt”) and connect small dark cracks. This tends to “open” up (dark) gaps between (bright) features.
Image array.
The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).
The array to store the result of the morphology. If None is passed, a new array will be allocated.
The result of the morphological opening.


Perform a morphological reconstruction of an image.
Morphological reconstruction by dilation is similar to basic morphological dilation: high-intensity values will replace nearby low-intensity values. The basic dilation operator, however, uses a structuring element to determine how far a value in the input image can spread. In contrast, reconstruction uses two images: a “seed” image, which specifies the values that spread, and a “mask” image, which gives the maximum allowed value at each pixel. The mask image, like the structuring element, limits the spread of high-intensity values. Reconstruction by erosion is simply the inverse: low-intensity values spread from the seed image and are limited by the mask image, which represents the minimum allowed value.
Alternatively, you can think of reconstruction as a way to isolate the connected regions of an image. For dilation, reconstruction connects regions marked by local maxima in the seed image: neighboring pixels less-than-or-equal-to those seeds are connected to the seeded region. Local maxima with values larger than the seed image will get truncated to the seed value.
The seed image (a.k.a. marker image), which specifies the values that are dilated or eroded.
The maximum (dilation) / minimum (erosion) allowed value at each pixel.
Perform reconstruction by dilation or erosion. In dilation (or erosion), the seed image is dilated (or eroded) until limited by the mask image. For dilation, each seed value must be less than or equal to the corresponding mask value; for erosion, the reverse is true. Default is ‘dilation’.
The neighborhood expressed as an n-D array of 1’s and 0’s. Default is the n-D square of radius equal to 1 (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.)
The coordinates of the center of the structuring element. Default is located on the geometrical center of the selem, in that case selem dimensions must be odd.
The result of morphological reconstruction.
The algorithm is taken from [1]. Applications for greyscale reconstruction are discussed in [2] and [3].
Robinson, “Efficient morphological reconstruction: a downhill filter”, Pattern Recognition Letters 25 (2004) 1759-1767.
Vincent, L., “Morphological Grayscale Reconstruction in Image Analysis: Applications and Efficient Algorithms”, IEEE Transactions on Image Processing (1993)
Soille, P., “Morphological Image Analysis: Principles and Applications”, Chapter 6, 2nd edition (2003), ISBN 3540429883.
First, we create a sinusoidal mask image with peaks at middle and ends.
Then, we create a seed image initialized to the minimum mask value (for reconstruction by dilation, min-intensity values don’t spread) and add “seeds” to the left and right peak, but at a fraction of peak value (1).
The reconstructed image (or curve, in this case) is exactly the same as the mask image, except that the peaks are truncated to 0.5 and 0. The middle peak disappears completely: Since there were no seed values in this peak region, its reconstructed value is truncated to the surrounding value (-1).
As a more practical example, we try to extract the bright features of an image by subtracting a background image created by reconstruction.
To create the background image, set the mask image to the original image, and the seed image to the original image with an intensity offset, h.
The resulting reconstructed image looks exactly like the original image, but with the peaks of the bumps cut off. Subtracting this reconstructed image from the original image leaves just the peaks of the bumps
This operation is known as the h-dome of the image and leaves features of height h in the subtracted image.


Generates a flat, rectangular-shaped structuring element.
Every pixel in the rectangle generated for a given width and given height belongs to the neighborhood.
The number of rows of the rectangle.
The number of columns of the rectangle.
A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood.
The data type of the structuring element.


Remove contiguous holes smaller than the specified size.
The array containing the connected components of interest.
The maximum area, in pixels, of a contiguous hole that will be filled. Replaces min_size.
The connectivity defining the neighborhood of a pixel.
If True, remove the connected components in the input array itself. Otherwise, make a copy.
The input array with small holes within connected components removed.
If the input array is of an invalid type, such as float or string.
If the input array contains negative values.
If the array type is int, it is assumed that it contains already-labeled objects. The labels are not kept in the output image (this function always outputs a bool image). It is suggested that labeling is completed after using this function.


Remove objects smaller than the specified size.
Expects ar to be an array with labeled objects, and removes objects smaller than min_size. If ar is bool, the image is first labeled. This leads to potentially different behavior for bool and 0-and-1 arrays.
The array containing the objects of interest. If the array type is int, the ints must be non-negative.
The smallest allowable object size.
The connectivity defining the neighborhood of a pixel. Used during labelling if ar is bool.
If True, remove the objects in the input array itself. Otherwise, make a copy.
The input array with small connected components removed.
If the input array is of an invalid type, such as float or string.
If the input array contains negative values.


Compute the skeleton of a binary image.
Thinning is used to reduce each connected component in a binary image to a single-pixel wide skeleton.
A binary image containing the objects to be skeletonized. Zeros represent background, nonzero values are foreground.
Which algorithm to use. Zhang’s algorithm [Zha84] only works for 2D images, and is the default for 2D. Lee’s algorithm [Lee94] works for 2D or 3D images and is the default for 3D.
The thinned image.
See also
T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models via 3-D medial surface/axis thinning algorithms. Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994.
A fast parallel algorithm for thinning digital patterns, T. Y. Zhang and C. Y. Suen, Communications of the ACM, March 1984, Volume 27, Number 3.


Compute the skeleton of a binary image.
Thinning is used to reduce each connected component in a binary image to a single-pixel wide skeleton.
A binary image containing the objects to be skeletonized. Zeros represent background, nonzero values are foreground.
The thinned image.
See also
The method of [Lee94] uses an octree data structure to examine a 3x3x3 neighborhood of a pixel. The algorithm proceeds by iteratively sweeping over the image, and removing pixels at each iteration until the image stops changing. Each iteration consists of two steps: first, a list of candidates for removal is assembled; then pixels from this list are rechecked sequentially, to better preserve connectivity of the image.
The algorithm this function implements is different from the algorithms used by either skeletonize or medial_axis, thus for 2D images the results produced by this function are generally different.
T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models via 3-D medial surface/axis thinning algorithms. Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994.


Generates a flat, square-shaped structuring element.
Every pixel along the perimeter has a chessboard distance no greater than radius (radius=floor(width/2)) pixels.
The width and height of the square.
A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood.
The data type of the structuring element.


Generates a star shaped structuring element.
Start has 8 vertices and is an overlap of square of size 2*a + 1 with its 45 degree rotated version. The slanted sides are 45 or 135 degrees to the horizontal axis.
Parameter deciding the size of the star structural element. The side of the square array returned is 2*a + 1 + 2*floor(a / 2).
The structuring element where elements of the neighborhood are 1 and 0 otherwise.
The data type of the structuring element.


Perform morphological thinning of a binary image.
The image to be thinned.
Regardless of the value of this parameter, the thinned image is returned immediately if an iteration produces no change. If this parameter is specified it thus sets an upper bound on the number of iterations performed.
Thinned image.
See also
This algorithm [1] works by making multiple passes over the image, removing pixels matching a set of criteria designed to thin connected regions while preserving eight-connected components and 2 x 2 squares [2]. In each of the two sub-iterations the algorithm correlates the intermediate skeleton image with a neighborhood mask, then looks up each neighborhood in a lookup table indicating whether the central pixel should be deleted in that sub-iteration.
Z. Guo and R. W. Hall, “Parallel thinning with two-subiteration algorithms,” Comm. ACM, vol. 32, no. 3, pp. 359-373, 1989. DOI:10.1145/62065.62074
Lam, L., Seong-Whan Lee, and Ching Y. Suen, “Thinning Methodologies-A Comprehensive Survey,” IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol 14, No. 9, p. 879, 1992. DOI:10.1109/34.161346


Deprecated function. Use skimage.segmentation.watershed instead.
Find watershed basins in image flooded from given markers.
Data array where the lowest value points are labeled first.
The desired number of markers, or an array marking the basins with the values to be assigned in the label matrix. Zero means not a marker. If None (no markers given), the local minima of the image are used as markers.
An array with the same number of dimensions as image whose non-zero elements indicate neighbors for connection. Following the scipy convention, default is a one-connected array of the dimension of the image.
offset of the connectivity (one offset per dimension)
Array of same shape as image. Only points at which mask == True will be labeled.
Use compact watershed [3] with given compactness parameter. Higher values result in more regularly-shaped watershed basins.
If watershed_line is True, a one-pixel wide line separates the regions obtained by the watershed algorithm. The line has the label 0.
A labeled matrix of the same type and shape as markers
See also
random walker segmentation A segmentation algorithm based on anisotropic diffusion, usually slower than the watershed but with good results on noisy data and boundaries with holes.
This function implements a watershed algorithm [1] [2] that apportions pixels into marked basins. The algorithm uses a priority queue to hold the pixels with the metric for the priority queue being pixel value, then the time of entry into the queue - this settles ties in favor of the closest marker. Some ideas taken from Soille, “Automated Basin Delineation from Digital Elevation Models Using Mathematical Morphology”, Signal Processing 20 (1990) 171-182 The most important insight in the paper is that entry time onto the queue solves two problems: a pixel should be assigned to the neighbor with the largest gradient or, if there is no gradient, pixels on a plateau should be split between markers on opposite sides. This implementation converts all arguments to specific, lowest common denominator types, then passes these to a C algorithm. Markers can be determined manually, or automatically using for example the local minima of the gradient of the image, or the local maxima of the distance function to the background for separating overlapping objects (see example).
https://en.wikipedia.org/wiki/Watershed_%28image_processing%29
http://cmm.ensmp.fr/~beucher/wtshed.html
Peer Neubert & Peter Protzel (2014). Compact Watershed and Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation Algorithms. ICPR 2014, pp 996-1001. DOI:10.1109/ICPR.2014.181 https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf
The watershed algorithm is useful to separate overlapping objects.
We first generate an initial image with two overlapping circles:
Next, we want to separate the two circles. We generate markers at the maxima of the distance to the background:
Finally, we run the watershed on the image and markers:
The algorithm works also for 3-D images, and can be used for example to separate overlapping spheres.


Return white top hat of an image.
The white top hat of an image is defined as the image minus its morphological opening. This operation returns the bright spots of the image that are smaller than the structuring element.
Image array.
The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).
The array to store the result of the morphology. If None is passed, a new array will be allocated.
The result of the morphological white top hat.
See also
https://en.wikipedia.org/wiki/Top-hat_transform


skimage.registration.optical_flow_ilk(…[, …])
Coarse to fine optical flow estimator.
skimage.registration.optical_flow_tvl1(…)
Coarse to fine optical flow estimator.
skimage.registration.phase_cross_correlation(…)
Efficient subpixel image translation registration by cross-correlation.
Coarse to fine optical flow estimator.
The iterative Lucas-Kanade (iLK) solver is applied at each level of the image pyramid. iLK [1] is a fast and robust alternative to TVL1 algorithm although less accurate for rendering flat surfaces and object boundaries (see [2]).
The first gray scale image of the sequence.
The second gray scale image of the sequence.
Radius of the window considered around each pixel.
Number of times moving_image is warped.
If True, a Gaussian kernel is used for the local integration. Otherwise, a uniform kernel is used.
Whether to prefilter the estimated optical flow before each image warp. When True, a median filter with window size 3 along each axis is applied. This helps to remove potential outliers.
Output data type: must be floating point. Single precision provides good results and saves memory usage and computation time compared to double precision.
The estimated optical flow components for each axis.
Le Besnerais, G., & Champagnat, F. (2005, September). Dense optical flow by iterative local window registration. In IEEE International Conference on Image Processing 2005 (Vol. 1, pp. I-137). IEEE. DOI:10.1109/ICIP.2005.1529706
Plyer, A., Le Besnerais, G., & Champagnat, F. (2016). Massively parallel Lucas Kanade optical flow for real-time video processing applications. Journal of Real-Time Image Processing, 11(4), 713-730. DOI:10.1007/s11554-014-0423-0
Registration using optical flow
Coarse to fine optical flow estimator.
The TV-L1 solver is applied at each level of the image pyramid. TV-L1 is a popular algorithm for optical flow estimation introduced by Zack et al. [1], improved in [2] and detailed in [3].
The first gray scale image of the sequence.
The second gray scale image of the sequence.
Attachment parameter (\(\lambda\) in [1]). The smaller this parameter is, the smoother the returned result will be.
Tightness parameter (\(\tau\) in [1]). It should have a small value in order to maintain attachement and regularization parts in correspondence.
Number of times image1 is warped.
Number of fixed point iteration.
Tolerance used as stopping criterion based on the L² distance between two consecutive values of (u, v).
Whether to prefilter the estimated optical flow before each image warp. When True, a median filter with window size 3 along each axis is applied. This helps to remove potential outliers.
Output data type: must be floating point. Single precision provides good results and saves memory usage and computation time compared to double precision.
The estimated optical flow components for each axis.
Color images are not supported.
Zach, C., Pock, T., & Bischof, H. (2007, September). A duality based approach for realtime TV-L 1 optical flow. In Joint pattern recognition symposium (pp. 214-223). Springer, Berlin, Heidelberg. DOI:10.1007/978-3-540-74936-3_22
Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers, D. (2009). An improved algorithm for TV-L 1 optical flow. In Statistical and geometrical approaches to visual motion analysis (pp. 23-45). Springer, Berlin, Heidelberg. DOI:10.1007/978-3-642-03061-1_2
Pérez, J. S., Meinhardt-Llopis, E., & Facciolo, G. (2013). TV-L1 optical flow estimation. Image Processing On Line, 2013, 137-150. DOI:10.5201/ipol.2013.26
Registration using optical flow
Efficient subpixel image translation registration by cross-correlation.
This code gives the same precision as the FFT upsampled cross-correlation in a fraction of the computation time and with reduced memory requirements. It obtains an initial estimate of the cross-correlation peak by an FFT and then refines the shift estimation by upsampling the DFT only in a small neighborhood of that estimate by means of a matrix-multiply DFT.
Reference image.
Image to register. Must be same dimensionality as reference_image.
Upsampling factor. Images will be registered to within 1 / upsample_factor of a pixel. For example upsample_factor == 20 means the images will be registered within 1/20th of a pixel. Default is 1 (no upsampling). Not used if any of reference_mask or moving_mask is not None.
Defines how the algorithm interprets input data. “real” means data will be FFT’d to compute the correlation, while “fourier” data will bypass FFT of input data. Case insensitive. Not used if any of reference_mask or moving_mask is not None.
Returns error and phase difference if on, otherwise only shifts are returned. Has noeffect if any of reference_mask or moving_mask is not None. In this case only shifts is returned.
Boolean mask for reference_image. The mask should evaluate to True (or 1) on valid pixels. reference_mask should have the same shape as reference_image.
Boolean mask for moving_image. The mask should evaluate to True (or 1) on valid pixels. moving_mask should have the same shape as moving_image. If None, reference_mask will be used.
Minimum allowed overlap ratio between images. The correlation for translations corresponding with an overlap ratio lower than this threshold will be ignored. A lower overlap_ratio leads to smaller maximum translation, while a higher overlap_ratio leads to greater robustness against spurious matches due to small overlap between masked images. Used only if one of reference_mask or moving_mask is None.
Shift vector (in pixels) required to register moving_image with reference_image. Axis ordering is consistent with numpy (e.g. Z, Y, X)
Translation invariant normalized RMS error between reference_image and moving_image.
Global phase difference between the two images (should be zero if images are non-negative).
Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, “Efficient subpixel image registration algorithms,” Optics Letters 33, 156-158 (2008). DOI:10.1364/OL.33.000156
James R. Fienup, “Invariant error metrics for image reconstruction” Optics Letters 36, 8352-8357 (1997). DOI:10.1364/AO.36.008352
Dirk Padfield. Masked Object Registration in the Fourier Domain. IEEE Transactions on Image Processing, vol. 21(5), pp. 2706-2718 (2012). DOI:10.1109/TIP.2011.2181402
D. Padfield. “Masked FFT registration”. In Proc. Computer Vision and Pattern Recognition, pp. 2918-2925 (2010). DOI:10.1109/CVPR.2010.5540032
Masked Normalized Cross-Correlation


Coarse to fine optical flow estimator.
The iterative Lucas-Kanade (iLK) solver is applied at each level of the image pyramid. iLK [1] is a fast and robust alternative to TVL1 algorithm although less accurate for rendering flat surfaces and object boundaries (see [2]).
The first gray scale image of the sequence.
The second gray scale image of the sequence.
Radius of the window considered around each pixel.
Number of times moving_image is warped.
If True, a Gaussian kernel is used for the local integration. Otherwise, a uniform kernel is used.
Whether to prefilter the estimated optical flow before each image warp. When True, a median filter with window size 3 along each axis is applied. This helps to remove potential outliers.
Output data type: must be floating point. Single precision provides good results and saves memory usage and computation time compared to double precision.
The estimated optical flow components for each axis.
Le Besnerais, G., & Champagnat, F. (2005, September). Dense optical flow by iterative local window registration. In IEEE International Conference on Image Processing 2005 (Vol. 1, pp. I-137). IEEE. DOI:10.1109/ICIP.2005.1529706
Plyer, A., Le Besnerais, G., & Champagnat, F. (2016). Massively parallel Lucas Kanade optical flow for real-time video processing applications. Journal of Real-Time Image Processing, 11(4), 713-730. DOI:10.1007/s11554-014-0423-0


Coarse to fine optical flow estimator.
The TV-L1 solver is applied at each level of the image pyramid. TV-L1 is a popular algorithm for optical flow estimation introduced by Zack et al. [1], improved in [2] and detailed in [3].
The first gray scale image of the sequence.
The second gray scale image of the sequence.
Attachment parameter (\(\lambda\) in [1]). The smaller this parameter is, the smoother the returned result will be.
Tightness parameter (\(\tau\) in [1]). It should have a small value in order to maintain attachement and regularization parts in correspondence.
Number of times image1 is warped.
Number of fixed point iteration.
Tolerance used as stopping criterion based on the L² distance between two consecutive values of (u, v).
Whether to prefilter the estimated optical flow before each image warp. When True, a median filter with window size 3 along each axis is applied. This helps to remove potential outliers.
Output data type: must be floating point. Single precision provides good results and saves memory usage and computation time compared to double precision.
The estimated optical flow components for each axis.
Color images are not supported.
Zach, C., Pock, T., & Bischof, H. (2007, September). A duality based approach for realtime TV-L 1 optical flow. In Joint pattern recognition symposium (pp. 214-223). Springer, Berlin, Heidelberg. DOI:10.1007/978-3-540-74936-3_22
Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers, D. (2009). An improved algorithm for TV-L 1 optical flow. In Statistical and geometrical approaches to visual motion analysis (pp. 23-45). Springer, Berlin, Heidelberg. DOI:10.1007/978-3-642-03061-1_2
Pérez, J. S., Meinhardt-Llopis, E., & Facciolo, G. (2013). TV-L1 optical flow estimation. Image Processing On Line, 2013, 137-150. DOI:10.5201/ipol.2013.26


Efficient subpixel image translation registration by cross-correlation.
This code gives the same precision as the FFT upsampled cross-correlation in a fraction of the computation time and with reduced memory requirements. It obtains an initial estimate of the cross-correlation peak by an FFT and then refines the shift estimation by upsampling the DFT only in a small neighborhood of that estimate by means of a matrix-multiply DFT.
Reference image.
Image to register. Must be same dimensionality as reference_image.
Upsampling factor. Images will be registered to within 1 / upsample_factor of a pixel. For example upsample_factor == 20 means the images will be registered within 1/20th of a pixel. Default is 1 (no upsampling). Not used if any of reference_mask or moving_mask is not None.
Defines how the algorithm interprets input data. “real” means data will be FFT’d to compute the correlation, while “fourier” data will bypass FFT of input data. Case insensitive. Not used if any of reference_mask or moving_mask is not None.
Returns error and phase difference if on, otherwise only shifts are returned. Has noeffect if any of reference_mask or moving_mask is not None. In this case only shifts is returned.
Boolean mask for reference_image. The mask should evaluate to True (or 1) on valid pixels. reference_mask should have the same shape as reference_image.
Boolean mask for moving_image. The mask should evaluate to True (or 1) on valid pixels. moving_mask should have the same shape as moving_image. If None, reference_mask will be used.
Minimum allowed overlap ratio between images. The correlation for translations corresponding with an overlap ratio lower than this threshold will be ignored. A lower overlap_ratio leads to smaller maximum translation, while a higher overlap_ratio leads to greater robustness against spurious matches due to small overlap between masked images. Used only if one of reference_mask or moving_mask is None.
Shift vector (in pixels) required to register moving_image with reference_image. Axis ordering is consistent with numpy (e.g. Z, Y, X)
Translation invariant normalized RMS error between reference_image and moving_image.
Global phase difference between the two images (should be zero if images are non-negative).
Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, “Efficient subpixel image registration algorithms,” Optics Letters 33, 156-158 (2008). DOI:10.1364/OL.33.000156
James R. Fienup, “Invariant error metrics for image reconstruction” Optics Letters 36, 8352-8357 (1997). DOI:10.1364/AO.36.008352
Dirk Padfield. Masked Object Registration in the Fourier Domain. IEEE Transactions on Image Processing, vol. 21(5), pp. 2706-2718 (2012). DOI:10.1109/TIP.2011.2181402
D. Padfield. “Masked FFT registration”. In Proc. Computer Vision and Pattern Recognition, pp. 2918-2925 (2010). DOI:10.1109/CVPR.2010.5540032


Image restoration module.
skimage.restoration.ball_kernel(radius, ndim)
Create a ball kernel for restoration.rolling_ball.
skimage.restoration.calibrate_denoiser(…)
Calibrate a denoising function and return optimal J-invariant version.
skimage.restoration.cycle_spin(x, func, …)
Cycle spinning (repeatedly apply func to shifted versions of x).
skimage.restoration.denoise_bilateral(image)
Denoise image using bilateral filter.
skimage.restoration.denoise_nl_means(image)
Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images.
skimage.restoration.denoise_tv_bregman(…)
Perform total-variation denoising using split-Bregman optimization.
skimage.restoration.denoise_tv_chambolle(image)
Perform total-variation denoising on n-dimensional images.
skimage.restoration.denoise_wavelet(image[, …])
Perform wavelet denoising on an image.
skimage.restoration.ellipsoid_kernel(shape, …)
Create an ellipoid kernel for restoration.rolling_ball.
skimage.restoration.estimate_sigma(image[, …])
Robust wavelet-based estimator of the (Gaussian) noise standard deviation.
skimage.restoration.inpaint_biharmonic(…)
Inpaint masked points in image with biharmonic equations.
skimage.restoration.richardson_lucy(image, psf)
Richardson-Lucy deconvolution.
skimage.restoration.rolling_ball(image, *[, …])
Estimate background intensity by rolling/translating a kernel.
skimage.restoration.unsupervised_wiener(…)
Unsupervised Wiener-Hunt deconvolution.
skimage.restoration.unwrap_phase(image[, …])
Recover the original from a wrapped phase image.
skimage.restoration.wiener(image, psf, balance)
Wiener-Hunt deconvolution
Create a ball kernel for restoration.rolling_ball.
Radius of the ball.
Number of dimensions of the ball. ndim should match the dimensionality of the image the kernel will be applied to.
The kernel containing the surface intensity of the top half of the ellipsoid.
See also
Calibrate a denoising function and return optimal J-invariant version.
The returned function is partially evaluated with optimal parameter values set for denoising the input image.
Input data to be denoised (converted using img_as_float).
Denoising function to be calibrated.
Ranges of parameters for denoise_function to be calibrated over.
Stride used in masking procedure that converts denoise_function to J-invariance.
Whether to approximate the self-supervised loss used to evaluate the denoiser by only computing it on one masked version of the image. If False, the runtime will be a factor of stride**image.ndim longer.
If True, return parameters and losses in addition to the calibrated denoising function
The optimal J-invariant version of denoise_function.
List of parameters tested for denoise_function, as a dictionary of kwargs Self-supervised loss for each set of parameters in parameters_tested.
The calibration procedure uses a self-supervised mean-square-error loss to evaluate the performance of J-invariant versions of denoise_function. The minimizer of the self-supervised loss is also the minimizer of the ground-truth loss (i.e., the true MSE error) [1]. The returned function can be used on the original noisy image, or other images with similar characteristics.
at the expense of increasing its runtime. It has no effect on the runtime of the calibration.
J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, International Conference on Machine Learning, p. 524-533 (2019).
Cycle spinning (repeatedly apply func to shifted versions of x).
Data for input to func.
A function to apply to circularly shifted versions of x. Should take x as its first argument. Any additional arguments can be supplied via func_kw.
If an integer, shifts in range(0, max_shifts+1) will be used along each axis of x. If a tuple, range(0, max_shifts[i]+1) will be along axis i.
The step size for the shifts applied along axis, i, are:: range((0, max_shifts[i]+1, shift_steps[i])). If an integer is provided, the same step size is used for all axes.
The number of parallel threads to use during cycle spinning. If set to None, the full set of available cores are used.
Whether to treat the final axis as channels (no cycle shifts are performed over the channels axis).
Additional keyword arguments to supply to func.
The output of func(x, **func_kw) averaged over all combinations of the specified axis shifts.
Cycle spinning was proposed as a way to approach shift-invariance via performing several circular shifts of a shift-variant transform [1].
For a n-level discrete wavelet transforms, one may wish to perform all shifts up to max_shifts = 2**n - 1. In practice, much of the benefit can often be realized with only a small number of shifts per axis.
For transforms such as the blockwise discrete cosine transform, one may wish to evaluate shifts up to the block size used by the transform.
R.R. Coifman and D.L. Donoho. “Translation-Invariant De-Noising”. Wavelets and Statistics, Lecture Notes in Statistics, vol.103. Springer, New York, 1995, pp.125-150. DOI:10.1007/978-1-4612-2544-7_9
Denoise image using bilateral filter.
Input image, 2D grayscale or RGB.
Window size for filtering. If win_size is not specified, it is calculated as max(5, 2 * ceil(3 * sigma_spatial) + 1).
Standard deviation for grayvalue/color distance (radiometric similarity). A larger value results in averaging of pixels with larger radiometric differences. Note, that the image will be converted using the img_as_float function and thus the standard deviation is in respect to the range [0, 1]. If the value is None the standard deviation of the image will be used.
Standard deviation for range distance. A larger value results in averaging of pixels with larger spatial differences.
Number of discrete values for Gaussian weights of color filtering. A larger value results in improved accuracy.
How to handle values outside the image borders. See numpy.pad for detail.
Used in conjunction with mode ‘constant’, the value outside the image boundaries.
Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.
Denoised image.
This is an edge-preserving, denoising filter. It averages pixels based on their spatial closeness and radiometric similarity [1].
Spatial closeness is measured by the Gaussian function of the Euclidean distance between two pixels and a certain standard deviation (sigma_spatial).
Radiometric similarity is measured by the Gaussian function of the Euclidean distance between two color values and a certain standard deviation (sigma_color).
C. Tomasi and R. Manduchi. “Bilateral Filtering for Gray and Color Images.” IEEE International Conference on Computer Vision (1998) 839-846. DOI:10.1109/ICCV.1998.710815
Rank filters
Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images.
Input image to be denoised, which can be 2D or 3D, and grayscale or RGB (for 2D images only, see multichannel parameter).
Size of patches used for denoising.
Maximal distance in pixels where to search patches used for denoising.
Cut-off distance (in gray levels). The higher h, the more permissive one is in accepting patches. A higher h results in a smoother image, at the expense of blurring features. For a Gaussian noise of standard deviation sigma, a rule of thumb is to choose the value of h to be sigma of slightly less.
Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.
If True (default value), a fast version of the non-local means algorithm is used. If False, the original version of non-local means is used. See the Notes section for more details about the algorithms.
The standard deviation of the (Gaussian) noise. If provided, a more robust computation of patch weights is computed that takes the expected noise variance into account (see Notes below).
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
Denoised image, of same shape as image.
The non-local means algorithm is well suited for denoising images with specific textures. The principle of the algorithm is to average the value of a given pixel with values of other pixels in a limited neighbourhood, provided that the patches centered on the other pixels are similar enough to the patch centered on the pixel of interest.
In the original version of the algorithm [1], corresponding to fast=False, the computational complexity is:
Hence, changing the size of patches or their maximal distance has a strong effect on computing times, especially for 3-D images.
However, the default behavior corresponds to fast_mode=True, for which another version of non-local means [2] is used, corresponding to a complexity of:
The computing time depends only weakly on the patch size, thanks to the computation of the integral of patches distances for a given shift, that reduces the number of operations [1]. Therefore, this algorithm executes faster than the classic algorithm (fast_mode=False), at the expense of using twice as much memory. This implementation has been proven to be more efficient compared to other alternatives, see e.g. [3].
Compared to the classic algorithm, all pixels of a patch contribute to the distance to another patch with the same weight, no matter their distance to the center of the patch. This coarser computation of the distance can result in a slightly poorer denoising performance. Moreover, for small images (images with a linear size that is only a few times the patch size), the classic algorithm can be faster due to boundary effects.
The image is padded using the reflect mode of skimage.util.pad before denoising.
If the noise standard deviation, sigma, is provided a more robust computation of patch weights is used. Subtracting the known noise variance from the computed patch distances improves the estimates of patch similarity, giving a moderate improvement to denoising performance [4]. It was also mentioned as an option for the fast variant of the algorithm in [3].
When sigma is provided, a smaller h should typically be used to avoid oversmoothing. The optimal value for h depends on the image content and noise level, but a reasonable starting point is h = 0.8 * sigma when fast_mode is True, or h = 0.6 * sigma when fast_mode is False.
A. Buades, B. Coll, & J-M. Morel. A non-local algorithm for image denoising. In CVPR 2005, Vol. 2, pp. 60-65, IEEE. DOI:10.1109/CVPR.2005.38
J. Darbon, A. Cunha, T.F. Chan, S. Osher, and G.J. Jensen, Fast nonlocal filtering applied to electron cryomicroscopy, in 5th IEEE International Symposium on Biomedical Imaging: From Nano to Macro, 2008, pp. 1331-1334. DOI:10.1109/ISBI.2008.4541250
Jacques Froment. Parameter-Free Fast Pixelwise Non-Local Means Denoising. Image Processing On Line, 2014, vol. 4, pp. 300-326. DOI:10.5201/ipol.2014.120
A. Buades, B. Coll, & J-M. Morel. Non-Local Means Denoising. Image Processing On Line, 2011, vol. 1, pp. 208-212. DOI:10.5201/ipol.2011.bcm_nlm
Perform total-variation denoising using split-Bregman optimization.
Total-variation denoising (also know as total-variation regularization) tries to find an image with less total-variation under the constraint of being similar to the input image, which is controlled by the regularization parameter ([1], [2], [3], [4]).
Input data to be denoised (converted using img_as_float`).
Denoising weight. The smaller the weight, the more denoising (at the expense of less similarity to the input). The regularization parameter lambda is chosen as 2 * weight.
Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:
Maximal number of iterations used for the optimization.
Switch between isotropic and anisotropic TV denoising.
Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension.
Denoised image.
https://en.wikipedia.org/wiki/Total_variation_denoising
Tom Goldstein and Stanley Osher, “The Split Bregman Method For L1 Regularized Problems”, ftp://ftp.math.ucla.edu/pub/camreport/cam08-29.pdf
Pascal Getreuer, “Rudin–Osher–Fatemi Total Variation Denoising using Split Bregman” in Image Processing On Line on 2012–05–19, https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf
https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf
Perform total-variation denoising on n-dimensional images.
Input data to be denoised. image can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image.
Denoising weight. The greater weight, the more denoising (at the expense of fidelity to input).
Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:
(E_(n-1) - E_n) < eps * E_0
Maximal number of iterations used for the optimization.
Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension.
Denoised image.
Make sure to set the multichannel parameter appropriately for color images.
The principle of total variation denoising is explained in https://en.wikipedia.org/wiki/Total_variation_denoising
The principle of total variation denoising is to minimize the total variation of the image, which can be roughly described as the integral of the norm of the image gradient. Total variation denoising tends to produce “cartoon-like” images, that is, piecewise-constant images.
This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [1].
A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 89-97.
2D example on astronaut image:
3D example on synthetic data:
Perform wavelet denoising on an image.
Input data to be denoised. image can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image.
The noise standard deviation used when computing the wavelet detail coefficient threshold(s). When None (default), the noise standard deviation is estimated via the method in [2].
The type of wavelet to perform and can be any of the options pywt.wavelist outputs. The default is ‘db1’. For example, wavelet can be any of {'db2', 'haar', 'sym9'} and many more.
An optional argument to choose the type of denoising performed. It noted that choosing soft thresholding given additive noise finds the best approximation of the original image.
The number of wavelet decomposition levels to use. The default is three less than the maximum number of possible decomposition levels.
Apply wavelet denoising separately for each channel (where channels correspond to the final axis of the array).
If True and multichannel True, do the wavelet denoising in the YCbCr colorspace instead of the RGB color space. This typically results in better performance for RGB images.
Thresholding method to be used. The currently supported methods are “BayesShrink” [1] and “VisuShrink” [2]. Defaults to “BayesShrink”.
If False, no rescaling of the user-provided sigma will be performed. The default of True rescales sigma appropriately if the image is rescaled internally.
New in version 0.16: rescale_sigma was introduced in 0.16
Denoised image.
The wavelet domain is a sparse representation of the image, and can be thought of similarly to the frequency domain of the Fourier transform. Sparse representations have most values zero or near-zero and truly random noise is (usually) represented by many small values in the wavelet domain. Setting all values below some threshold to 0 reduces the noise in the image, but larger thresholds also decrease the detail present in the image.
If the input is 3D, this function performs wavelet denoising on each color plane separately.
Changed in version 0.16: For floating point inputs, the original input range is maintained and there is no clipping applied to the output. Other input types will be converted to a floating point value in the range [-1, 1] or [0, 1] depending on the input image range. Unless rescale_sigma = False, any internal rescaling applied to the image will also be applied to sigma to maintain the same relative amplitude.
Many wavelet coefficient thresholding approaches have been proposed. By default, denoise_wavelet applies BayesShrink, which is an adaptive thresholding method that computes separate thresholds for each wavelet sub-band as described in [1].
If method == "VisuShrink", a single “universal threshold” is applied to all wavelet detail coefficients as described in [2]. This threshold is designed to remove all Gaussian noise at a given sigma with high probability, but tends to produce images that appear overly smooth.
Although any of the wavelets from PyWavelets can be selected, the thresholding methods assume an orthogonal wavelet transform and may not choose the threshold appropriately for biorthogonal wavelets. Orthogonal wavelets are desirable because white noise in the input remains white noise in the subbands. Biorthogonal wavelets lead to colored noise in the subbands. Additionally, the orthogonal wavelets in PyWavelets are orthonormal so that noise variance in the subbands remains identical to the noise variance of the input. Example orthogonal wavelets are the Daubechies (e.g. ‘db2’) or symmlet (e.g. ‘sym2’) families.
Chang, S. Grace, Bin Yu, and Martin Vetterli. “Adaptive wavelet thresholding for image denoising and compression.” Image Processing, IEEE Transactions on 9.9 (2000): 1532-1546. DOI:10.1109/83.862633
D. L. Donoho and I. M. Johnstone. “Ideal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425
Create an ellipoid kernel for restoration.rolling_ball.
Length of the principal axis of the ellipsoid (excluding the intensity axis). The kernel needs to have the same dimensionality as the image it will be applied to.
Length of the intensity axis of the ellipsoid.
The kernel containing the surface intensity of the top half of the ellipsoid.
See also
Use rolling-ball algorithm for estimating background intensity
Robust wavelet-based estimator of the (Gaussian) noise standard deviation.
Image for which to estimate the noise standard deviation.
If true, average the channel estimates of sigma. Otherwise return a list of sigmas corresponding to each channel.
Estimate sigma separately for each channel.
Estimated noise standard deviation(s). If multichannel is True and average_sigmas is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned.
This function assumes the noise follows a Gaussian distribution. The estimation algorithm is based on the median absolute deviation of the wavelet detail coefficients as described in section 4.2 of [1].
D. L. Donoho and I. M. Johnstone. “Ideal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425
Inpaint masked points in image with biharmonic equations.
Input image.
Array of pixels to be inpainted. Have to be the same shape as one of the ‘image’ channels. Unknown pixels have to be represented with 1, known pixels - with 0.
If True, the last image dimension is considered as a color channel, otherwise as spatial.
Input image with masked pixels inpainted.
N.S.Hoang, S.B.Damelin, “On surface completion and image inpainting by biharmonic functions: numerical aspects”, arXiv:1707.06567
C. K. Chui and H. N. Mhaskar, MRA Contextual-Recovery Extension of Smooth Functions on Manifolds, Appl. and Comp. Harmonic Anal., 28 (2010), 104-113, DOI:10.1016/j.acha.2009.04.004
Richardson-Lucy deconvolution.
Input degraded image (can be N dimensional).
The point spread function.
Number of iterations. This parameter plays the role of regularisation.
True by default. If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility.
Value below which intermediate results become 0 to avoid division by small numbers.
The deconvolved image.
https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution
Estimate background intensity by rolling/translating a kernel.
This rolling ball algorithm estimates background intensity for a ndimage in case of uneven exposure. It is a generalization of the frequently used rolling ball algorithm [1].
The image to be filtered.
Radius of a ball shaped kernel to be rolled/translated in the image. Used if kernel = None.
The kernel to be rolled/translated in the image. It must have the same number of dimensions as image. Kernel is filled with the intensity of the kernel at that position.
If False (default) assumes that none of the values in image are np.nan, and uses a faster implementation.
The maximum number of threads to use. If None use the OpenMP default value; typically equal to the maximum number of virtual cores. Note: This is an upper limit to the number of threads. The exact number is determined by the system’s OpenMP library.
The estimated background of the image.
For the pixel that has its background intensity estimated (without loss of generality at center) the rolling ball method centers kernel under it and raises the kernel until the surface touches the image umbra at some pos=(y,x). The background intensity is then estimated using the image intensity at that position (image[pos]) plus the difference of kernel[center] - kernel[pos].
This algorithm assumes that dark pixels correspond to the background. If you have a bright background, invert the image before passing it to the function, e.g., using utils.invert. See the gallery example for details.
This algorithm is sensitive to noise (in particular salt-and-pepper noise). If this is a problem in your image, you can apply mild gaussian smoothing before passing the image to this function.
Sternberg, Stanley R. “Biomedical image processing.” Computer 1 (1983): 22-34. DOI:10.1109/MC.1983.1654163
Use rolling-ball algorithm for estimating background intensity
Unsupervised Wiener-Hunt deconvolution.
Return the deconvolution with a Wiener-Hunt approach, where the hyperparameters are automatically estimated. The algorithm is a stochastic iterative process (Gibbs sampler) described in the reference below. See also wiener function.
The input degraded image.
The impulse response (input image’s space) or the transfer function (Fourier space). Both are accepted. The transfer function is automatically recognized as being complex (np.iscomplexobj(psf)).
The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf.
Dictionary of parameters for the Gibbs sampler. See below.
True by default. If true, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility.
The deconvolved image (the posterior mean).
The keys noise and prior contain the chain list of noise and prior precision respectively.
The stopping criterion: the norm of the difference between to successive approximated solution (empirical mean of object samples, see Notes section). 1e-4 by default.
The number of sample to ignore to start computation of the mean. 15 by default.
The minimum number of iterations. 30 by default.
The maximum number of iterations if threshold is not satisfied. 200 by default.
A user provided callable to which is passed, if the function exists, the current image sample for whatever purpose. The user can store the sample, or compute other moments than the mean. It has no influence on the algorithm execution and is only for inspection.
The estimated image is design as the posterior mean of a probability law (from a Bayesian analysis). The mean is defined as a sum over all the possible images weighted by their respective probability. Given the size of the problem, the exact sum is not tractable. This algorithm use of MCMC to draw image under the posterior law. The practical idea is to only draw highly probable images since they have the biggest contribution to the mean. At the opposite, the less probable images are drawn less often since their contribution is low. Finally the empirical mean of these samples give us an estimation of the mean, and an exact computation with an infinite sample set.
François Orieux, Jean-François Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010)
https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593
http://research.orieux.fr/files/papers/OGR-JOSA10.pdf
Recover the original from a wrapped phase image.
From an image wrapped to lie in the interval [-pi, pi), recover the original, unwrapped image.
The values should be in the range [-pi, pi). If a masked array is provided, the masked entries will not be changed, and their values will not be used to guide the unwrapping of neighboring, unmasked values. Masked 1D arrays are not allowed, and will raise a ValueError.
When an element of the sequence is True, the unwrapping process will regard the edges along the corresponding axis of the image to be connected and use this connectivity to guide the phase unwrapping process. If only a single boolean is given, it will apply to all axes. Wrap around is not supported for 1D arrays.
Unwrapping 2D or 3D images uses random initialization. This sets the seed of the PRNG to achieve deterministic behavior.
Unwrapped image of the same shape as the input. If the input image was a masked array, the mask will be preserved.
If called with a masked 1D array or called with a 1D array and wrap_around=True.
Miguel Arevallilo Herraez, David R. Burton, Michael J. Lalor, and Munther A. Gdeisat, “Fast two-dimensional phase-unwrapping algorithm based on sorting by reliability following a noncontinuous path”, Journal Applied Optics, Vol. 41, No. 35 (2002) 7437,
Abdul-Rahman, H., Gdeisat, M., Burton, D., & Lalor, M., “Fast three-dimensional phase-unwrapping algorithm based on sorting by reliability following a non-continuous path. In W. Osten, C. Gorecki, & E. L. Novak (Eds.), Optical Metrology (2005) 32–40, International Society for Optics and Photonics.
Phase Unwrapping
Wiener-Hunt deconvolution
Return the deconvolution with a Wiener-Hunt approach (i.e. with Fourier diagonalisation).
Input degraded image
Point Spread Function. This is assumed to be the impulse response (input image space) if the data-type is real, or the transfer function (Fourier space) if the data-type is complex. There is no constraints on the shape of the impulse response. The transfer function must be of shape (M, N) if is_real is True, (M, N // 2 + 1) otherwise (see np.fft.rfftn).
The regularisation parameter value that tunes the balance between the data adequacy that improve frequency restoration and the prior adequacy that reduce frequency restoration (to avoid noise artifacts).
The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. Shape constraint is the same as for the psf parameter.
True by default. Specify if psf and reg are provided with hermitian hypothesis, that is only half of the frequency plane is provided (due to the redundancy of Fourier transform of real signal). It’s apply only if psf and/or reg are provided as transfer function. For the hermitian property see uft module or np.fft.rfftn.
True by default. If True, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility.
The deconvolved image.
This function applies the Wiener filter to a noisy and degraded image by an impulse response (or PSF). If the data model is
where \(n\) is noise, \(H\) the PSF and \(x\) the unknown original image, the Wiener filter is
where \(F\) and \(F^\dagger\) are the Fourier and inverse Fourier transforms respectively, \(\Lambda_H\) the transfer function (or the Fourier transform of the PSF, see [Hunt] below) and \(\Lambda_D\) the filter to penalize the restored image frequencies (Laplacian by default, that is penalization of high frequency). The parameter \(\lambda\) tunes the balance between the data (that tends to increase high frequency, even those coming from noise), and the regularization.
These methods are then specific to a prior model. Consequently, the application or the true image nature must corresponds to the prior model. By default, the prior model (Laplacian) introduce image smoothness or pixel correlation. It can also be interpreted as high-frequency penalization to compensate the instability of the solution with respect to the data (sometimes called noise amplification or “explosive” solution).
Finally, the use of Fourier space implies a circulant property of \(H\), see [Hunt].
François Orieux, Jean-François Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010)
https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593
http://research.orieux.fr/files/papers/OGR-JOSA10.pdf
B. R. Hunt “A matrix theory proof of the discrete convolution theorem”, IEEE Trans. on Audio and Electroacoustics, vol. au-19, no. 4, pp. 285-288, dec. 1971


Create a ball kernel for restoration.rolling_ball.
Radius of the ball.
Number of dimensions of the ball. ndim should match the dimensionality of the image the kernel will be applied to.
The kernel containing the surface intensity of the top half of the ellipsoid.
See also


Calibrate a denoising function and return optimal J-invariant version.
The returned function is partially evaluated with optimal parameter values set for denoising the input image.
Input data to be denoised (converted using img_as_float).
Denoising function to be calibrated.
Ranges of parameters for denoise_function to be calibrated over.
Stride used in masking procedure that converts denoise_function to J-invariance.
Whether to approximate the self-supervised loss used to evaluate the denoiser by only computing it on one masked version of the image. If False, the runtime will be a factor of stride**image.ndim longer.
If True, return parameters and losses in addition to the calibrated denoising function
The optimal J-invariant version of denoise_function.
List of parameters tested for denoise_function, as a dictionary of kwargs Self-supervised loss for each set of parameters in parameters_tested.
The calibration procedure uses a self-supervised mean-square-error loss to evaluate the performance of J-invariant versions of denoise_function. The minimizer of the self-supervised loss is also the minimizer of the ground-truth loss (i.e., the true MSE error) [1]. The returned function can be used on the original noisy image, or other images with similar characteristics.
at the expense of increasing its runtime. It has no effect on the runtime of the calibration.
J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, International Conference on Machine Learning, p. 524-533 (2019).


Cycle spinning (repeatedly apply func to shifted versions of x).
Data for input to func.
A function to apply to circularly shifted versions of x. Should take x as its first argument. Any additional arguments can be supplied via func_kw.
If an integer, shifts in range(0, max_shifts+1) will be used along each axis of x. If a tuple, range(0, max_shifts[i]+1) will be along axis i.
The step size for the shifts applied along axis, i, are:: range((0, max_shifts[i]+1, shift_steps[i])). If an integer is provided, the same step size is used for all axes.
The number of parallel threads to use during cycle spinning. If set to None, the full set of available cores are used.
Whether to treat the final axis as channels (no cycle shifts are performed over the channels axis).
Additional keyword arguments to supply to func.
The output of func(x, **func_kw) averaged over all combinations of the specified axis shifts.
Cycle spinning was proposed as a way to approach shift-invariance via performing several circular shifts of a shift-variant transform [1].
For a n-level discrete wavelet transforms, one may wish to perform all shifts up to max_shifts = 2**n - 1. In practice, much of the benefit can often be realized with only a small number of shifts per axis.
For transforms such as the blockwise discrete cosine transform, one may wish to evaluate shifts up to the block size used by the transform.
R.R. Coifman and D.L. Donoho. “Translation-Invariant De-Noising”. Wavelets and Statistics, Lecture Notes in Statistics, vol.103. Springer, New York, 1995, pp.125-150. DOI:10.1007/978-1-4612-2544-7_9


Denoise image using bilateral filter.
Input image, 2D grayscale or RGB.
Window size for filtering. If win_size is not specified, it is calculated as max(5, 2 * ceil(3 * sigma_spatial) + 1).
Standard deviation for grayvalue/color distance (radiometric similarity). A larger value results in averaging of pixels with larger radiometric differences. Note, that the image will be converted using the img_as_float function and thus the standard deviation is in respect to the range [0, 1]. If the value is None the standard deviation of the image will be used.
Standard deviation for range distance. A larger value results in averaging of pixels with larger spatial differences.
Number of discrete values for Gaussian weights of color filtering. A larger value results in improved accuracy.
How to handle values outside the image borders. See numpy.pad for detail.
Used in conjunction with mode ‘constant’, the value outside the image boundaries.
Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.
Denoised image.
This is an edge-preserving, denoising filter. It averages pixels based on their spatial closeness and radiometric similarity [1].
Spatial closeness is measured by the Gaussian function of the Euclidean distance between two pixels and a certain standard deviation (sigma_spatial).
Radiometric similarity is measured by the Gaussian function of the Euclidean distance between two color values and a certain standard deviation (sigma_color).
C. Tomasi and R. Manduchi. “Bilateral Filtering for Gray and Color Images.” IEEE International Conference on Computer Vision (1998) 839-846. DOI:10.1109/ICCV.1998.710815


Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images.
Input image to be denoised, which can be 2D or 3D, and grayscale or RGB (for 2D images only, see multichannel parameter).
Size of patches used for denoising.
Maximal distance in pixels where to search patches used for denoising.
Cut-off distance (in gray levels). The higher h, the more permissive one is in accepting patches. A higher h results in a smoother image, at the expense of blurring features. For a Gaussian noise of standard deviation sigma, a rule of thumb is to choose the value of h to be sigma of slightly less.
Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.
If True (default value), a fast version of the non-local means algorithm is used. If False, the original version of non-local means is used. See the Notes section for more details about the algorithms.
The standard deviation of the (Gaussian) noise. If provided, a more robust computation of patch weights is computed that takes the expected noise variance into account (see Notes below).
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
Denoised image, of same shape as image.
The non-local means algorithm is well suited for denoising images with specific textures. The principle of the algorithm is to average the value of a given pixel with values of other pixels in a limited neighbourhood, provided that the patches centered on the other pixels are similar enough to the patch centered on the pixel of interest.
In the original version of the algorithm [1], corresponding to fast=False, the computational complexity is:
Hence, changing the size of patches or their maximal distance has a strong effect on computing times, especially for 3-D images.
However, the default behavior corresponds to fast_mode=True, for which another version of non-local means [2] is used, corresponding to a complexity of:
The computing time depends only weakly on the patch size, thanks to the computation of the integral of patches distances for a given shift, that reduces the number of operations [1]. Therefore, this algorithm executes faster than the classic algorithm (fast_mode=False), at the expense of using twice as much memory. This implementation has been proven to be more efficient compared to other alternatives, see e.g. [3].
Compared to the classic algorithm, all pixels of a patch contribute to the distance to another patch with the same weight, no matter their distance to the center of the patch. This coarser computation of the distance can result in a slightly poorer denoising performance. Moreover, for small images (images with a linear size that is only a few times the patch size), the classic algorithm can be faster due to boundary effects.
The image is padded using the reflect mode of skimage.util.pad before denoising.
If the noise standard deviation, sigma, is provided a more robust computation of patch weights is used. Subtracting the known noise variance from the computed patch distances improves the estimates of patch similarity, giving a moderate improvement to denoising performance [4]. It was also mentioned as an option for the fast variant of the algorithm in [3].
When sigma is provided, a smaller h should typically be used to avoid oversmoothing. The optimal value for h depends on the image content and noise level, but a reasonable starting point is h = 0.8 * sigma when fast_mode is True, or h = 0.6 * sigma when fast_mode is False.
A. Buades, B. Coll, & J-M. Morel. A non-local algorithm for image denoising. In CVPR 2005, Vol. 2, pp. 60-65, IEEE. DOI:10.1109/CVPR.2005.38
J. Darbon, A. Cunha, T.F. Chan, S. Osher, and G.J. Jensen, Fast nonlocal filtering applied to electron cryomicroscopy, in 5th IEEE International Symposium on Biomedical Imaging: From Nano to Macro, 2008, pp. 1331-1334. DOI:10.1109/ISBI.2008.4541250
Jacques Froment. Parameter-Free Fast Pixelwise Non-Local Means Denoising. Image Processing On Line, 2014, vol. 4, pp. 300-326. DOI:10.5201/ipol.2014.120
A. Buades, B. Coll, & J-M. Morel. Non-Local Means Denoising. Image Processing On Line, 2011, vol. 1, pp. 208-212. DOI:10.5201/ipol.2011.bcm_nlm


Perform total-variation denoising using split-Bregman optimization.
Total-variation denoising (also know as total-variation regularization) tries to find an image with less total-variation under the constraint of being similar to the input image, which is controlled by the regularization parameter ([1], [2], [3], [4]).
Input data to be denoised (converted using img_as_float`).
Denoising weight. The smaller the weight, the more denoising (at the expense of less similarity to the input). The regularization parameter lambda is chosen as 2 * weight.
Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:
Maximal number of iterations used for the optimization.
Switch between isotropic and anisotropic TV denoising.
Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension.
Denoised image.
https://en.wikipedia.org/wiki/Total_variation_denoising
Tom Goldstein and Stanley Osher, “The Split Bregman Method For L1 Regularized Problems”, ftp://ftp.math.ucla.edu/pub/camreport/cam08-29.pdf
Pascal Getreuer, “Rudin–Osher–Fatemi Total Variation Denoising using Split Bregman” in Image Processing On Line on 2012–05–19, https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf
https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf


Perform total-variation denoising on n-dimensional images.
Input data to be denoised. image can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image.
Denoising weight. The greater weight, the more denoising (at the expense of fidelity to input).
Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:
(E_(n-1) - E_n) < eps * E_0
Maximal number of iterations used for the optimization.
Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension.
Denoised image.
Make sure to set the multichannel parameter appropriately for color images.
The principle of total variation denoising is explained in https://en.wikipedia.org/wiki/Total_variation_denoising
The principle of total variation denoising is to minimize the total variation of the image, which can be roughly described as the integral of the norm of the image gradient. Total variation denoising tends to produce “cartoon-like” images, that is, piecewise-constant images.
This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [1].
A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 89-97.
2D example on astronaut image:
3D example on synthetic data:


Perform wavelet denoising on an image.
Input data to be denoised. image can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image.
The noise standard deviation used when computing the wavelet detail coefficient threshold(s). When None (default), the noise standard deviation is estimated via the method in [2].
The type of wavelet to perform and can be any of the options pywt.wavelist outputs. The default is ‘db1’. For example, wavelet can be any of {'db2', 'haar', 'sym9'} and many more.
An optional argument to choose the type of denoising performed. It noted that choosing soft thresholding given additive noise finds the best approximation of the original image.
The number of wavelet decomposition levels to use. The default is three less than the maximum number of possible decomposition levels.
Apply wavelet denoising separately for each channel (where channels correspond to the final axis of the array).
If True and multichannel True, do the wavelet denoising in the YCbCr colorspace instead of the RGB color space. This typically results in better performance for RGB images.
Thresholding method to be used. The currently supported methods are “BayesShrink” [1] and “VisuShrink” [2]. Defaults to “BayesShrink”.
If False, no rescaling of the user-provided sigma will be performed. The default of True rescales sigma appropriately if the image is rescaled internally.
New in version 0.16: rescale_sigma was introduced in 0.16
Denoised image.
The wavelet domain is a sparse representation of the image, and can be thought of similarly to the frequency domain of the Fourier transform. Sparse representations have most values zero or near-zero and truly random noise is (usually) represented by many small values in the wavelet domain. Setting all values below some threshold to 0 reduces the noise in the image, but larger thresholds also decrease the detail present in the image.
If the input is 3D, this function performs wavelet denoising on each color plane separately.
Changed in version 0.16: For floating point inputs, the original input range is maintained and there is no clipping applied to the output. Other input types will be converted to a floating point value in the range [-1, 1] or [0, 1] depending on the input image range. Unless rescale_sigma = False, any internal rescaling applied to the image will also be applied to sigma to maintain the same relative amplitude.
Many wavelet coefficient thresholding approaches have been proposed. By default, denoise_wavelet applies BayesShrink, which is an adaptive thresholding method that computes separate thresholds for each wavelet sub-band as described in [1].
If method == "VisuShrink", a single “universal threshold” is applied to all wavelet detail coefficients as described in [2]. This threshold is designed to remove all Gaussian noise at a given sigma with high probability, but tends to produce images that appear overly smooth.
Although any of the wavelets from PyWavelets can be selected, the thresholding methods assume an orthogonal wavelet transform and may not choose the threshold appropriately for biorthogonal wavelets. Orthogonal wavelets are desirable because white noise in the input remains white noise in the subbands. Biorthogonal wavelets lead to colored noise in the subbands. Additionally, the orthogonal wavelets in PyWavelets are orthonormal so that noise variance in the subbands remains identical to the noise variance of the input. Example orthogonal wavelets are the Daubechies (e.g. ‘db2’) or symmlet (e.g. ‘sym2’) families.
Chang, S. Grace, Bin Yu, and Martin Vetterli. “Adaptive wavelet thresholding for image denoising and compression.” Image Processing, IEEE Transactions on 9.9 (2000): 1532-1546. DOI:10.1109/83.862633
D. L. Donoho and I. M. Johnstone. “Ideal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425


Create an ellipoid kernel for restoration.rolling_ball.
Length of the principal axis of the ellipsoid (excluding the intensity axis). The kernel needs to have the same dimensionality as the image it will be applied to.
Length of the intensity axis of the ellipsoid.
The kernel containing the surface intensity of the top half of the ellipsoid.
See also


Robust wavelet-based estimator of the (Gaussian) noise standard deviation.
Image for which to estimate the noise standard deviation.
If true, average the channel estimates of sigma. Otherwise return a list of sigmas corresponding to each channel.
Estimate sigma separately for each channel.
Estimated noise standard deviation(s). If multichannel is True and average_sigmas is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned.
This function assumes the noise follows a Gaussian distribution. The estimation algorithm is based on the median absolute deviation of the wavelet detail coefficients as described in section 4.2 of [1].
D. L. Donoho and I. M. Johnstone. “Ideal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425


Inpaint masked points in image with biharmonic equations.
Input image.
Array of pixels to be inpainted. Have to be the same shape as one of the ‘image’ channels. Unknown pixels have to be represented with 1, known pixels - with 0.
If True, the last image dimension is considered as a color channel, otherwise as spatial.
Input image with masked pixels inpainted.
N.S.Hoang, S.B.Damelin, “On surface completion and image inpainting by biharmonic functions: numerical aspects”, arXiv:1707.06567
C. K. Chui and H. N. Mhaskar, MRA Contextual-Recovery Extension of Smooth Functions on Manifolds, Appl. and Comp. Harmonic Anal., 28 (2010), 104-113, DOI:10.1016/j.acha.2009.04.004


Richardson-Lucy deconvolution.
Input degraded image (can be N dimensional).
The point spread function.
Number of iterations. This parameter plays the role of regularisation.
True by default. If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility.
Value below which intermediate results become 0 to avoid division by small numbers.
The deconvolved image.
https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution


Estimate background intensity by rolling/translating a kernel.
This rolling ball algorithm estimates background intensity for a ndimage in case of uneven exposure. It is a generalization of the frequently used rolling ball algorithm [1].
The image to be filtered.
Radius of a ball shaped kernel to be rolled/translated in the image. Used if kernel = None.
The kernel to be rolled/translated in the image. It must have the same number of dimensions as image. Kernel is filled with the intensity of the kernel at that position.
If False (default) assumes that none of the values in image are np.nan, and uses a faster implementation.
The maximum number of threads to use. If None use the OpenMP default value; typically equal to the maximum number of virtual cores. Note: This is an upper limit to the number of threads. The exact number is determined by the system’s OpenMP library.
The estimated background of the image.
For the pixel that has its background intensity estimated (without loss of generality at center) the rolling ball method centers kernel under it and raises the kernel until the surface touches the image umbra at some pos=(y,x). The background intensity is then estimated using the image intensity at that position (image[pos]) plus the difference of kernel[center] - kernel[pos].
This algorithm assumes that dark pixels correspond to the background. If you have a bright background, invert the image before passing it to the function, e.g., using utils.invert. See the gallery example for details.
This algorithm is sensitive to noise (in particular salt-and-pepper noise). If this is a problem in your image, you can apply mild gaussian smoothing before passing the image to this function.
Sternberg, Stanley R. “Biomedical image processing.” Computer 1 (1983): 22-34. DOI:10.1109/MC.1983.1654163


Unsupervised Wiener-Hunt deconvolution.
Return the deconvolution with a Wiener-Hunt approach, where the hyperparameters are automatically estimated. The algorithm is a stochastic iterative process (Gibbs sampler) described in the reference below. See also wiener function.
The input degraded image.
The impulse response (input image’s space) or the transfer function (Fourier space). Both are accepted. The transfer function is automatically recognized as being complex (np.iscomplexobj(psf)).
The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf.
Dictionary of parameters for the Gibbs sampler. See below.
True by default. If true, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility.
The deconvolved image (the posterior mean).
The keys noise and prior contain the chain list of noise and prior precision respectively.
The stopping criterion: the norm of the difference between to successive approximated solution (empirical mean of object samples, see Notes section). 1e-4 by default.
The number of sample to ignore to start computation of the mean. 15 by default.
The minimum number of iterations. 30 by default.
The maximum number of iterations if threshold is not satisfied. 200 by default.
A user provided callable to which is passed, if the function exists, the current image sample for whatever purpose. The user can store the sample, or compute other moments than the mean. It has no influence on the algorithm execution and is only for inspection.
The estimated image is design as the posterior mean of a probability law (from a Bayesian analysis). The mean is defined as a sum over all the possible images weighted by their respective probability. Given the size of the problem, the exact sum is not tractable. This algorithm use of MCMC to draw image under the posterior law. The practical idea is to only draw highly probable images since they have the biggest contribution to the mean. At the opposite, the less probable images are drawn less often since their contribution is low. Finally the empirical mean of these samples give us an estimation of the mean, and an exact computation with an infinite sample set.
François Orieux, Jean-François Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010)
https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593
http://research.orieux.fr/files/papers/OGR-JOSA10.pdf


Recover the original from a wrapped phase image.
From an image wrapped to lie in the interval [-pi, pi), recover the original, unwrapped image.
The values should be in the range [-pi, pi). If a masked array is provided, the masked entries will not be changed, and their values will not be used to guide the unwrapping of neighboring, unmasked values. Masked 1D arrays are not allowed, and will raise a ValueError.
When an element of the sequence is True, the unwrapping process will regard the edges along the corresponding axis of the image to be connected and use this connectivity to guide the phase unwrapping process. If only a single boolean is given, it will apply to all axes. Wrap around is not supported for 1D arrays.
Unwrapping 2D or 3D images uses random initialization. This sets the seed of the PRNG to achieve deterministic behavior.
Unwrapped image of the same shape as the input. If the input image was a masked array, the mask will be preserved.
If called with a masked 1D array or called with a 1D array and wrap_around=True.
Miguel Arevallilo Herraez, David R. Burton, Michael J. Lalor, and Munther A. Gdeisat, “Fast two-dimensional phase-unwrapping algorithm based on sorting by reliability following a noncontinuous path”, Journal Applied Optics, Vol. 41, No. 35 (2002) 7437,
Abdul-Rahman, H., Gdeisat, M., Burton, D., & Lalor, M., “Fast three-dimensional phase-unwrapping algorithm based on sorting by reliability following a non-continuous path. In W. Osten, C. Gorecki, & E. L. Novak (Eds.), Optical Metrology (2005) 32–40, International Society for Optics and Photonics.