Docs for 0.13.1
All versions

Module: filters

skimage.filters.copy_func(f[, name]) Create a copy of a function.
skimage.filters.frangi(image[, scale_range, …]) Filter an image with the Frangi filter.
skimage.filters.gabor(image, frequency[, …]) Return real and imaginary responses to Gabor filter.
skimage.filters.gabor_filter(image, frequency) Deprecated function. Use skimage.filters.gabor instead.
skimage.filters.gabor_kernel(frequency[, …]) Return complex 2D Gabor filter kernel.
skimage.filters.gaussian(image[, sigma, …]) Multi-dimensional Gaussian filter.
skimage.filters.gaussian_filter(image[, …]) Deprecated function. Use skimage.filters.gaussian instead.
skimage.filters.hessian(image[, …]) Filter an image with the Hessian filter.
skimage.filters.inverse(data[, …]) Apply the filter in reverse to the given data.
skimage.filters.laplace(image[, ksize, mask]) Find the edges of an image using the Laplace operator.
skimage.filters.median(image[, selem, out, …]) Return local median of an image.
skimage.filters.prewitt(image[, mask]) Find the edge magnitude using the Prewitt transform.
skimage.filters.prewitt_h(image[, mask]) Find the horizontal edges of an image using the Prewitt transform.
skimage.filters.prewitt_v(image[, mask]) Find the vertical edges of an image using the Prewitt transform.
skimage.filters.rank_order(image) 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.
skimage.filters.roberts(image[, mask]) Find the edge magnitude using Roberts’ cross operator.
skimage.filters.roberts_neg_diag(image[, mask]) Find the cross edges of an image using the Roberts’ Cross operator.
skimage.filters.roberts_pos_diag(image[, mask]) Find the cross edges of an image using Roberts’ cross operator.
skimage.filters.scharr(image[, mask]) Find the edge magnitude using the Scharr transform.
skimage.filters.scharr_h(image[, mask]) Find the horizontal edges of an image using the Scharr transform.
skimage.filters.scharr_v(image[, mask]) Find the vertical edges of an image using the Scharr transform.
skimage.filters.sobel(image[, mask]) Find the edge magnitude using the Sobel transform.
skimage.filters.sobel_h(image[, mask]) Find the horizontal edges of an image using the Sobel transform.
skimage.filters.sobel_v(image[, mask]) Find the vertical edges of an image using the Sobel transform.
skimage.filters.threshold_adaptive(image, …) Deprecated function. Use threshold_local instead.
skimage.filters.threshold_isodata(image[, …]) Return threshold value(s) based on ISODATA method.
skimage.filters.threshold_li(image) Return threshold value based on adaptation of Li’s Minimum Cross Entropy method.
skimage.filters.threshold_local(image, …) Compute a threshold mask image based on local pixel neighborhood.
skimage.filters.threshold_mean(image) Return threshold value based on the mean of grayscale values.
skimage.filters.threshold_minimum(image[, …]) Return threshold value based on minimum method.
skimage.filters.threshold_niblack(image[, …]) Applies Niblack local threshold to an array.
skimage.filters.threshold_otsu(image[, nbins]) Return threshold value based on Otsu’s method.
skimage.filters.threshold_sauvola(image[, …]) Applies Sauvola local threshold to an array.
skimage.filters.threshold_triangle(image[, …]) Return threshold value based on the triangle algorithm.
skimage.filters.threshold_yen(image[, nbins]) Return threshold value based on Yen’s method.
skimage.filters.try_all_threshold(image[, …]) Returns a figure comparing the outputs of different thresholding methods.
skimage.filters.wiener(data[, …]) Minimum Mean Square Error (Wiener) inverse filter.
skimage.filters.LPIFilter2D(…) Linear Position-Invariant Filter (2-dimensional)
skimage.filters.deprecated([alt_func, …]) Decorator to mark deprecated functions with warning.
skimage.filters.edges Sobel and Prewitt filters originally part of CellProfiler, code licensed under both GPL and BSD licenses.
skimage.filters.lpi_filter
author:Stefan van der Walt, 2008
skimage.filters.rank
skimage.filters.thresholding

copy_func

skimage.filters.copy_func(f, name=None)[source]

Create a copy of a function.

Parameters:

f : function

Function to copy.

name : str, optional

Name of new function.

frangi

skimage.filters.frangi(image, scale_range=(1, 10), scale_step=2, beta1=0.5, beta2=15, black_ridges=True)[source]

Filter an image with the Frangi filter.

