Auto-level image using local histogram.
This filter locally stretches the histogram of gray values to cover the entire range of values from “white” to “black”.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Return greyscale local autolevel of an image.
This filter locally stretches the histogram of greyvalues to cover the entire range of values from “white” to “black”.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [p0, p1] percentile interval to be considered for computing the value.
Output image.


Local bottom-hat of an image.
This filter computes the morphological closing of the image and then subtracts the result from the original image.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
New in version 0.17.
This function is deprecated and will be removed in scikit-image 0.19. This filter was misnamed and we believe that the usefulness is narrow.


Enhance contrast of an image.
This replaces each pixel by the local maximum if the pixel gray value is closer to the local maximum than the local minimum. Otherwise it is replaced by the local minimum.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image


Enhance contrast of an image.
This replaces each pixel by the local maximum if the pixel greyvalue is closer to the local maximum than the local minimum. Otherwise it is replaced by the local minimum.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [p0, p1] percentile interval to be considered for computing the value.
Output image.


Local entropy.
The entropy is computed using base 2 logarithm i.e. the filter returns the minimum number of bits needed to encode the local gray level distribution.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
https://en.wikipedia.org/wiki/Entropy_(information_theory)


Equalize image using local histogram.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Return local geometric mean of an image.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
Gonzalez, R. C. and Wood, R. E. “Digital Image Processing (3rd Edition).” Prentice-Hall Inc, 2006.


Return local gradient of an image (i.e. local maximum - local minimum).
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Return local gradient of an image (i.e. local maximum - local minimum).
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [p0, p1] percentile interval to be considered for computing the value.
Output image.


Majority filter assign to each pixel the most occuring value within its neighborhood.
Image array (uint8, uint16 array).
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array will be allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Return local maximum of an image.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
See also
The lower algorithm complexity makes skimage.filters.rank.maximum more efficient for larger images and structuring elements.


Return local mean of an image.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Apply a flat kernel bilateral filter.
This is an edge-preserving and noise reducing denoising filter. It averages pixels based on their spatial closeness and radiometric similarity.
Spatial closeness is measured by considering only the local pixel neighborhood given by a structuring element.
Radiometric similarity is defined by the greylevel interval [g-s0, g+s1] where g is the current pixel greylevel.
Only pixels belonging to the structuring element and having a greylevel inside this interval are averaged.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value.
Output image.
See also


Return local mean of an image.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [p0, p1] percentile interval to be considered for computing the value.
Output image.


Return local median of an image.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s. If None, a full square of size 3 is used.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
See also
Implementation of a median filtering which handles images with floating precision.


Return local minimum of an image.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
See also
The lower algorithm complexity makes skimage.filters.rank.minimum more efficient for larger images and structuring elements.


Return local mode of an image.
The mode is the value that appears most often in the local histogram.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Noise feature.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
N. Hashimoto et al. Referenceless image quality evaluation for whole slide imaging. J Pathol Inform 2012;3:9.


Local Otsu’s threshold value for each pixel.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
https://en.wikipedia.org/wiki/Otsu’s_method


Return local percentile of an image.
Returns the value of the p0 lower percentile of the local greyvalue distribution.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Set the percentile value.
Output image.


Return the local number (population) of pixels.
The number of pixels is defined as the number of pixels which are included in the structuring element and the mask.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Return the local number (population) of pixels.
The number of pixels is defined as the number of pixels which are included in the structuring element and the mask. Additionally pixels must have a greylevel inside the interval [g-s0, g+s1] where g is the greyvalue of the center pixel.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value.
Output image.


Return the local number (population) of pixels.
The number of pixels is defined as the number of pixels which are included in the structuring element and the mask.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [p0, p1] percentile interval to be considered for computing the value.
Output image.


Return image subtracted from its local mean.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
Subtracting the mean value may introduce underflow. To compensate this potential underflow, the obtained difference is downscaled by a factor of 2 and shifted by n_bins / 2 - 1, the median value of the local histogram (n_bins = max(3, image.max()) +1 for 16-bits images and 256 otherwise).


Return image subtracted from its local mean.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [p0, p1] percentile interval to be considered for computing the value.
Output image.


Return the local sum of pixels.
Note that the sum may overflow depending on the data type of the input array.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Apply a flat kernel bilateral filter.
This is an edge-preserving and noise reducing denoising filter. It averages pixels based on their spatial closeness and radiometric similarity.
Spatial closeness is measured by considering only the local pixel neighborhood given by a structuring element (selem).
Radiometric similarity is defined by the greylevel interval [g-s0, g+s1] where g is the current pixel greylevel.
Only pixels belonging to the structuring element AND having a greylevel inside this interval are summed.
Note that the sum may overflow depending on the data type of the input array.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value.
Output image.
See also


Return the local sum of pixels.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Note that the sum may overflow depending on the data type of the input array.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Define the [p0, p1] percentile interval to be considered for computing the value.
Output image.


Local threshold of an image.
The resulting binary mask is True if the gray value of the center pixel is greater than the local mean.
Input image.
The neighborhood expressed as an ndarray of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.


Local threshold of an image.
The resulting binary mask is True if the greyvalue of the center pixel is greater than the local mean.
Only greyvalues between percentiles [p0, p1] are considered in the filter.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Set the percentile value.
Output image.


Local top-hat of an image.
This filter computes the morphological opening of the image and then subtracts the result from the original image.
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
Output image.
New in version 0.17.
This function is deprecated and will be removed in scikit-image 0.19. This filter was misnamed and we believe that the usefulness is narrow.


Normalized sliding window histogram
Input image.
The neighborhood expressed as a 2-D array of 1’s and 0’s.
If None, a new array is allocated.
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
The number of histogram bins. Will default to image.max() + 1 if None is passed.
Array of dimensions (H,W,N), where (H,W) are the dimensions of the input image and N is n_bins or image.max() + 1 if no value is provided as a parameter. Effectively, each pixel is a N-D feature vector that is the histogram. The sum of the elements in the feature vector will be 1, unless no pixels in the window were covered by both selem and mask, in which case all elements will be 0.


Return an image of the same shape where each pixel is the index of the pixel value in the ascending order of the unique values of image, aka the rank-order value.
New array where each pixel has the rank-order value of the corresponding pixel in image. Pixel values are between 0 and n - 1, where n is the number of distinct unique values in image.
Unique original values of image


Find the edge magnitude using Roberts’ cross operator.
Image to process.
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result.
The Roberts’ Cross edge map.
See also


Find the cross edges of an image using the Roberts’ Cross operator.
The kernel is applied to the input image to produce separate measurements of the gradient component one orientation.
Image to process.
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result.
The Robert’s edge map.
We use the following kernel:


Find the cross edges of an image using Roberts’ cross operator.
The kernel is applied to the input image to produce separate measurements of the gradient component one orientation.
Image to process.
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result.
The Robert’s edge map.
We use the following kernel:


Filter an image with the Sato tubeness filter.
This filter can be used to detect continuous ridges, e.g. tubes, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects.
Defined only for 2-D and 3-D images. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to tubes, according to the method described in [1].
Array with input image data.
Sigmas used as scales of filter.
When True (the default), the filter detects black ridges; when False, it detects white ridges.
How to handle values outside the image borders.
Used in conjunction with mode ‘constant’, the value outside the image boundaries.
Filtered image (maximum of pixels across all scales).
See also
Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S., Koller, T., …, Kikinis, R. (1998). Three-dimensional multi-scale line filter for segmentation and visualization of curvilinear structures in medical images. Medical image analysis, 2(2), 143-168. DOI:10.1016/S1361-8415(98)80009-1


