Module: filter¶
Inheritance diagram for skimage.filter:
LPIFilter2D¶
- class skimage.filter.LPIFilter2D(impulse_response, **filter_params)¶
Bases: object
Linear Position-Invariant Filter (2-dimensional)
- __init__(impulse_response, **filter_params)¶
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, example would be called like this:
>>> r = [0,0,0,1,1,1,2,2,2] >>> c = [0,1,2,0,1,2,0,1,2] >>> impulse_response(r, c, **filter_params)
Examples
Gaussian filter:
>>> def filt_func(r, c): return np.exp(-np.hypot(r, c)/1)
>>> filter = LPIFilter2D(filt_func)
skimage.filter.canny(image[, sigma, ...]) | Edge filter an image using the Canny algorithm. |
skimage.filter.hprewitt(image[, mask]) | Find the horizontal edges of an image using the Prewitt transform. |
skimage.filter.hsobel(image[, mask]) | Find the horizontal edges of an image using the Sobel transform. |
skimage.filter.inverse(data[, ...]) | Apply the filter in reverse to the given data. |
skimage.filter.median_filter(image[, ...]) | Masked median filter with octagon shape. |
skimage.filter.prewitt(image[, mask]) | Find the edge magnitude using the Prewitt transform. |
skimage.filter.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.filter.sobel(image[, mask]) | Calculate the absolute magnitude Sobel to find edges. |
skimage.filter.threshold_adaptive(image, ...) | Applies an adaptive threshold to an array. |
skimage.filter.threshold_otsu(image[, nbins]) | Return threshold value based on Otsu’s method. |
skimage.filter.tv_denoise(im[, weight, eps, ...]) | Perform total-variation denoising on 2-d and 3-d images |
skimage.filter.vprewitt(image[, mask]) | Find the vertical edges of an image using the Prewitt transform. |
skimage.filter.vsobel(image[, mask]) | Find the vertical edges of an image using the Sobel transform. |
skimage.filter.wiener(data[, ...]) | Minimum Mean Square Error (Wiener) inverse filter. |
canny¶
- skimage.filter.canny(image, sigma=1.0, low_threshold=0.10000000000000001, high_threshold=0.20000000000000001, mask=None)¶
Edge filter an image using the Canny algorithm.
Parameters : image : array_like, dtype=float
The greyscale input image to detect edges on; should be normalized to 0.0 to 1.0.
sigma : float
The standard deviation of the Gaussian filter
low_threshold : float
The lower bound for hysterisis thresholding (linking edges)
high_threshold : float
The upper bound for hysterisis thresholding (linking edges)
mask : array, dtype=bool, optional
An optional mask to limit the application of Canny to a certain area.
Returns : output : array (image)
The binary edge map.
See also
skimage.sobel
Notes
The steps of the algorithm are as follows:
- Smooth the image using a Gaussian with sigma width.
- Apply the horizontal and vertical Sobel operators to get the gradients within the image. The edge strength is the norm of the gradient.
- Thin potential edges to 1-pixel wide curves. First, find the normal to the edge at each point. This is done by looking at the signs and the relative magnitude of the X-Sobel and Y-Sobel to sort the points into 4 categories: horizontal, vertical, diagonal and antidiagonal. Then look in the normal and reverse directions to see if the values in either of those directions are greater than the point in question. Use interpolation to get a mix of points instead of picking the one that’s the closest to the normal.
- Perform a hysteresis thresholding: first label all points above the high threshold as edges. Then recursively label any point above the low threshold that is 8-connected to a labeled point as an edge.
References
Canny, J., A Computational Approach To Edge Detection, IEEE Trans. Pattern Analysis and Machine Intelligence, 8:679-714, 1986
William Green’ Canny tutorial http://dasl.mem.drexel.edu/alumni/bGreen/www.pages.drexel.edu/_weg22/can_tut.html
Examples
>>> from skimage import filter >>> # Generate noisy image of a square >>> im = np.zeros((256, 256)) >>> im[64:-64, 64:-64] = 1 >>> im += 0.2*np.random.random(im.shape) >>> # First trial with the Canny filter, with the default smoothing >>> edges1 = filter.canny(im) >>> # Increase the smoothing for better results >>> edges2 = filter.canny(im, sigma=3)
hprewitt¶
- skimage.filter.hprewitt(image, mask=None)¶
Find the horizontal edges of an image using the Prewitt transform.
Parameters : image : array_like, dtype=float
Image to process.
mask : array_like, dtype=bool, optional
An optional mask to limit the application to a certain area.
Returns : output : ndarray
The Prewitt edge map.
Notes
We use the following kernel and return the absolute value of the result at each point:
1 1 1 0 0 0 -1 -1 -1
hsobel¶
- skimage.filter.hsobel(image, mask=None)¶
Find the horizontal edges of an image using the Sobel transform.
Parameters : image : array_like, dtype=float
Image to process.
mask : array_like, dtype=bool, optional
An optional mask to limit the application to a certain area.
Returns : output : ndarray
The Sobel edge map.
Notes
We use the following kernel and return the absolute value of the result at each point:
1 2 1 0 0 0 -1 -2 -1
inverse¶
- skimage.filter.inverse(data, impulse_response=None, filter_params={}, max_gain=2, predefined_filter=None)¶
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.
median_filter¶
- skimage.filter.median_filter(image, radius=2, mask=None, percent=50)¶
Masked median filter with octagon shape.
Parameters : image : (M,N) ndarray, dtype uint8
Input image.
radius : {int, 2}, optional
The radius of a circle inscribed into the filtering octagon. Must be at least 2. Default radius is 2.
mask : (M,N) ndarray, dtype uint8, optional
A value of 1 indicates a significant pixel, 0 that a pixel is masked. By default, all pixels are considered.
percent : {int, 50}, optional
The unmasked pixels within the octagon are sorted, and the value at the percent-th index chosen. For example, the default value of 50 chooses the median pixel.
Returns : out : (M,N) ndarray, dtype uint8
Filtered array. In areas where the median filter does not overlap the mask, the filtered result is underfined, but in practice, it will be the lowest value in the valid area.
prewitt¶
- skimage.filter.prewitt(image, mask=None)¶
Find the edge magnitude using the Prewitt transform.
Parameters : image : array_like, dtype=float
Image to process.
mask : array_like, dtype=bool, optional
An optional mask to limit the application to a certain area.
Returns : output : ndarray
The Prewitt edge map.
Notes
Return the square root of the sum of squares of the horizontal and vertical Prewitt transforms.
rank_order¶
- skimage.filter.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.
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]))
sobel¶
- skimage.filter.sobel(image, mask=None)¶
Calculate the absolute magnitude Sobel to find edges.
Parameters : image : array_like, dtype=float
Image to process.
mask : array_like, dtype=bool, optional
An optional mask to limit the application to a certain area.
Returns : output : ndarray
The Sobel edge map.
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.
Note that scipy.ndimage.sobel returns a directional Sobel which has to be further processed to perform edge detection.
threshold_adaptive¶
- skimage.filter.threshold_adaptive(image, block_size, method='gaussian', offset=0, mode='reflect', param=None)¶
Applies an adaptive threshold to an array.
Also known as local or dynamic thresholding where 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 a given function using the ‘generic’ method.
Parameters : image : NxM ndarray
Input image.
block_size : int
Uneven 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 : NxM ndarray
Thresholded binary image
References
- http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations
- .html?highlight=threshold#adaptivethreshold
Examples
>>> from skimage.data import camera >>> image = camera() >>> binary_image1 = threshold_adaptive(image, 15, 'mean') >>> func = lambda arr: arr.mean() >>> binary_image2 = threshold_adaptive(image, 15, 'generic', param=func)
threshold_otsu¶
- skimage.filter.threshold_otsu(image, nbins=256)¶
Return threshold value based on Otsu’s method.
Parameters : image : array
Input image.
nbins : int
Number of bins used to calculate histogram. This value is ignored for integer arrays.
Returns : threshold : float
Threshold value.
References
[R35] Wikipedia, http://en.wikipedia.org/wiki/Otsu’s_Method Examples
>>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_otsu(image) >>> binary = image > thresh
tv_denoise¶
- skimage.filter.tv_denoise(im, weight=50, eps=0.00020000000000000001, keep_type=False, n_iter_max=200)¶
Perform total-variation denoising on 2-d and 3-d images
Parameters : im: ndarray (2d or 3d) of ints, uints or floats :
input data to be denoised. im can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image.
weight: float, optional :
denoising weight. The greater weight, the more denoising (at the expense of fidelity to input)
eps: float, optional :
relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:
(E_(n-1) - E_n) < eps * E_0
keep_type: bool, optional (False) :
whether the output has the same dtype as the input array. keep_type is False by default, and the dtype of the output is np.float
n_iter_max: int, optional :
maximal number of iterations used for the optimization.
Returns : out: ndarray :
denoised array
Notes
The principle of total variation denoising is explained in http://en.wikipedia.org/wiki/Total_variation_denoising
The principle of total variation denoising is to minimize the total variation of the image, which can be roughly described as the integral of the norm of the image gradient. Total variation denoising tends to produce “cartoon-like” images, that is, piecewise-constant images.
This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [R36].
References
[R36] (1, 2) A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 89-97. Examples
>>> import scipy >>> # 2D example using lena >>> lena = scipy.lena() >>> import scipy >>> lena = scipy.lena().astype(np.float) >>> lena += 0.5 * lena.std()*np.random.randn(*lena.shape) >>> denoised_lena = tv_denoise(lena, weight=60) >>> # 3D example on synthetic data >>> x, y, z = np.ogrid[0:40, 0:40, 0:40] >>> mask = (x -22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2 >>> mask = mask.astype(np.float) >>> mask += 0.2*np.random.randn(*mask.shape) >>> res = tv_denoise_3d(mask, weight=100)
vprewitt¶
- skimage.filter.vprewitt(image, mask=None)¶
Find the vertical edges of an image using the Prewitt transform.
Parameters : image : array_like, dtype=float
Image to process.
mask : array_like, dtype=bool, optional
An optional mask to limit the application to a certain area.
Returns : output : ndarray
The Prewitt edge map.
Notes
We use the following kernel and return the absolute value of the result at each point:
1 0 -1 1 0 -1 1 0 -1
vsobel¶
- skimage.filter.vsobel(image, mask=None)¶
Find the vertical edges of an image using the Sobel transform.
Parameters : image : array_like, dtype=float
Image to process
mask : array_like, dtype=bool, optional
An optional mask to limit the application to a certain area
Returns : output : ndarray
The Sobel edge map.
Notes
We use the following kernel and return the absolute value of the result at each point:
1 0 -1 2 0 -2 1 0 -1
wiener¶
- skimage.filter.wiener(data, impulse_response=None, filter_params={}, K=0.25, predefined_filter=None)¶
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.