This filter can be used to detect continuous edges, e.g. vessels, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects.

Calculates the eigenvectors of the Hessian to compute the similarity of an image region to vessels, according to the method described in _[1].

Parameters:

image : (N, M) ndarray

Array with input image data.

scale_range : 2-tuple of floats, optional

The range of sigmas used.

scale_step : float, optional

Step size between sigmas.

beta1 : float, optional

Frangi correction constant that adjusts the filter’s sensitivity to deviation from a blob-like structure.

beta2 : float, optional

Frangi correction constant that adjusts the filter’s sensitivity to areas of high variance/texture/structure.

black_ridges : boolean, optional

When True (the default), the filter detects black ridges; when False, it detects white ridges.

Returns:

out : (N, M) ndarray

Filtered image (maximum of pixels across all scales).

Notes

Written by Marc Schrijver, 2/11/2001 Re-Written by D. J. Kroon University of Twente (May 2009)

References

[R483485]A. Frangi, W. Niessen, K. Vincken, and M. Viergever. “Multiscale vessel enhancement filtering,” In LNCS, vol. 1496, pages 130-137, Germany, 1998. Springer-Verlag.
[R484485]Kroon, D.J.: Hessian based Frangi vesselness filter.
[R485485]http://mplab.ucsd.edu/tutorials/gabor.pdf.

gabor

skimage.filters.gabor(image, frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, mode='reflect', cval=0)[source]

Return real and imaginary responses to Gabor filter.

The real and imaginary parts of the Gabor filter kernel are applied to the image and the response is returned as a pair of arrays.

Gabor filter is a linear filter with a Gaussian kernel which is modulated by a sinusoidal plane wave. Frequency and orientation representations of the Gabor filter are similar to those of the human visual system. Gabor filter banks are commonly used in computer vision and image processing. They are especially suitable for edge detection and texture classification.

Parameters:

image : 2-D array

Input image.

frequency : float

Spatial frequency of the harmonic function. Specified in pixels.

theta : float, optional

Orientation in radians. If 0, the harmonic is in the x-direction.

bandwidth : float, optional

The bandwidth captured by the filter. For fixed bandwidth, sigma_x and sigma_y will decrease with increasing frequency. This value is ignored if sigma_x and sigma_y are set by the user.

sigma_x, sigma_y : float, optional

Standard deviation in x- and y-directions. These directions apply to the kernel before rotation. If theta = pi/2, then the kernel is rotated 90 degrees so that sigma_x controls the vertical direction.

n_stds : scalar, optional

The linear size of the kernel is n_stds (3 by default) standard deviations.

offset : float, optional

Phase offset of harmonic function in radians.

mode : {‘constant’, ‘nearest’, ‘reflect’, ‘mirror’, ‘wrap’}, optional

Mode used to convolve image with a kernel, passed to ndi.convolve

cval : scalar, optional

Value to fill past edges of input if mode of convolution is ‘constant’. The parameter is passed to ndi.convolve.

Returns:

real, imag : arrays

Filtered images using the real and imaginary parts of the Gabor filter kernel. Images are of the same dimensions as the input one.

References

[R489490]http://en.wikipedia.org/wiki/Gabor_filter
[R490490]http://mplab.ucsd.edu/tutorials/gabor.pdf

Examples

>>> from skimage.filters import gabor
>>> from skimage import data, io
>>> from matplotlib import pyplot as plt  
>>> image = data.coins()
>>> # detecting edges in a coin image
>>> filt_real, filt_imag = gabor(image, frequency=0.6)
>>> plt.figure()            
>>> io.imshow(filt_real)    
>>> io.show()               
>>> # less sensitivity to finer details with the lower frequency kernel
>>> filt_real, filt_imag = gabor(image, frequency=0.1)
>>> plt.figure()            
>>> io.imshow(filt_real)    
>>> io.show()               

gabor_filter

skimage.filters.gabor_filter(image, frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, mode='reflect', cval=0)[source]

Deprecated function. Use skimage.filters.gabor instead.

Return real and imaginary responses to Gabor filter.

The real and imaginary parts of the Gabor filter kernel are applied to the image and the response is returned as a pair of arrays.

Gabor filter is a linear filter with a Gaussian kernel which is modulated by a sinusoidal plane wave. Frequency and orientation representations of the Gabor filter are similar to those of the human visual system. Gabor filter banks are commonly used in computer vision and image processing. They are especially suitable for edge detection and texture classification.

Parameters:

image : 2-D array

Input image.

frequency : float

Spatial frequency of the harmonic function. Specified in pixels.

theta : float, optional

Orientation in radians. If 0, the harmonic is in the x-direction.

bandwidth : float, optional

The bandwidth captured by the filter. For fixed bandwidth, sigma_x and sigma_y will decrease with increasing frequency. This value is ignored if sigma_x and sigma_y are set by the user.

sigma_x, sigma_y : float, optional

Standard deviation in x- and y-directions. These directions apply to the kernel before rotation. If theta = pi/2, then the kernel is rotated 90 degrees so that sigma_x controls the vertical direction.

n_stds : scalar, optional

The linear size of the kernel is n_stds (3 by default) standard deviations.

offset : float, optional

Phase offset of harmonic function in radians.

mode : {‘constant’, ‘nearest’, ‘reflect’, ‘mirror’, ‘wrap’}, optional

Mode used to convolve image with a kernel, passed to ndi.convolve

cval : scalar, optional

Value to fill past edges of input if mode of convolution is ‘constant’. The parameter is passed to ndi.convolve.

Returns:

real, imag : arrays

Filtered images using the real and imaginary parts of the Gabor filter kernel. Images are of the same dimensions as the input one.

References

[R493494]http://en.wikipedia.org/wiki/Gabor_filter
[R494494]http://mplab.ucsd.edu/tutorials/gabor.pdf

Examples

>>> from skimage.filters import gabor
>>> from skimage import data, io
>>> from matplotlib import pyplot as plt  
>>> image = data.coins()
>>> # detecting edges in a coin image
>>> filt_real, filt_imag = gabor(image, frequency=0.6)
>>> plt.figure()            
>>> io.imshow(filt_real)    
>>> io.show()               
>>> # less sensitivity to finer details with the lower frequency kernel
>>> filt_real, filt_imag = gabor(image, frequency=0.1)
>>> plt.figure()            
>>> io.imshow(filt_real)    
>>> io.show()               

gabor_kernel

skimage.filters.gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0)[source]

Return complex 2D Gabor filter kernel.

Gabor kernel is a Gaussian kernel modulated by a complex harmonic function. Harmonic function consists of an imaginary sine function and a real cosine function. Spatial frequency is inversely proportional to the wavelength of the harmonic and to the standard deviation of a Gaussian kernel. The bandwidth is also inversely proportional to the standard deviation.

Parameters:

frequency : float

Spatial frequency of the harmonic function. Specified in pixels.

theta : float, optional

Orientation in radians. If 0, the harmonic is in the x-direction.

bandwidth : float, optional

The bandwidth captured by the filter. For fixed bandwidth, sigma_x and sigma_y will decrease with increasing frequency. This value is ignored if sigma_x and sigma_y are set by the user.

sigma_x, sigma_y : float, optional

Standard deviation in x- and y-directions. These directions apply to the kernel before rotation. If theta = pi/2, then the kernel is rotated 90 degrees so that sigma_x controls the vertical direction.

n_stds : scalar, optional

The linear size of the kernel is n_stds (3 by default) standard deviations

offset : float, optional

Phase offset of harmonic function in radians.

Returns:

g : complex array

Complex filter kernel.

References

[R497498]http://en.wikipedia.org/wiki/Gabor_filter
[R498498]http://mplab.ucsd.edu/tutorials/gabor.pdf

Examples

>>> from skimage.filters import gabor_kernel
>>> from skimage import io
>>> from matplotlib import pyplot as plt  
>>> gk = gabor_kernel(frequency=0.2)
>>> plt.figure()        
>>> io.imshow(gk.real)  
>>> io.show()           
>>> # more ripples (equivalent to increasing the size of the
>>> # Gaussian spread)
>>> gk = gabor_kernel(frequency=0.2, bandwidth=0.1)
>>> plt.figure()        
>>> io.imshow(gk.real)  
>>> io.show()           

gaussian

skimage.filters.gaussian(image, sigma=1, output=None, mode='nearest', cval=0, multichannel=None, preserve_range=False, truncate=4.0)[source]

Multi-dimensional Gaussian filter.

Parameters:

image : array-like

Input image (grayscale or color) to filter.

sigma : scalar or sequence of scalars, optional

Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.

output : array, optional

The output parameter passes an array in which to store the filter output.

mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional

The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘nearest’.

cval : scalar, optional

Value to fill past edges of input if mode is ‘constant’. Default is 0.0

multichannel : bool, optional (default: None)

Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If None, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3).