Find the edge magnitude using the Scharr transform.
The input image.
Clip the output image to this mask. (Values where mask=0 will be set to 0.)
Compute the edge filter along this axis. If not provided, the edge magnitude is computed. This is defined as:
The magnitude is also computed if axis is a sequence.
The boundary mode for the convolution. See scipy.ndimage.convolve for a description of the modes. This can be either a single boundary mode or one boundary mode per axis.
When mode is 'constant', this is the constant used in values outside the boundary of the image data.
The Scharr edge map.
See also
The Scharr operator has a better rotation invariance than other edge filters such as the Sobel or the Prewitt operators.
D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.
https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators


Find the horizontal edges of an image using the Scharr transform.
Image to process.
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result.
The Scharr edge map.
We use the following kernel:
D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.


Find the vertical edges of an image using the Scharr transform.
Image to process
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result.
The Scharr edge map.
We use the following kernel:
D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.


Find edges in an image using the Sobel filter.
The input image.
Clip the output image to this mask. (Values where mask=0 will be set to 0.)
Compute the edge filter along this axis. If not provided, the edge magnitude is computed. This is defined as:
The magnitude is also computed if axis is a sequence.
The boundary mode for the convolution. See scipy.ndimage.convolve for a description of the modes. This can be either a single boundary mode or one boundary mode per axis.
When mode is 'constant', this is the constant used in values outside the boundary of the image data.
The Sobel edge map.
See also
D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.
https://en.wikipedia.org/wiki/Sobel_operator


Find the horizontal edges of an image using the Sobel transform.
Image to process.
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result.
The Sobel edge map.
We use the following kernel:


Find the vertical edges of an image using the Sobel transform.
Image to process.
An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result.
The Sobel edge map.
We use the following kernel:


Return threshold value(s) based on ISODATA method.
Histogram-based threshold, known as Ridler-Calvard method or inter-means. Threshold values returned satisfy the following equality:
That is, returned thresholds are intensities that separate the image into two groups of pixels, where the threshold intensity is midway between the mean intensities of these groups.
For integer images, the above equality holds to within one; for floating- point images, the equality holds to within the histogram bin-width.
Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored.
Input image.
Number of bins used to calculate histogram. This value is ignored for integer arrays.
If False (default), return only the lowest threshold that satisfies the above equality. If True, return all valid thresholds.
Histogram to determine the threshold from and a corresponding array of bin center intensities. Alternatively, only the histogram can be passed.
Threshold value(s).
Ridler, TW & Calvard, S (1978), “Picture thresholding using an iterative selection method” IEEE Transactions on Systems, Man and Cybernetics 8: 630-632, DOI:10.1109/TSMC.1978.4310039
Sezgin M. and Sankur B. (2004) “Survey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146-165, http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf DOI:10.1117/1.1631315
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold


Compute threshold value by Li’s iterative Minimum Cross Entropy method.
Input image.
Finish the computation when the change in the threshold in an iteration is less than this value. By default, this is half the smallest difference between intensity values in image.
Li’s iterative method uses gradient descent to find the optimal threshold. If the image intensity histogram contains more than two modes (peaks), the gradient descent could get stuck in a local optimum. An initial guess for the iteration can help the algorithm find the globally-optimal threshold. A float value defines a specific start point, while a callable should take in an array of image intensities and return a float value. Example valid callables include numpy.mean (default), lambda arr: numpy.quantile(arr, 0.95), or even skimage.filters.threshold_otsu().
A function that will be called on the threshold at every iteration of the algorithm.
Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.
Li C.H. and Lee C.K. (1993) “Minimum Cross Entropy Thresholding” Pattern Recognition, 26(4): 617-625 DOI:10.1016/0031-3203(93)90115-D
Li C.H. and Tam P.K.S. (1998) “An Iterative Algorithm for Minimum Cross Entropy Thresholding” Pattern Recognition Letters, 18(8): 771-776 DOI:10.1016/S0167-8655(98)00057-9
Sezgin M. and Sankur B. (2004) “Survey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146-165 DOI:10.1117/1.1631315
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold


Compute a threshold mask image based on local pixel neighborhood.
Also known as adaptive or dynamic thresholding. The threshold value is the weighted mean for the local neighborhood of a pixel subtracted by a constant. Alternatively the threshold can be determined dynamically by a given function, using the ‘generic’ method.
Input image.
Odd size of pixel neighborhood which is used to calculate the threshold value (e.g. 3, 5, 7, …, 21, …).
Method used to determine adaptive threshold for local neighbourhood in weighted mean image.
By default the ‘gaussian’ method is used.
Constant subtracted from weighted mean of neighborhood to calculate the local threshold value. Default offset is 0.
The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘reflect’.
Either specify sigma for ‘gaussian’ method or function object for ‘generic’ method. This functions takes the flat array of local neighbourhood as a single argument and returns the calculated threshold for the centre pixel.
Value to fill past edges of input if mode is ‘constant’.
Threshold image. All pixels in the input image higher than the corresponding pixel in the threshold image are considered foreground.
https://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#adaptivethreshold


Return threshold value based on the mean of grayscale values.
Grayscale input image.
Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.
C. A. Glasbey, “An analysis of histogram-based thresholding algorithms,” CVGIP: Graphical Models and Image Processing, vol. 55, pp. 532-537, 1993. DOI:10.1006/cgip.1993.1040


Return threshold value based on minimum method.
The histogram of the input image is computed if not provided and smoothed until there are only two maxima. Then the minimum in between is the threshold value.
Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored.
Input image.
Number of bins used to calculate histogram. This value is ignored for integer arrays.
Maximum number of iterations to smooth the histogram.
Histogram to determine the threshold from and a corresponding array of bin center intensities. Alternatively, only the histogram can be passed.
Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.
If unable to find two local maxima in the histogram or if the smoothing takes more than 1e4 iterations.
C. A. Glasbey, “An analysis of histogram-based thresholding algorithms,” CVGIP: Graphical Models and Image Processing, vol. 55, pp. 532-537, 1993.
Prewitt, JMS & Mendelsohn, ML (1966), “The analysis of cell images”, Annals of the New York Academy of Sciences 128: 1035-1053 DOI:10.1111/j.1749-6632.1965.tb11715.x


Generate classes-1 threshold values to divide gray levels in image.
The threshold values are chosen to maximize the total sum of pairwise variances between the thresholded graylevel classes. See Notes and [1] for more details.
Grayscale input image.
Number of classes to be thresholded, i.e. the number of resulting regions.
Number of bins used to calculate the histogram. This value is ignored for integer arrays.
Array containing the threshold values for the desired classes.
If image contains less grayscale value then the desired number of classes.
This implementation relies on a Cython function whose complexity is \(O\left(\frac{Ch^{C-1}}{(C-1)!}\right)\), where \(h\) is the number of histogram bins and \(C\) is the number of classes desired.
The input image must be grayscale.
Liao, P-S., Chen, T-S. and Chung, P-C., “A fast algorithm for multilevel thresholding”, Journal of Information Science and Engineering 17 (5): 713-727, 2001. Available at: <https://ftp.iis.sinica.edu.tw/JISE/2001/200109_01.pdf> DOI:10.6688/JISE.2001.17.5.1
Tosa, Y., “Multi-Otsu Threshold”, a java plugin for ImageJ. Available at: <http://imagej.net/plugins/download/Multi_OtsuThreshold.java>


Applies Niblack local threshold to an array.
A threshold T is calculated for every pixel in the image using the following formula:
where m(x,y) and s(x,y) are the mean and standard deviation of pixel (x,y) neighborhood defined by a rectangular window with size w times w centered around the pixel. k is a configurable parameter that weights the effect of standard deviation.
Input image.
Window size specified as a single odd integer (3, 5, 7, …), or an iterable of length image.ndim containing only odd integers (e.g. (1, 5, 5)).
Value of parameter k in threshold formula.
Threshold mask. All pixels with an intensity higher than this value are assumed to be foreground.
This algorithm is originally designed for text recognition.
The Bradley threshold is a particular case of the Niblack one, being equivalent to
for some value q. By default, Bradley and Roth use q=1.
W. Niblack, An introduction to Digital Image Processing, Prentice-Hall, 1986.
D. Bradley and G. Roth, “Adaptive thresholding using Integral Image”, Journal of Graphics Tools 12(2), pp. 13-21, 2007. DOI:10.1080/2151237X.2007.10129236


