scipy.ndimage.generic_filter#
- scipy.ndimage.generic_filter(input, function, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0, extra_arguments=(), extra_keywords=None)[source]#
Calculate a multidimensional filter using the given function.
At each element the provided function is called. The input values within the filter footprint at that element are passed to the function as a 1-D array of double values.
- Parameters:
- inputarray_like
The input array.
- function{callable, scipy.LowLevelCallable}
Function to apply at each element.
- sizescalar or tuple, optional
See footprint, below. Ignored if footprint is given.
- footprintarray, optional
Either size or footprint must be defined. size gives the shape that is taken from the input array, at every element position, to define the input to the filter function. footprint is a boolean array that specifies (implicitly) a shape, but also which of the elements within this shape will get passed to the filter function. Thus
size=(n,m)
is equivalent tofootprint=np.ones((n,m))
. We adjust size to the number of dimensions of the input array, so that, if the input array is shape (10,10,10), and size is 2, then the actual size used is (2,2,2). When footprint is given, size is ignored.- outputarray or dtype, optional
The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.
- mode{‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional
The mode parameter determines how the input array is extended beyond its boundaries. Default is ‘reflect’. Behavior for each valid value is as follows:
- ‘reflect’ (d c b a | a b c d | d c b a)
The input is extended by reflecting about the edge of the last pixel. This mode is also sometimes referred to as half-sample symmetric.
- ‘constant’ (k k k k | a b c d | k k k k)
The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter.
- ‘nearest’ (a a a a | a b c d | d d d d)
The input is extended by replicating the last pixel.
- ‘mirror’ (d c b | a b c d | c b a)
The input is extended by reflecting about the center of the last pixel. This mode is also sometimes referred to as whole-sample symmetric.
- ‘wrap’ (a b c d | a b c d | a b c d)
The input is extended by wrapping around to the opposite edge.
For consistency with the interpolation functions, the following mode names can also be used:
- ‘grid-mirror’
This is a synonym for ‘reflect’.
- ‘grid-constant’
This is a synonym for ‘constant’.
- ‘grid-wrap’
This is a synonym for ‘wrap’.
- cvalscalar, optional
Value to fill past edges of input if mode is ‘constant’. Default is 0.0.
- originint or sequence, optional
Controls the placement of the filter on the input array’s pixels. A value of 0 (the default) centers the filter over the pixel, with positive values shifting the filter to the left, and negative ones to the right. By passing a sequence of origins with length equal to the number of dimensions of the input array, different shifts can be specified along each axis.
- extra_argumentssequence, optional
Sequence of extra positional arguments to pass to passed function.
- extra_keywordsdict, optional
dict of extra keyword arguments to pass to passed function.
- Returns:
- generic_filterndarray
Filtered array. Has the same shape as input.
Notes
This function also accepts low-level callback functions with one of the following signatures and wrapped in
scipy.LowLevelCallable
:int callback(double *buffer, npy_intp filter_size, double *return_value, void *user_data) int callback(double *buffer, intptr_t filter_size, double *return_value, void *user_data)
The calling function iterates over the elements of the input and output arrays, calling the callback function at each element. The elements within the footprint of the filter at the current element are passed through the
buffer
parameter, and the number of elements within the footprint throughfilter_size
. The calculated value is returned inreturn_value
.user_data
is the data pointer provided toscipy.LowLevelCallable
as-is.The callback function must return an integer error status that is zero if something went wrong and one otherwise. If an error occurs, you should normally set the python error status with an informative message before returning, otherwise a default error message is set by the calling function.
In addition, some other low-level function pointer specifications are accepted, but these are for backward compatibility only and should not be used in new code.
Examples
Import the necessary modules and load the example image used for filtering.
>>> import numpy as np >>> from scipy import datasets >>> from scipy.ndimage import generic_filter >>> import matplotlib.pyplot as plt >>> ascent = datasets.ascent()
Compute a maximum filter with kernel size 10 by passing a simple NumPy aggregation function as argument to function.
>>> maximum_filter_result = generic_filter(ascent, np.amax, [10, 10])
While a maximmum filter could also directly be obtained using
maximum_filter
,generic_filter
allows generic Python function orscipy.LowLevelCallable
to be used as a filter. Here, we compute the range between maximum and minimum value as an example for a kernel size of 5.>>> def custom_filter(image): ... return np.amax(image) - np.amin(image) >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
Plot the original and filtered images.
>>> fig, axes = plt.subplots(3, 1, figsize=(4, 12)) >>> plt.gray() # show the filtered result in grayscale >>> top, middle, bottom = axes >>> for ax in axes: ... ax.set_axis_off() # remove coordinate system >>> top.imshow(ascent) >>> top.set_title("Original image") >>> middle.imshow(maximum_filter_result) >>> middle.set_title("Maximum filter, Kernel: 10x10") >>> bottom.imshow(custom_filter_result) >>> bottom.set_title("Custom filter, Kernel: 5x5") >>> fig.tight_layout()