preserve_range : bool, optional

Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.

truncate : float, optional

Truncate the filter at this many standard deviations.

Returns:

filtered_image : ndarray

the filtered array

Notes

This function is a wrapper around scipy.ndi.gaussian_filter().

Integer arrays are converted to float.

The multi-dimensional filter is implemented as a sequence of one-dimensional convolution filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision.

Examples

>>> a = np.zeros((3, 3))
>>> a[1, 1] = 1
>>> a
array([[ 0.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  0.]])
>>> gaussian(a, sigma=0.4)  # mild smoothing
array([[ 0.00163116,  0.03712502,  0.00163116],
       [ 0.03712502,  0.84496158,  0.03712502],
       [ 0.00163116,  0.03712502,  0.00163116]])
>>> gaussian(a, sigma=1)  # more smoothing
array([[ 0.05855018,  0.09653293,  0.05855018],
       [ 0.09653293,  0.15915589,  0.09653293],
       [ 0.05855018,  0.09653293,  0.05855018]])
>>> # Several modes are possible for handling boundaries
>>> gaussian(a, sigma=1, mode='reflect')
array([[ 0.08767308,  0.12075024,  0.08767308],
       [ 0.12075024,  0.16630671,  0.12075024],
       [ 0.08767308,  0.12075024,  0.08767308]])
>>> # For RGB images, each is filtered separately
>>> from skimage.data import astronaut
>>> image = astronaut()
>>> filtered_img = gaussian(image, sigma=1, multichannel=True)

gaussian_filter

skimage.filters.gaussian_filter(image, sigma=1, output=None, mode='nearest', cval=0, multichannel=None, preserve_range=False, truncate=4.0)[source]

Deprecated function. Use skimage.filters.gaussian instead.

Multi-dimensional Gaussian filter.

Parameters:

image : array-like

Input image (grayscale or color) to filter.

sigma : scalar or sequence of scalars, optional

Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.

output : array, optional

The output parameter passes an array in which to store the filter output.

mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional

The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘nearest’.

cval : scalar, optional

Value to fill past edges of input if mode is ‘constant’. Default is 0.0

multichannel : bool, optional (default: None)

Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If None, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3).

preserve_range : bool, optional

Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.

truncate : float, optional

Truncate the filter at this many standard deviations.

Returns:

filtered_image : ndarray

the filtered array

Notes

This function is a wrapper around scipy.ndi.gaussian_filter().

Integer arrays are converted to float.

The multi-dimensional filter is implemented as a sequence of one-dimensional convolution filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision.

Examples

>>> a = np.zeros((3, 3))
>>> a[1, 1] = 1
>>> a
array([[ 0.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  0.]])
>>> gaussian(a, sigma=0.4)  # mild smoothing
array([[ 0.00163116,  0.03712502,  0.00163116],
       [ 0.03712502,  0.84496158,  0.03712502],
       [ 0.00163116,  0.03712502,  0.00163116]])
>>> gaussian(a, sigma=1)  # more smoothing
array([[ 0.05855018,  0.09653293,  0.05855018],
       [ 0.09653293,  0.15915589,  0.09653293],
       [ 0.05855018,  0.09653293,  0.05855018]])
>>> # Several modes are possible for handling boundaries
>>> gaussian(a, sigma=1, mode='reflect')
array([[ 0.08767308,  0.12075024,  0.08767308],
       [ 0.12075024,  0.16630671,  0.12075024],
       [ 0.08767308,  0.12075024,  0.08767308]])
>>> # For RGB images, each is filtered separately
>>> from skimage.data import astronaut
>>> image = astronaut()
>>> filtered_img = gaussian(image, sigma=1, multichannel=True)

hessian

skimage.filters.hessian(image, scale_range=(1, 10), scale_step=2, beta1=0.5, beta2=15)[source]

Filter an image with the Hessian filter.

This filter can be used to detect continuous edges, e.g. vessels, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects.

Almost equal to Frangi filter, but uses alternative method of smoothing. Refer to _[1] to find the differences between Frangi and Hessian filters.

Parameters:

image : (N, M) ndarray

Array with input image data.

scale_range : 2-tuple of floats, optional

The range of sigmas used.

scale_step : float, optional

Step size between sigmas.

beta1 : float, optional

Frangi correction constant that adjusts the filter’s sensitivity to deviation from a blob-like structure.

beta2 : float, optional

Frangi correction constant that adjusts the filter’s sensitivity to areas of high variance/texture/structure.