Return threshold value based on Otsu’s method.
Either image or hist must be provided. If hist is provided, the actual histogram of the image is ignored.
Grayscale input image.
Number of bins used to calculate histogram. This value is ignored for integer arrays.
Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. An alternative use of this function is to pass it only hist.
Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.
The input image must be grayscale.
Wikipedia, https://en.wikipedia.org/wiki/Otsu’s_Method


Applies Sauvola local threshold to an array. Sauvola is a modification of Niblack technique.
In the original method a threshold T is calculated for every pixel in the image using the following formula:
where m(x,y) and s(x,y) are the mean and standard deviation of pixel (x,y) neighborhood defined by a rectangular window with size w times w centered around the pixel. k is a configurable parameter that weights the effect of standard deviation. R is the maximum standard deviation of a greyscale image.
Input image.
Window size specified as a single odd integer (3, 5, 7, …), or an iterable of length image.ndim containing only odd integers (e.g. (1, 5, 5)).
Value of the positive parameter k.
Value of R, the dynamic range of standard deviation. If None, set to the half of the image dtype range.
Threshold mask. All pixels with an intensity higher than this value are assumed to be foreground.
This algorithm is originally designed for text recognition.
J. Sauvola and M. Pietikainen, “Adaptive document image binarization,” Pattern Recognition 33(2), pp. 225-236, 2000. DOI:10.1016/S0031-3203(99)00055-2


Return threshold value based on the triangle algorithm.
Grayscale input image.
Number of bins used to calculate histogram. This value is ignored for integer arrays.
Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.
Zack, G. W., Rogers, W. E. and Latt, S. A., 1977, Automatic Measurement of Sister Chromatid Exchange Frequency, Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753 DOI:10.1177/25.7.70454
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold


Return threshold value based on Yen’s method. Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored.
Input image.
Number of bins used to calculate histogram. This value is ignored for integer arrays.
Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. An alternative use of this function is to pass it only hist.
Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.
Yen J.C., Chang F.J., and Chang S. (1995) “A New Criterion for Automatic Multilevel Thresholding” IEEE Trans. on Image Processing, 4(3): 370-378. DOI:10.1109/83.366472
Sezgin M. and Sankur B. (2004) “Survey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146-165, DOI:10.1117/1.1631315 http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold


Returns a figure comparing the outputs of different thresholding methods.
Input image.
Figure size (in inches).
Print function name for each method.
Matplotlib figure and axes.
The following algorithms are used:


Unsharp masking filter.
The sharp details are identified as the difference between the original image and its blurred version. These details are then scaled, and added back to the original image.
Input image.
If a scalar is given, then its value is used for all dimensions. If sequence is given, then there must be exactly one radius for each dimension except the last dimension for multichannel images. Note that 0 radius means no blurring, and negative values are not allowed.
The details will be amplified with this factor. The factor could be 0 or negative. Typically, it is a small positive number, e.g. 1.0.
If True, the last image dimension is considered as a color channel, otherwise as spatial. Color channels are processed individually.
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
Image with unsharp mask applied.
Unsharp masking is an image sharpening technique. It is a linear image operation, and numerically stable, unlike deconvolution which is an ill-posed problem. Because of this stability, it is often preferred over deconvolution.
The main idea is as follows: sharp details are identified as the difference between the original image and its blurred version. These details are added back to the original image after a scaling step:
enhanced image = original + amount * (original - blurred)
When applying this filter to several color layers independently, color bleeding may occur. More visually pleasing result can be achieved by processing only the brightness/lightness/intensity channel in a suitable color space such as HSV, HSL, YUV, or YCbCr.
Unsharp masking is described in most introductory digital image processing books. This implementation is based on [1].
Maria Petrou, Costas Petrou “Image Processing: The Fundamentals”, (2010), ed ii., page 357, ISBN 13: 9781119994398 DOI:10.1002/9781119994398
Wikipedia. Unsharp masking https://en.wikipedia.org/wiki/Unsharp_masking


Minimum Mean Square Error (Wiener) inverse filter.
Input data.
Ratio between power spectrum of noise and undegraded image.
Impulse response of the filter. See LPIFilter2D.__init__.
Additional keyword parameters to the impulse_response function.
If you need to apply the same filter multiple times over different images, construct the LPIFilter2D and specify it here.


Return an n-dimensional window of a given size and dimensionality.
The type of window to be created. Any window type supported by scipy.signal.get_window is allowed here. See notes below for a current list, or the SciPy documentation for the version of SciPy on your machine.
The shape of the window along each axis. If an integer is provided, a 1D window is generated.
Keyword arguments passed to skimage.transform.warp (e.g., warp_kwargs={'order':3} to change interpolation method).
A window of the specified shape. dtype is np.double.
This function is based on scipy.signal.get_window and thus can access all of the window types available to that function (e.g., "hann", "boxcar"). Note that certain window types require parameters that have to be supplied with the window name as a tuple (e.g., ("tukey", 0.8)). If only a float is supplied, it is interpreted as the beta parameter of the Kaiser window.
See https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.get_window.html for more details.
Note that this function generates a double precision array of the specified shape and can thus generate very large arrays that consume a large amount of available memory.
The approach taken here to create nD windows is to first calculate the Euclidean distance from the center of the intended nD window to each position in the array. That distance is used to sample, with interpolation, from a 1D window returned from scipy.signal.get_window. The method of interpolation can be changed with the order keyword argument passed to skimage.transform.warp.
Some coordinates in the output window will be outside of the original signal; these will be filled in with zeros.
Window types: - boxcar - triang - blackman - hamming - hann - bartlett - flattop - parzen - bohman - blackmanharris - nuttall - barthann - kaiser (needs beta) - gaussian (needs standard deviation) - general_gaussian (needs power, width) - slepian (needs width) - dpss (needs normalized half-bandwidth) - chebwin (needs attenuation) - exponential (needs decay scale) - tukey (needs taper fraction)
Two-dimensional window design, Wikipedia, https://en.wikipedia.org/wiki/Two_dimensional_window_design
Return a Hann window with shape (512, 512):
Return a Kaiser window with beta parameter of 16 and shape (256, 256, 35):
Return a Tukey window with an alpha parameter of 0.8 and shape (100, 300):


Functionality with an experimental API. Although you can count on the functions in this package being around in the future, the API may change with any version update and will not follow the skimage two-version deprecation path. Therefore, use the functions herein with care, and do not use them in production code that will depend on updated skimage versions.
skimage.future.fit_segmenter(labels, …)
Segmentation using labeled parts of the image and a classifier.
skimage.future.manual_lasso_segmentation(image)
Return a label image based on freeform selections made with the mouse.
skimage.future.manual_polygon_segmentation(image)
Return a label image based on polygon selections made with the mouse.
skimage.future.predict_segmenter(features, clf)
Segmentation of images using a pretrained classifier.
skimage.future.TrainableSegmenter([clf, …])
Estimator for classifying pixels.
skimage.future.graph
Segmentation using labeled parts of the image and a classifier.
Image of labels. Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.
Array of features, with the first dimension corresponding to the number of features, and the other dimensions correspond to labels.shape.
classifier object, exposing a fit and a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier.
classifier trained on labels
Trainable segmentation using local features and random forests
Return a label image based on freeform selections made with the mouse.
Grayscale or RGB image.
Transparency value for polygons drawn over the image.
If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap.
The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew.
Press and hold the left mouse button to draw around each object.
Return a label image based on polygon selections made with the mouse.
Grayscale or RGB image.
Transparency value for polygons drawn over the image.
If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap.
The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew.
Use left click to select the vertices of the polygon and right click to confirm the selection once all vertices are selected.
Segmentation of images using a pretrained classifier.
Array of features, with the last dimension corresponding to the number of features, and the other dimensions are compatible with the shape of the image to segment, or a flattened image.
trained classifier object, exposing a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier. The classifier must be already trained, for example with skimage.segmentation.fit_segmenter().
Labeled array, built from the prediction of the classifier.
Trainable segmentation using local features and random forests
Bases: object
Estimator for classifying pixels.
classifier object, exposing a fit and a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier.
function computing features on all pixels of the image, to be passed to the classifier. The output should be of shape (m_features, *labels.shape). If None, skimage.segmentation.multiscale_basic_features() is used.
fit(image, labels)
Train classifier using partially labeled (annotated) image.
predict(image)
Segment new image using trained internal classifier.
compute_features
Initialize self. See help(type(self)) for accurate signature.
Train classifier using partially labeled (annotated) image.
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.
Labeled array of shape compatible with image (same shape for a single-channel image). Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.
Segment new image using trained internal classifier.
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.