Returns:

out : (N, M) ndarray

Filtered image (maximum of pixels across all scales).

Notes

Written by Marc Schrijver, 2/11/2001 Re-Written by D. J. Kroon University of Twente (May 2009)

References

[R501501]Choon-Ching Ng, Moi Hoon Yap, Nicholas Costen and Baihua Li, “Automatic Wrinkle Detection using Hybrid Hessian Filter”.

inverse

skimage.filters.inverse(data, impulse_response=None, filter_params={}, max_gain=2, predefined_filter=None)[source]

Apply the filter in reverse to the given data.

Parameters:

data : (M,N) ndarray

Input data.

impulse_response : callable f(r, c, **filter_params)

Impulse response of the filter. See LPIFilter2D.__init__.

filter_params : dict

Additional keyword parameters to the impulse_response function.

max_gain : float

Limit the filter gain. Often, the filter contains zeros, which would cause the inverse filter to have infinite gain. High gain causes amplification of artefacts, so a conservative limit is recommended.

Other Parameters:
 

predefined_filter : LPIFilter2D

If you need to apply the same filter multiple times over different images, construct the LPIFilter2D and specify it here.

laplace

skimage.filters.laplace(image, ksize=3, mask=None)[source]

Find the edges of an image using the Laplace operator.

Parameters:

image : ndarray

Image to process.

ksize : int, optional

Define the size of the discrete Laplacian operator such that it will have a size of (ksize,) * image.ndim.

mask : ndarray, optional

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.

Returns:

output : ndarray

The Laplace edge map.

Notes

The Laplacian operator is generated using the function skimage.restoration.uft.laplacian().

median

skimage.filters.median(image, selem=None, out=None, mask=None, shift_x=False, shift_y=False)[source]

Return local median of an image.

Parameters:

image : 2-D array (uint8, uint16)

Input image.

selem : 2-D array, optional

The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, a full square of size 3 is used.

out : 2-D array (same dtype as input)

If None, a new array is allocated.

mask : ndarray

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

shift_x, shift_y : int

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

Returns:

out : 2-D array (same dtype as input image)

Output image.

Examples

>>> from skimage import data
>>> from skimage.morphology import disk
>>> from skimage.filters.rank import median
>>> img = data.camera()
>>> med = median(img, disk(5))

prewitt

skimage.filters.prewitt(image, mask=None)[source]

Find the edge magnitude using the Prewitt transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Prewitt edge map.

See also

sobel, scharr

Notes

Return the square root of the sum of squares of the horizontal and vertical Prewitt transforms. The edge magnitude depends slightly on edge directions, since the approximation of the gradient operator by the Prewitt operator is not completely rotation invariant. For a better rotation invariance, the Scharr operator should be used. The Sobel operator has a better rotation invariance than the Prewitt operator, but a worse rotation invariance than the Scharr operator.

Examples

>>> from skimage import data
>>> camera = data.camera()
>>> from skimage import filters
>>> edges = filters.prewitt(camera)

prewitt_h

skimage.filters.prewitt_h(image, mask=None)[source]

Find the horizontal edges of an image using the Prewitt transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Prewitt edge map.

Notes

We use the following kernel:

 1   1   1
 0   0   0
-1  -1  -1

prewitt_v

skimage.filters.prewitt_v(image, mask=None)[source]

Find the vertical edges of an image using the Prewitt transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Prewitt edge map.

Notes

We use the following kernel:

1   0  -1
1   0  -1
1   0  -1

rank_order

skimage.filters.rank_order(image)[source]

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.

Parameters:

image: ndarray

Returns:

labels: ndarray of type np.uint32, of shape image.shape

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.

original_values: 1-D ndarray

Unique original values of image

Examples

>>> a = np.array([[1, 4, 5], [4, 4, 1], [5, 1, 1]])
>>> a
array([[1, 4, 5],
       [4, 4, 1],
       [5, 1, 1]])
>>> rank_order(a)
(array([[0, 1, 2],
       [1, 1, 0],
       [2, 0, 0]], dtype=uint32), array([1, 4, 5]))
>>> b = np.array([-1., 2.5, 3.1, 2.5])
>>> rank_order(b)
(array([0, 1, 2, 1], dtype=uint32), array([-1. ,  2.5,  3.1]))

roberts

skimage.filters.roberts(image, mask=None)[source]

Find the edge magnitude using Roberts’ cross operator.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Roberts’ Cross edge map.

See also

sobel, scharr, prewitt, feature.canny

Examples

>>> from skimage import data
>>> camera = data.camera()
>>> from skimage import filters
>>> edges = filters.roberts(camera)

roberts_neg_diag

skimage.filters.roberts_neg_diag(image, mask=None)[source]

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.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Robert’s edge map.

Notes

We use the following kernel:

 0   1
-1   0

roberts_pos_diag

skimage.filters.roberts_pos_diag(image, mask=None)[source]

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.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Robert’s edge map.

Notes

We use the following kernel:

1   0
0  -1

scharr

skimage.filters.scharr(image, mask=None)[source]

Find the edge magnitude using the Scharr transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Scharr edge map.

See also

sobel, prewitt, canny

Notes

Take the square root of the sum of the squares of the horizontal and vertical Scharrs to get a magnitude that is somewhat insensitive to direction. The Scharr operator has a better rotation invariance than other edge filters such as the Sobel or the Prewitt operators.

References

[R503504]D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.
[R504504]http://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators

Examples

>>> from skimage import data
>>> camera = data.camera()
>>> from skimage import filters
>>> edges = filters.scharr(camera)

scharr_h

skimage.filters.scharr_h(image, mask=None)[source]

Find the horizontal edges of an image using the Scharr transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Scharr edge map.

Notes

We use the following kernel:

 3   10   3
 0    0   0
-3  -10  -3

References

[R507507]D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.

scharr_v

skimage.filters.scharr_v(image, mask=None)[source]

Find the vertical edges of an image using the Scharr transform.

Parameters:

image : 2-D array

Image to process

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Scharr edge map.

Notes

We use the following kernel:

 3   0   -3
10   0  -10
 3   0   -3

References

[R509509]D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.

sobel

skimage.filters.sobel(image, mask=None)[source]

Find the edge magnitude using the Sobel transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Sobel edge map.

See also

scharr, prewitt, roberts, feature.canny

Notes

Take the square root of the sum of the squares of the horizontal and vertical Sobels to get a magnitude that’s somewhat insensitive to direction.

The 3x3 convolution kernel used in the horizontal and vertical Sobels is an approximation of the gradient of the image (with some slight blurring since 9 pixels are used to compute the gradient at a given pixel). As an approximation of the gradient, the Sobel operator is not completely rotation-invariant. The Scharr operator should be used for a better rotation invariance.

Note that scipy.ndimage.sobel returns a directional Sobel which has to be further processed to perform edge detection.

Examples

>>> from skimage import data
>>> camera = data.camera()
>>> from skimage import filters
>>> edges = filters.sobel(camera)

sobel_h

skimage.filters.sobel_h(image, mask=None)[source]

Find the horizontal edges of an image using the Sobel transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Sobel edge map.

Notes

We use the following kernel:

 1   2   1
 0   0   0
-1  -2  -1

sobel_v

skimage.filters.sobel_v(image, mask=None)[source]

Find the vertical edges of an image using the Sobel transform.

Parameters:

image : 2-D array

Image to process.

mask : 2-D array, optional

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.

Returns:

output : 2-D array

The Sobel edge map.

Notes

We use the following kernel:

1   0  -1
2   0  -2
1   0  -1

threshold_adaptive

skimage.filters.threshold_adaptive(image, block_size, method='gaussian', offset=0, mode='reflect', param=None)[source]

Deprecated function. Use threshold_local instead.

threshold_isodata

skimage.filters.threshold_isodata(image, nbins=256, return_all=False)[source]

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:

threshold = (image[image <= threshold].mean() +
image[image > threshold].mean()) / 2.0

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.

Parameters:

image : (N, M) ndarray

Input image.

nbins : int, optional

Number of bins used to calculate histogram. This value is ignored for integer arrays.

return_all: bool, optional

If False (default), return only the lowest threshold that satisfies the above equality. If True, return all valid thresholds.

Returns:

threshold : float or int or array

Threshold value(s).

References

[R511513]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
[R512513]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
[R513513]ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold

Examples

>>> from skimage.data import coins
>>> image = coins()
>>> thresh = threshold_isodata(image)
>>> binary = image > thresh

threshold_li

skimage.filters.threshold_li(image)[source]

Return threshold value based on adaptation of Li’s Minimum Cross Entropy method.

Parameters:

image : (N, M) ndarray

Input image.

Returns:

threshold : float

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

References

[R517520]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
[R518520]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
[R519520]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
[R520520]ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold

Examples

>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_li(image)
>>> binary = image > thresh