Segmentation using labeled parts of the image and a classifier.
Image of labels. Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.
Array of features, with the first dimension corresponding to the number of features, and the other dimensions correspond to labels.shape.
classifier object, exposing a fit and a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier.
classifier trained on labels


skimage.future.graph.cut_normalized(labels, rag)
Perform Normalized Graph cut on the Region Adjacency Graph.
skimage.future.graph.cut_threshold(labels, …)
Combine regions separated by weight less than threshold.
skimage.future.graph.merge_hierarchical(…)
Perform hierarchical merging of a RAG.
skimage.future.graph.ncut(labels, rag[, …])
Perform Normalized Graph cut on the Region Adjacency Graph.
skimage.future.graph.rag_boundary(labels, …)
Comouter RAG based on region boundaries
skimage.future.graph.rag_mean_color(image, …)
Compute the Region Adjacency Graph using mean colors.
skimage.future.graph.show_rag(labels, rag, image)
Show a Region Adjacency Graph on an image.
skimage.future.graph.RAG([label_image, …])
The Region Adjacency Graph (RAG) of an image, subclasses networx.Graph
Perform Normalized Graph cut on the Region Adjacency Graph.
Given an image’s labels and its similarity RAG, recursively perform a 2-way normalized cut on it. All nodes belonging to a subgraph that cannot be cut further are assigned a unique label in the output.
The array of labels.
The region adjacency graph.
The threshold. A subgraph won’t be further subdivided if the value of the N-cut exceeds thresh.
The number or N-cuts to perform before determining the optimal one.
If set, modifies rag in place. For each node n the function will set a new attribute rag.nodes[n]['ncut label'].
The maximum possible value of an edge in the RAG. This corresponds to an edge between identical regions. This is used to put self edges in the RAG.
If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. The random state is used for the starting point of scipy.sparse.linalg.eigsh.
The new labeled array.
Shi, J.; Malik, J., “Normalized cuts and image segmentation”, Pattern Analysis and Machine Intelligence, IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.
Combine regions separated by weight less than threshold.
Given an image’s labels and its RAG, output new labels by combining regions whose nodes are separated by a weight less than the given threshold.
The array of labels.
The region adjacency graph.
The threshold. Regions connected by edges with smaller weights are combined.
If set, modifies rag in place. The function will remove the edges with weights less that thresh. If set to False the function makes a copy of rag before proceeding.
The new labelled array.
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” DOI:10.1109/83.841950
Perform hierarchical merging of a RAG.
Greedily merges the most similar pair of nodes until no edges lower than thresh remain.
The array of labels.
The Region Adjacency Graph.
Regions connected by an edge with weight smaller than thresh are merged.
If set, the RAG copied before modifying.
If set, the nodes are merged in place. Otherwise, a new node is created for each merge..
This function is called before merging two nodes. For the RAG graph while merging src and dst, it is called as follows merge_func(graph, src, dst).
The function to compute the new weights of the nodes adjacent to the merged node. This is directly supplied as the argument weight_func to merge_nodes.
The new labeled array.
Perform Normalized Graph cut on the Region Adjacency Graph.
Given an image’s labels and its similarity RAG, recursively perform a 2-way normalized cut on it. All nodes belonging to a subgraph that cannot be cut further are assigned a unique label in the output.
The array of labels.
The region adjacency graph.
The threshold. A subgraph won’t be further subdivided if the value of the N-cut exceeds thresh.
The number or N-cuts to perform before determining the optimal one.
If set, modifies rag in place. For each node n the function will set a new attribute rag.nodes[n]['ncut label'].
The maximum possible value of an edge in the RAG. This corresponds to an edge between identical regions. This is used to put self edges in the RAG.
If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. The random state is used for the starting point of scipy.sparse.linalg.eigsh.
The new labeled array.
Shi, J.; Malik, J., “Normalized cuts and image segmentation”, Pattern Analysis and Machine Intelligence, IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.
Comouter RAG based on region boundaries
Given an image’s initial segmentation and its edge map this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within the image with the same label in labels. The weight between two adjacent regions is the average value in edge_map along their boundary.
The labelled image.
This should have the same shape as that of labels. For all pixels along the boundary between 2 adjacent regions, the average value of the corresponding pixels in edge_map is the edge weight between them.
Pixels with a squared distance less than connectivity from each other are considered adjacent. It can range from 1 to labels.ndim. Its behavior is the same as connectivity parameter in scipy.ndimage.filters.generate_binary_structure.
Compute the Region Adjacency Graph using mean colors.
Given an image and its initial segmentation, this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within image with the same label in labels. The weight between two adjacent regions represents how similar or dissimilar two regions are depending on the mode parameter.
Input image.
The labelled image. This should have one dimension less than image. If image has dimensions (M, N, 3) labels should have dimensions (M, N).
Pixels with a squared distance less than connectivity from each other are considered adjacent. It can range from 1 to labels.ndim. Its behavior is the same as connectivity parameter in scipy.ndimage.generate_binary_structure.
The strategy to assign edge weights.
‘distance’ : The weight between two adjacent regions is the \(|c_1 - c_2|\), where \(c_1\) and \(c_2\) are the mean colors of the two regions. It represents the Euclidean distance in their average color.
‘similarity’ : The weight between two adjacent is \(e^{-d^2/sigma}\) where \(d=|c_1 - c_2|\), where \(c_1\) and \(c_2\) are the mean colors of the two regions. It represents how similar two regions are.
Used for computation when mode is “similarity”. It governs how close to each other two colors should be, for their corresponding edge weight to be significant. A very large value of sigma could make any two colors behave as though they were similar.
The region adjacency graph.
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” DOI:10.1109/83.841950
Show a Region Adjacency Graph on an image.
Given a labelled image and its corresponding RAG, show the nodes and edges of the RAG on the image with the specified colors. Edges are displayed between the centroid of the 2 adjacent regions in the image.
The labelled image.
The Region Adjacency Graph.
Input image. If colormap is None, the image should be in RGB format.
Color with which the borders between regions are drawn.
The thickness with which the RAG edges are drawn.
Any matplotlib colormap with which the edges are drawn.
Any matplotlib colormap with which the image is draw. If set to None the image is drawn as it is.
If set, the RAG is modified in place. For each node n the function will set a new attribute rag.nodes[n]['centroid'].
The axes to draw on. If not specified, new axes are created and drawn on.
A colection of lines that represent the edges of the graph. It can be passed to the matplotlib.figure.Figure.colorbar() function.
Bases: networkx.classes.graph.Graph
The Region Adjacency Graph (RAG) of an image, subclasses networx.Graph
An initial segmentation, with each region labeled as a different integer. Every unique value in label_image will correspond to a node in the graph.
The connectivity between pixels in label_image. For a 2D image, a connectivity of 1 corresponds to immediate neighbors up, down, left, and right, while a connectivity of 2 also includes diagonal neighbors. See scipy.ndimage.generate_binary_structure.
Initial or additional edges to pass to the NetworkX Graph constructor. See networkx.Graph. Valid edge specifications include edge list (list of tuples), NumPy arrays, and SciPy sparse matrices.
Additional attributes to add to the graph.
Initialize a graph with edges, name, or graph attributes.
Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
Attributes to add to graph as key=value pairs.
See also
Arbitrary graph attribute pairs (key=value) may be assigned
Add an edge between u and v while updating max node id.
See also
networkx.Graph.add_edge().
Add node n while updating the maximum node id.
See also
networkx.Graph.add_node().
Copy the graph with its max node id.
See also
networkx.Graph.copy().
Return a fresh copy graph with the same data structure.
A fresh copy has no nodes, edges or graph attributes. It is the same data structure as the current graph. This method is typically used to create an empty version of the graph.
This is required when subclassing Graph with networkx v2 and does not cause problems for v1. Here is more detail from the network migrating from 1.x to 2.x document:
Merge node src and dst.
The new combined node is adjacent to all the neighbors of src and dst. weight_func is called to decide the weight of edges incident on the new node.
Nodes to be merged.
Function to decide the attributes of edges incident on the new node. For each neighbor n for src and `dst, weight_func will be called as follows: weight_func(src, dst, n, *extra_arguments, **extra_keywords). src, dst and n are IDs of vertices in the RAG object which is in turn a subclass of networkx.Graph. It is expected to return a dict of attributes of the resulting edge.
If set to True, the merged node has the id dst, else merged node has a new id which is returned.
The sequence of extra positional arguments passed to weight_func.
The dict of keyword arguments passed to the weight_func.
The id of the new node.
If in_place is False the resulting node has a new id, rather than dst.
Returns the id for the new node to be inserted.
The current implementation returns one more than the maximum id.
The id of the new node to be inserted.


Perform Normalized Graph cut on the Region Adjacency Graph.
Given an image’s labels and its similarity RAG, recursively perform a 2-way normalized cut on it. All nodes belonging to a subgraph that cannot be cut further are assigned a unique label in the output.
The array of labels.
The region adjacency graph.
The threshold. A subgraph won’t be further subdivided if the value of the N-cut exceeds thresh.
The number or N-cuts to perform before determining the optimal one.
If set, modifies rag in place. For each node n the function will set a new attribute rag.nodes[n]['ncut label'].
The maximum possible value of an edge in the RAG. This corresponds to an edge between identical regions. This is used to put self edges in the RAG.
If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. The random state is used for the starting point of scipy.sparse.linalg.eigsh.
The new labeled array.
Shi, J.; Malik, J., “Normalized cuts and image segmentation”, Pattern Analysis and Machine Intelligence, IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.


Combine regions separated by weight less than threshold.
Given an image’s labels and its RAG, output new labels by combining regions whose nodes are separated by a weight less than the given threshold.
The array of labels.
The region adjacency graph.
The threshold. Regions connected by edges with smaller weights are combined.
If set, modifies rag in place. The function will remove the edges with weights less that thresh. If set to False the function makes a copy of rag before proceeding.
The new labelled array.
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” DOI:10.1109/83.841950


Perform hierarchical merging of a RAG.
Greedily merges the most similar pair of nodes until no edges lower than thresh remain.
The array of labels.
The Region Adjacency Graph.
Regions connected by an edge with weight smaller than thresh are merged.
If set, the RAG copied before modifying.
If set, the nodes are merged in place. Otherwise, a new node is created for each merge..
This function is called before merging two nodes. For the RAG graph while merging src and dst, it is called as follows merge_func(graph, src, dst).
The function to compute the new weights of the nodes adjacent to the merged node. This is directly supplied as the argument weight_func to merge_nodes.
The new labeled array.


Bases: networkx.classes.graph.Graph
The Region Adjacency Graph (RAG) of an image, subclasses networx.Graph
An initial segmentation, with each region labeled as a different integer. Every unique value in label_image will correspond to a node in the graph.
The connectivity between pixels in label_image. For a 2D image, a connectivity of 1 corresponds to immediate neighbors up, down, left, and right, while a connectivity of 2 also includes diagonal neighbors. See scipy.ndimage.generate_binary_structure.
Initial or additional edges to pass to the NetworkX Graph constructor. See networkx.Graph. Valid edge specifications include edge list (list of tuples), NumPy arrays, and SciPy sparse matrices.
Additional attributes to add to the graph.
Initialize a graph with edges, name, or graph attributes.
Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
Attributes to add to graph as key=value pairs.
See also
Arbitrary graph attribute pairs (key=value) may be assigned
Add an edge between u and v while updating max node id.
See also
networkx.Graph.add_edge().
Add node n while updating the maximum node id.
See also
networkx.Graph.add_node().
Copy the graph with its max node id.
See also
networkx.Graph.copy().
Return a fresh copy graph with the same data structure.
A fresh copy has no nodes, edges or graph attributes. It is the same data structure as the current graph. This method is typically used to create an empty version of the graph.
This is required when subclassing Graph with networkx v2 and does not cause problems for v1. Here is more detail from the network migrating from 1.x to 2.x document:
Merge node src and dst.
The new combined node is adjacent to all the neighbors of src and dst. weight_func is called to decide the weight of edges incident on the new node.
Nodes to be merged.
Function to decide the attributes of edges incident on the new node. For each neighbor n for src and `dst, weight_func will be called as follows: weight_func(src, dst, n, *extra_arguments, **extra_keywords). src, dst and n are IDs of vertices in the RAG object which is in turn a subclass of networkx.Graph. It is expected to return a dict of attributes of the resulting edge.
If set to True, the merged node has the id dst, else merged node has a new id which is returned.
The sequence of extra positional arguments passed to weight_func.
The dict of keyword arguments passed to the weight_func.
The id of the new node.
If in_place is False the resulting node has a new id, rather than dst.
Returns the id for the new node to be inserted.
The current implementation returns one more than the maximum id.
The id of the new node to be inserted.