threshold_local

skimage.filters.threshold_local(image, block_size, method='gaussian', offset=0, mode='reflect', param=None)[source]

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.

Parameters:

image : (N, M) ndarray

Input image.

block_size : int

Odd size of pixel neighborhood which is used to calculate the threshold value (e.g. 3, 5, 7, …, 21, …).

method : {‘generic’, ‘gaussian’, ‘mean’, ‘median’}, optional

Method used to determine adaptive threshold for local neighbourhood in weighted mean image.

  • ‘generic’: use custom function (see param parameter)
  • ‘gaussian’: apply gaussian filter (see param parameter for custom sigma value)
  • ‘mean’: apply arithmetic mean filter
  • ‘median’: apply median rank filter

By default the ‘gaussian’ method is used.

offset : float, optional

Constant subtracted from weighted mean of neighborhood to calculate the local threshold value. Default offset is 0.

mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional

The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘reflect’.

param : {int, function}, optional

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.

Returns:

threshold : (N, M) ndarray

Threshold image. All pixels in the input image higher than the corresponding pixel in the threshold image are considered foreground.

References

[R525525]http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#adaptivethreshold

Examples

>>> from skimage.data import camera
>>> image = camera()[:50, :50]
>>> binary_image1 = image > threshold_local(image, 15, 'mean')
>>> func = lambda arr: arr.mean()
>>> binary_image2 = image > threshold_local(image, 15, 'generic',
...                                         param=func)

threshold_mean

skimage.filters.threshold_mean(image)[source]

Return threshold value based on the mean of grayscale values.

Parameters:

image : (N, M[, …, P]) ndarray

Grayscale input image.

Returns:

threshold : float

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

References

[R527527]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

Examples

>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_mean(image)
>>> binary = image > thresh

threshold_minimum

skimage.filters.threshold_minimum(image, nbins=256, max_iter=10000)[source]

Return threshold value based on minimum method.

The histogram of the input image is computed and smoothed until there are only two maxima. Then the minimum in between is the threshold value.

Parameters:

image : (M, N) ndarray

Input image.

nbins : int, optional

Number of bins used to calculate histogram. This value is ignored for integer arrays.

max_iter: int, optional

Maximum number of iterations to smooth the histogram.

Returns:

threshold : float

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

Raises:

RuntimeError

If unable to find two local maxima in the histogram or if the smoothing takes more than 1e4 iterations.

References

[R529530]C. A. Glasbey, “An analysis of histogram-based thresholding algorithms,” CVGIP: Graphical Models and Image Processing, vol. 55, pp. 532-537, 1993.
[R530530]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

Examples

>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_minimum(image)
>>> binary = image > thresh

threshold_niblack

skimage.filters.threshold_niblack(image, window_size=15, k=0.2)[source]

Applies Niblack local threshold to an array.

A threshold T is calculated for every pixel in the image using the following formula:

T = m(x,y) - k * s(x,y)

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.

Parameters:

image: (N, M) ndarray

Grayscale input image.

window_size : int, optional

Odd size of pixel neighborhood window (e.g. 3, 5, 7…).

k : float, optional

Value of parameter k in threshold formula.

Returns:

threshold : (N, M) ndarray

Threshold mask. All pixels with an intensity higher than this value are assumed to be foreground.

Notes

This algorithm is originally designed for text recognition.

References

[R533533]Niblack, W (1986), An introduction to Digital Image Processing, Prentice-Hall.

Examples

>>> from skimage import data
>>> image = data.page()
>>> binary_image = threshold_niblack(image, window_size=7, k=0.1)

threshold_otsu

skimage.filters.threshold_otsu(image, nbins=256)[source]

Return threshold value based on Otsu’s method.

Parameters:

image : (N, M) ndarray

Grayscale input image.

nbins : int, optional

Number of bins used to calculate histogram. This value is ignored for integer arrays.

Returns:

threshold : float

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

Raises:

ValueError

If image only contains a single grayscale value.

Notes

The input image must be grayscale.

References

[R535535]Wikipedia, http://en.wikipedia.org/wiki/Otsu’s_Method

Examples

>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_otsu(image)
>>> binary = image <= thresh

threshold_sauvola

skimage.filters.threshold_sauvola(image, window_size=15, k=0.2, r=None)[source]

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:

T = m(x,y) * (1 + k * ((s(x,y) / R) - 1))

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.

Parameters:

image: (N, M) ndarray

Grayscale input image.

window_size : int, optional

Odd size of pixel neighborhood window (e.g. 3, 5, 7…).

k : float, optional

Value of the positive parameter k.

r : float, optional

Value of R, the dynamic range of standard deviation. If None, set to the half of the image dtype range.

Returns:

threshold : (N, M) ndarray

Threshold mask. All pixels with an intensity higher than this value are assumed to be foreground.

Notes

This algorithm is originally designed for text recognition.

References

[R537537]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

Examples

>>> from skimage import data
>>> image = data.page()
>>> binary_sauvola = threshold_sauvola(image,
...                                    window_size=15, k=0.2)

threshold_triangle

skimage.filters.threshold_triangle(image, nbins=256)[source]

Return threshold value based on the triangle algorithm.

Parameters:

image : (N, M[, …, P]) ndarray

Grayscale input image.

nbins : int, optional

Number of bins used to calculate histogram. This value is ignored for integer arrays.

Returns:

threshold : float

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

References

[R539540]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
[R540540]ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold

Examples

>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_triangle(image)
>>> binary = image > thresh

threshold_yen

skimage.filters.threshold_yen(image, nbins=256)[source]

Return threshold value based on Yen’s method.

Parameters:

image : (N, M) ndarray

Input image.

nbins : int, optional

Number of bins used to calculate histogram. This value is ignored for integer arrays.

Returns:

threshold : float

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

References

[R543545]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
[R544545]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
[R545545]ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold

Examples

>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_yen(image)
>>> binary = image <= thresh

try_all_threshold

skimage.filters.try_all_threshold(image, figsize=(8, 5), verbose=True)[source]

Returns a figure comparing the outputs of different thresholding methods.

Parameters:

image : (N, M) ndarray

Input image.

figsize : tuple, optional

Figure size (in inches).

verbose : bool, optional

Print function name for each method.

Returns:

fig, ax : tuple

Matplotlib figure and axes.

Notes

The following algorithms are used:

  • isodata
  • li
  • mean
  • minimum
  • otsu
  • triangle
  • yen

Examples

>>> from skimage.data import text
>>> fig, ax = try_all_threshold(text(), figsize=(10, 6), verbose=False)

wiener

skimage.filters.wiener(data, impulse_response=None, filter_params={}, K=0.25, predefined_filter=None)[source]

Minimum Mean Square Error (Wiener) inverse filter.

Parameters:

data : (M,N) ndarray

Input data.

K : float or (M,N) ndarray

Ratio between power spectrum of noise and undegraded image.

impulse_response : callable f(r, c, **filter_params)

Impulse response of the filter. See LPIFilter2D.__init__.

filter_params : dict

Additional keyword parameters to the impulse_response function.

Other Parameters:
 

predefined_filter : LPIFilter2D

If you need to apply the same filter multiple times over different images, construct the LPIFilter2D and specify it here.

LPIFilter2D

class skimage.filters.LPIFilter2D(impulse_response, **filter_params)[source]

Bases: object

Linear Position-Invariant Filter (2-dimensional)

__init__(impulse_response, **filter_params)[source]
Parameters:

impulse_response : callable f(r, c, **filter_params)

Function that yields the impulse response. r and c are 1-dimensional vectors that represent row and column positions, in other words coordinates are (r[0],c[0]),(r[0],c[1]) etc. **filter_params are passed through.

In other words, impulse_response would be called like this:

>>> def impulse_response(r, c, **filter_params):
...     pass
>>>
>>> r = [0,0,0,1,1,1,2,2,2]
>>> c = [0,1,2,0,1,2,0,1,2]
>>> filter_params = {'kw1': 1, 'kw2': 2, 'kw3': 3}
>>> impulse_response(r, c, **filter_params)

Examples

Gaussian filter: Use a 1-D gaussian in each direction without normalization coefficients.

>>> def filt_func(r, c, sigma = 1):
...     return np.exp(-np.hypot(r, c)/sigma)
>>> filter = LPIFilter2D(filt_func)

deprecated

class skimage.filters.deprecated(alt_func=None, behavior='warn', removed_version=None)[source]

Bases: object

Decorator to mark deprecated functions with warning.

Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.

Parameters:

alt_func : str

If given, tell user what function to use instead.

behavior : {‘warn’, ‘raise’}

Behavior during call to deprecated function: ‘warn’ = warn user that function is deprecated; ‘raise’ = raise error.

removed_version : str

The package version in which the deprecated function will be removed.

__init__(alt_func=None, behavior='warn', removed_version=None)[source]