Add an edge between u and v while updating max node id.
See also
networkx.Graph.add_edge().


Add node n while updating the maximum node id.
See also
networkx.Graph.add_node().


Copy the graph with its max node id.
See also
networkx.Graph.copy().


Return a fresh copy graph with the same data structure.
A fresh copy has no nodes, edges or graph attributes. It is the same data structure as the current graph. This method is typically used to create an empty version of the graph.
This is required when subclassing Graph with networkx v2 and does not cause problems for v1. Here is more detail from the network migrating from 1.x to 2.x document:


Merge node src and dst.
The new combined node is adjacent to all the neighbors of src and dst. weight_func is called to decide the weight of edges incident on the new node.
Nodes to be merged.
Function to decide the attributes of edges incident on the new node. For each neighbor n for src and `dst, weight_func will be called as follows: weight_func(src, dst, n, *extra_arguments, **extra_keywords). src, dst and n are IDs of vertices in the RAG object which is in turn a subclass of networkx.Graph. It is expected to return a dict of attributes of the resulting edge.
If set to True, the merged node has the id dst, else merged node has a new id which is returned.
The sequence of extra positional arguments passed to weight_func.
The dict of keyword arguments passed to the weight_func.
The id of the new node.
If in_place is False the resulting node has a new id, rather than dst.


Returns the id for the new node to be inserted.
The current implementation returns one more than the maximum id.
The id of the new node to be inserted.


Initialize a graph with edges, name, or graph attributes.
Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
Attributes to add to graph as key=value pairs.
See also
Arbitrary graph attribute pairs (key=value) may be assigned


Comouter RAG based on region boundaries
Given an image’s initial segmentation and its edge map this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within the image with the same label in labels. The weight between two adjacent regions is the average value in edge_map along their boundary.
The labelled image.
This should have the same shape as that of labels. For all pixels along the boundary between 2 adjacent regions, the average value of the corresponding pixels in edge_map is the edge weight between them.
Pixels with a squared distance less than connectivity from each other are considered adjacent. It can range from 1 to labels.ndim. Its behavior is the same as connectivity parameter in scipy.ndimage.filters.generate_binary_structure.


Compute the Region Adjacency Graph using mean colors.
Given an image and its initial segmentation, this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within image with the same label in labels. The weight between two adjacent regions represents how similar or dissimilar two regions are depending on the mode parameter.
Input image.
The labelled image. This should have one dimension less than image. If image has dimensions (M, N, 3) labels should have dimensions (M, N).
Pixels with a squared distance less than connectivity from each other are considered adjacent. It can range from 1 to labels.ndim. Its behavior is the same as connectivity parameter in scipy.ndimage.generate_binary_structure.
The strategy to assign edge weights.
‘distance’ : The weight between two adjacent regions is the \(|c_1 - c_2|\), where \(c_1\) and \(c_2\) are the mean colors of the two regions. It represents the Euclidean distance in their average color.
‘similarity’ : The weight between two adjacent is \(e^{-d^2/sigma}\) where \(d=|c_1 - c_2|\), where \(c_1\) and \(c_2\) are the mean colors of the two regions. It represents how similar two regions are.
Used for computation when mode is “similarity”. It governs how close to each other two colors should be, for their corresponding edge weight to be significant. A very large value of sigma could make any two colors behave as though they were similar.
The region adjacency graph.
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” DOI:10.1109/83.841950


Show a Region Adjacency Graph on an image.
Given a labelled image and its corresponding RAG, show the nodes and edges of the RAG on the image with the specified colors. Edges are displayed between the centroid of the 2 adjacent regions in the image.
The labelled image.
The Region Adjacency Graph.
Input image. If colormap is None, the image should be in RGB format.
Color with which the borders between regions are drawn.
The thickness with which the RAG edges are drawn.
Any matplotlib colormap with which the edges are drawn.
Any matplotlib colormap with which the image is draw. If set to None the image is drawn as it is.
If set, the RAG is modified in place. For each node n the function will set a new attribute rag.nodes[n]['centroid'].
The axes to draw on. If not specified, new axes are created and drawn on.
A colection of lines that represent the edges of the graph. It can be passed to the matplotlib.figure.Figure.colorbar() function.


Return a label image based on freeform selections made with the mouse.
Grayscale or RGB image.
Transparency value for polygons drawn over the image.
If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap.
The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew.
Press and hold the left mouse button to draw around each object.


Return a label image based on polygon selections made with the mouse.
Grayscale or RGB image.
Transparency value for polygons drawn over the image.
If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons “overwrite” earlier ones where they overlap.
The segmented regions. If mode is ‘separate’, the leading dimension of the array corresponds to the number of regions that the user drew.
Use left click to select the vertices of the polygon and right click to confirm the selection once all vertices are selected.


Segmentation of images using a pretrained classifier.
Array of features, with the last dimension corresponding to the number of features, and the other dimensions are compatible with the shape of the image to segment, or a flattened image.
trained classifier object, exposing a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier. The classifier must be already trained, for example with skimage.segmentation.fit_segmenter().
Labeled array, built from the prediction of the classifier.


Bases: object
Estimator for classifying pixels.
classifier object, exposing a fit and a predict method as in scikit-learn’s API, for example an instance of RandomForestClassifier or LogisticRegression classifier.
function computing features on all pixels of the image, to be passed to the classifier. The output should be of shape (m_features, *labels.shape). If None, skimage.segmentation.multiscale_basic_features() is used.
fit(image, labels)
Train classifier using partially labeled (annotated) image.
predict(image)
Segment new image using trained internal classifier.
compute_features
Initialize self. See help(type(self)) for accurate signature.
Train classifier using partially labeled (annotated) image.
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.
Labeled array of shape compatible with image (same shape for a single-channel image). Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.
Segment new image using trained internal classifier.
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.


Train classifier using partially labeled (annotated) image.
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.
Labeled array of shape compatible with image (same shape for a single-channel image). Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.


Segment new image using trained internal classifier.
Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with self.features_func.


Initialize self. See help(type(self)) for accurate signature.


skimage.graph.route_through_array(array, …)
Simple example of how to use the MCP and MCP_Geometric classes.
skimage.graph.shortest_path(arr[, reach, …])
Find the shortest path through an n-d array from one side to another.
skimage.graph.MCP(costs[, offsets, …])
A class for finding the minimum cost path through a given n-d costs array.
skimage.graph.MCP_Connect(costs[, offsets, …])
Connect source points using the distance-weighted minimum cost function.
skimage.graph.MCP_Flexible(costs[, offsets, …])
Find minimum cost paths through an N-d costs array.
skimage.graph.MCP_Geometric(costs[, …])
Find distance-weighted minimum cost paths through an n-d costs array.
Simple example of how to use the MCP and MCP_Geometric classes.
See the MCP and MCP_Geometric class documentation for explanation of the path-finding algorithm.
Array of costs.
n-d index into array defining the starting point
n-d index into array defining the end point
If True, diagonal moves are permitted, if False, only axial moves.
If True, the MCP_Geometric class is used to calculate costs, if False, the MCP base class is used. See the class documentation for an explanation of the differences between MCP and MCP_Geometric.
List of n-d index tuples defining the path from start to end.
Cost of the path. If geometric is False, the cost of the path is the sum of the values of array along the path. If geometric is True, a finer computation is made (see the documentation of the MCP_Geometric class).
See also
Find the shortest path through an n-d array from one side to another.
By default (reach = 1), the shortest path can only move one row up or down for every step it moves forward (i.e., the path gradient is limited to 1). reach defines the number of elements that can be skipped along each non-axis dimension at each step.
The axis along which the path must always move forward (default -1)
See return value p for explanation.
For each step along axis, the coordinate of the shortest path. If output_indexlist is True, then the path is returned as a list of n-d tuples that index into arr. If False, then the path is returned as an array listing the coordinates of the path along the non-axis dimensions for each step along the axis dimension. That is, p.shape == (arr.shape[axis], arr.ndim-1) except that p is squeezed before returning so if arr.ndim == 2, then p.shape == (arr.shape[axis],)
Cost of path. This is the absolute sum of all the differences along the path.
Bases: object
A class for finding the minimum cost path through a given n-d costs array.
Given an n-d costs array, this class can be used to find the minimum-cost path through that array from any set of points to any other set of points. Basic usage is to initialize the class and call find_costs() with a one or more starting indices (and an optional list of end indices). After that, call traceback() one or more times to find the path from any given end-position to the closest starting index. New paths through the same costs array can be found by calling find_costs() repeatedly.
The cost of a path is calculated simply as the sum of the values of the costs array at each point on the path. The class MCP_Geometric, on the other hand, accounts for the fact that diagonal vs. axial moves are of different lengths, and weights the path cost accordingly.
Array elements with infinite or negative costs will simply be ignored, as will paths whose cumulative cost overflows to infinite.
A list of offset tuples: each offset specifies a valid move from a given n-d position. If not provided, offsets corresponding to a singly- or fully-connected n-d neighborhood will be constructed with make_offsets(), using the fully_connected parameter value.
If no offsets are provided, this determines the connectivity of the generated neighborhood. If true, the path may go along diagonals between elements of the costs array; otherwise only axial moves are permitted.
For each dimension, specifies the distance between two cells/voxels. If not given or None, the distance is assumed unit.
Equivalent to the offsets provided to the constructor, or if none were so provided, the offsets created for the requested n-d neighborhood. These are useful for interpreting the traceback array returned by the find_costs() method.
See class documentation.
Find the minimum-cost path from the given starting points.
This method finds the minimum-cost path to the specified ending indices from any one of the specified starting indices. If no end positions are given, then the minimum-cost path to every position in the costs array will be found.
A list of n-d starting indices (where n is the dimension of the costs array). The minimum cost path to the closest/cheapest starting point will be found.
A list of n-d ending indices.
If ‘True’ (default), the minimum-cost-path to every specified end-position will be found; otherwise the algorithm will stop when a a path is found to any end-position. (If no ends were specified, then this parameter has no effect.)
Same shape as the costs array; this array records the minimum cost path from the nearest/cheapest starting index to each index considered. (If ends were specified, not all elements in the array will necessarily be considered: positions not evaluated will have a cumulative cost of inf. If find_all_ends is ‘False’, only one of the specified end-positions will have a finite cumulative cost.)
Same shape as the costs array; this array contains the offset to any given index from its predecessor index. The offset indices index into the offsets attribute, which is a array of n-d offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1), that means that the predecessor of [x, y] in the minimum cost path to some start position is [x+1, y+1]. Note that if the offset_index is -1, then the given index was not considered.
int goal_reached(int index, float cumcost) This method is called each iteration after popping an index from the heap, before examining the neighbours.
This method can be overloaded to modify the behavior of the MCP algorithm. An example might be to stop the algorithm when a certain cumulative cost is reached, or when the front is a certain distance away from the seed point.
This method should return 1 if the algorithm should not check the current point’s neighbours and 2 if the algorithm is now done.
Trace a minimum cost path through the pre-calculated traceback array.
This convenience function reconstructs the the minimum cost path to a given end position from one of the starting indices provided to find_costs(), which must have been called previously. This function can be called as many times as desired after find_costs() has been run.
An n-d index into the costs array.
A list of indices into the costs array, starting with one of the start positions passed to find_costs(), and ending with the given end index. These indices specify the minimum-cost path from any given start index to the end index. (The total cost of that path can be read out from the cumulative_costs array returned by find_costs().)
Bases: skimage.graph._mcp.MCP
Connect source points using the distance-weighted minimum cost function.
A front is grown from each seed point simultaneously, while the origin of the front is tracked as well. When two fronts meet, create_connection() is called. This method must be overloaded to deal with the found edges in a way that is appropriate for the application.
Initialize self. See help(type(self)) for accurate signature.
create_connection id1, id2, pos1, pos2, cost1, cost2)
Overload this method to keep track of the connections that are found during MCP processing. Note that a connection with the same ids can be found multiple times (but with different positions and costs).
At the time that this method is called, both points are “frozen” and will not be visited again by the MCP algorithm.
The seed point id where the first neighbor originated from.
The seed point id where the second neighbor originated from.
The index of of the first neighbour in the connection.
The index of of the second neighbour in the connection.
The cumulative cost at pos1.
The cumulative costs at pos2.
Bases: skimage.graph._mcp.MCP
Find minimum cost paths through an N-d costs array.
See the documentation for MCP for full details. This class differs from MCP in that several methods can be overloaded (from pure Python) to modify the behavior of the algorithm and/or create custom algorithms based on MCP. Note that goal_reached can also be overloaded in the MCP class.
See class documentation.
This method is called once for every pair of neighboring nodes, as soon as both nodes are frozen.
This method can be overloaded to obtain information about neightboring nodes, and/or to modify the behavior of the MCP algorithm. One example is the MCP_Connect class, which checks for meeting fronts using this hook.
This method calculates the travel cost for going from the current node to the next. The default implementation returns new_cost. Overload this method to adapt the behaviour of the algorithm.
This method is called when a node is updated, right after new_index is pushed onto the heap and the traceback map is updated.
This method can be overloaded to keep track of other arrays that are used by a specific implementation of the algorithm. For instance the MCP_Connect class uses it to update an id map.
Bases: skimage.graph._mcp.MCP
Find distance-weighted minimum cost paths through an n-d costs array.
See the documentation for MCP for full details. This class differs from MCP in that the cost of a path is not simply the sum of the costs along that path.
This class instead assumes that the costs array contains at each position the “cost” of a unit distance of travel through that position. For example, a move (in 2-d) from (1, 1) to (1, 2) is assumed to originate in the center of the pixel (1, 1) and terminate in the center of (1, 2). The entire move is of distance 1, half through (1, 1) and half through (1, 2); thus the cost of that move is (1/2)*costs[1,1] + (1/2)*costs[1,2].
On the other hand, a move from (1, 1) to (2, 2) is along the diagonal and is sqrt(2) in length. Half of this move is within the pixel (1, 1) and the other half in (2, 2), so the cost of this move is calculated as (sqrt(2)/2)*costs[1,1] + (sqrt(2)/2)*costs[2,2].
These calculations don’t make a lot of sense with offsets of magnitude greater than 1. Use the sampling argument in order to deal with anisotropic data.
See class documentation.


Bases: object
A class for finding the minimum cost path through a given n-d costs array.
Given an n-d costs array, this class can be used to find the minimum-cost path through that array from any set of points to any other set of points. Basic usage is to initialize the class and call find_costs() with a one or more starting indices (and an optional list of end indices). After that, call traceback() one or more times to find the path from any given end-position to the closest starting index. New paths through the same costs array can be found by calling find_costs() repeatedly.
The cost of a path is calculated simply as the sum of the values of the costs array at each point on the path. The class MCP_Geometric, on the other hand, accounts for the fact that diagonal vs. axial moves are of different lengths, and weights the path cost accordingly.
Array elements with infinite or negative costs will simply be ignored, as will paths whose cumulative cost overflows to infinite.
A list of offset tuples: each offset specifies a valid move from a given n-d position. If not provided, offsets corresponding to a singly- or fully-connected n-d neighborhood will be constructed with make_offsets(), using the fully_connected parameter value.
If no offsets are provided, this determines the connectivity of the generated neighborhood. If true, the path may go along diagonals between elements of the costs array; otherwise only axial moves are permitted.
For each dimension, specifies the distance between two cells/voxels. If not given or None, the distance is assumed unit.
Equivalent to the offsets provided to the constructor, or if none were so provided, the offsets created for the requested n-d neighborhood. These are useful for interpreting the traceback array returned by the find_costs() method.
See class documentation.
Find the minimum-cost path from the given starting points.
This method finds the minimum-cost path to the specified ending indices from any one of the specified starting indices. If no end positions are given, then the minimum-cost path to every position in the costs array will be found.
A list of n-d starting indices (where n is the dimension of the costs array). The minimum cost path to the closest/cheapest starting point will be found.
A list of n-d ending indices.
If ‘True’ (default), the minimum-cost-path to every specified end-position will be found; otherwise the algorithm will stop when a a path is found to any end-position. (If no ends were specified, then this parameter has no effect.)
Same shape as the costs array; this array records the minimum cost path from the nearest/cheapest starting index to each index considered. (If ends were specified, not all elements in the array will necessarily be considered: positions not evaluated will have a cumulative cost of inf. If find_all_ends is ‘False’, only one of the specified end-positions will have a finite cumulative cost.)
Same shape as the costs array; this array contains the offset to any given index from its predecessor index. The offset indices index into the offsets attribute, which is a array of n-d offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1), that means that the predecessor of [x, y] in the minimum cost path to some start position is [x+1, y+1]. Note that if the offset_index is -1, then the given index was not considered.
int goal_reached(int index, float cumcost) This method is called each iteration after popping an index from the heap, before examining the neighbours.
This method can be overloaded to modify the behavior of the MCP algorithm. An example might be to stop the algorithm when a certain cumulative cost is reached, or when the front is a certain distance away from the seed point.
This method should return 1 if the algorithm should not check the current point’s neighbours and 2 if the algorithm is now done.
Trace a minimum cost path through the pre-calculated traceback array.
This convenience function reconstructs the the minimum cost path to a given end position from one of the starting indices provided to find_costs(), which must have been called previously. This function can be called as many times as desired after find_costs() has been run.
An n-d index into the costs array.
A list of indices into the costs array, starting with one of the start positions passed to find_costs(), and ending with the given end index. These indices specify the minimum-cost path from any given start index to the end index. (The total cost of that path can be read out from the cumulative_costs array returned by find_costs().)


Find the minimum-cost path from the given starting points.
This method finds the minimum-cost path to the specified ending indices from any one of the specified starting indices. If no end positions are given, then the minimum-cost path to every position in the costs array will be found.
A list of n-d starting indices (where n is the dimension of the costs array). The minimum cost path to the closest/cheapest starting point will be found.
A list of n-d ending indices.
If ‘True’ (default), the minimum-cost-path to every specified end-position will be found; otherwise the algorithm will stop when a a path is found to any end-position. (If no ends were specified, then this parameter has no effect.)
Same shape as the costs array; this array records the minimum cost path from the nearest/cheapest starting index to each index considered. (If ends were specified, not all elements in the array will necessarily be considered: positions not evaluated will have a cumulative cost of inf. If find_all_ends is ‘False’, only one of the specified end-positions will have a finite cumulative cost.)
Same shape as the costs array; this array contains the offset to any given index from its predecessor index. The offset indices index into the offsets attribute, which is a array of n-d offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1), that means that the predecessor of [x, y] in the minimum cost path to some start position is [x+1, y+1]. Note that if the offset_index is -1, then the given index was not considered.


int goal_reached(int index, float cumcost) This method is called each iteration after popping an index from the heap, before examining the neighbours.
This method can be overloaded to modify the behavior of the MCP algorithm. An example might be to stop the algorithm when a certain cumulative cost is reached, or when the front is a certain distance away from the seed point.
This method should return 1 if the algorithm should not check the current point’s neighbours and 2 if the algorithm is now done.


Trace a minimum cost path through the pre-calculated traceback array.
This convenience function reconstructs the the minimum cost path to a given end position from one of the starting indices provided to find_costs(), which must have been called previously. This function can be called as many times as desired after find_costs() has been run.
An n-d index into the costs array.
A list of indices into the costs array, starting with one of the start positions passed to find_costs(), and ending with the given end index. These indices specify the minimum-cost path from any given start index to the end index. (The total cost of that path can be read out from the cumulative_costs array returned by find_costs().)


Bases: skimage.graph._mcp.MCP
Connect source points using the distance-weighted minimum cost function.
A front is grown from each seed point simultaneously, while the origin of the front is tracked as well. When two fronts meet, create_connection() is called. This method must be overloaded to deal with the found edges in a way that is appropriate for the application.
Initialize self. See help(type(self)) for accurate signature.
create_connection id1, id2, pos1, pos2, cost1, cost2)
Overload this method to keep track of the connections that are found during MCP processing. Note that a connection with the same ids can be found multiple times (but with different positions and costs).
At the time that this method is called, both points are “frozen” and will not be visited again by the MCP algorithm.
The seed point id where the first neighbor originated from.
The seed point id where the second neighbor originated from.
The index of of the first neighbour in the connection.
The index of of the second neighbour in the connection.
The cumulative cost at pos1.
The cumulative costs at pos2.


create_connection id1, id2, pos1, pos2, cost1, cost2)
Overload this method to keep track of the connections that are found during MCP processing. Note that a connection with the same ids can be found multiple times (but with different positions and costs).
At the time that this method is called, both points are “frozen” and will not be visited again by the MCP algorithm.
The seed point id where the first neighbor originated from.
The seed point id where the second neighbor originated from.
The index of of the first neighbour in the connection.
The index of of the second neighbour in the connection.
The cumulative cost at pos1.
The cumulative costs at pos2.


Bases: skimage.graph._mcp.MCP
Find minimum cost paths through an N-d costs array.
See the documentation for MCP for full details. This class differs from MCP in that several methods can be overloaded (from pure Python) to modify the behavior of the algorithm and/or create custom algorithms based on MCP. Note that goal_reached can also be overloaded in the MCP class.
See class documentation.
This method is called once for every pair of neighboring nodes, as soon as both nodes are frozen.
This method can be overloaded to obtain information about neightboring nodes, and/or to modify the behavior of the MCP algorithm. One example is the MCP_Connect class, which checks for meeting fronts using this hook.
This method calculates the travel cost for going from the current node to the next. The default implementation returns new_cost. Overload this method to adapt the behaviour of the algorithm.
This method is called when a node is updated, right after new_index is pushed onto the heap and the traceback map is updated.
This method can be overloaded to keep track of other arrays that are used by a specific implementation of the algorithm. For instance the MCP_Connect class uses it to update an id map.


This method is called once for every pair of neighboring nodes, as soon as both nodes are frozen.
This method can be overloaded to obtain information about neightboring nodes, and/or to modify the behavior of the MCP algorithm. One example is the MCP_Connect class, which checks for meeting fronts using this hook.


This method calculates the travel cost for going from the current node to the next. The default implementation returns new_cost. Overload this method to adapt the behaviour of the algorithm.


This method is called when a node is updated, right after new_index is pushed onto the heap and the traceback map is updated.
This method can be overloaded to keep track of other arrays that are used by a specific implementation of the algorithm. For instance the MCP_Connect class uses it to update an id map.


Bases: skimage.graph._mcp.MCP
Find distance-weighted minimum cost paths through an n-d costs array.
See the documentation for MCP for full details. This class differs from MCP in that the cost of a path is not simply the sum of the costs along that path.
This class instead assumes that the costs array contains at each position the “cost” of a unit distance of travel through that position. For example, a move (in 2-d) from (1, 1) to (1, 2) is assumed to originate in the center of the pixel (1, 1) and terminate in the center of (1, 2). The entire move is of distance 1, half through (1, 1) and half through (1, 2); thus the cost of that move is (1/2)*costs[1,1] + (1/2)*costs[1,2].
On the other hand, a move from (1, 1) to (2, 2) is along the diagonal and is sqrt(2) in length. Half of this move is within the pixel (1, 1) and the other half in (2, 2), so the cost of this move is calculated as (sqrt(2)/2)*costs[1,1] + (sqrt(2)/2)*costs[2,2].
These calculations don’t make a lot of sense with offsets of magnitude greater than 1. Use the sampling argument in order to deal with anisotropic data.
See class documentation.


Simple example of how to use the MCP and MCP_Geometric classes.
See the MCP and MCP_Geometric class documentation for explanation of the path-finding algorithm.
Array of costs.
n-d index into array defining the starting point
n-d index into array defining the end point
If True, diagonal moves are permitted, if False, only axial moves.
If True, the MCP_Geometric class is used to calculate costs, if False, the MCP base class is used. See the class documentation for an explanation of the differences between MCP and MCP_Geometric.
List of n-d index tuples defining the path from start to end.
Cost of the path. If geometric is False, the cost of the path is the sum of the values of array along the path. If geometric is True, a finer computation is made (see the documentation of the MCP_Geometric class).
See also


Find the shortest path through an n-d array from one side to another.
By default (reach = 1), the shortest path can only move one row up or down for every step it moves forward (i.e., the path gradient is limited to 1). reach defines the number of elements that can be skipped along each non-axis dimension at each step.
The axis along which the path must always move forward (default -1)
See return value p for explanation.
For each step along axis, the coordinate of the shortest path. If output_indexlist is True, then the path is returned as a list of n-d tuples that index into arr. If False, then the path is returned as an array listing the coordinates of the path along the non-axis dimensions for each step along the axis dimension. That is, p.shape == (arr.shape[axis], arr.ndim-1) except that p is squeezed before returning so if arr.ndim == 2, then p.shape == (arr.shape[axis],)
Cost of path. This is the absolute sum of all the differences along the path.


Convert an image to boolean format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The upper half of the input dtype’s positive range is True, and the lower half is False. All negative values (if present) are False.


Convert an image to floating point format.
This function is similar to img_as_float64, but will not convert lower-precision floating point arrays to float64.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].


Convert an image to single-precision (32-bit) floating point format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].


Convert an image to double-precision (64-bit) floating point format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].