generic_filter#

ndfilters.generic_filter(array, function, size, axis=None, where=True, mode='mirror', args=())[source]#

Filter a multidimensional array using an arbitrary compiled function.

Parameters:
  • array (ndarray | Quantity) – The input array to be filtered

  • function (Callable[[ndarray, tuple], float]) – The function to applied to each kernel footprint. This is usually either a Numpy reduction function like numpy.mean(), or a function compiled using numba.njit(). This function must accept a 1D array and a tuple of extra arguments as input and return a scalar.

  • size (int | tuple[int, ...]) – The shape of the kernel over which the trimmed mean will be calculated.

  • axis (None | int | tuple[int, ...]) – The axes over which to apply the kernel. Should either be a scalar or have the same number of items as size. If None (the default) the kernel spans every axis of the array.

  • where (bool | ndarray) – An optional mask that can be used to exclude parts of the array during filtering.

  • mode (Literal['mirror', 'nearest', 'wrap', 'truncate']) – The method used to extend the input array beyond its boundaries. See scipy.ndimage.generic_filter() for the definitions. Currently, only “mirror”, “nearest”, “wrap”, and “truncate” modes are supported.

  • args (tuple) – Extra arguments to pass to function.

Return type:

ndarray

Examples

import numpy as np
import numba
import matplotlib.pyplot as plt
import scipy.datasets
import ndfilters

# Download a sample image
img = scipy.datasets.ascent()

# Define a compiled function to apply at every
# kernel footprint.
@numba.njit
def function(a: np.ndarray, args: tuple) -> float:
    return np.mean(a)

# Filter the image using an arbitrary function.
img_filtered = ndfilters.generic_filter(
    function=function,
    array=img,
    size=21,
)

fig, axs = plt.subplots(ncols=2, sharex=True, sharey=True)
axs[0].set_title("original image");
axs[0].imshow(img, cmap="gray");
axs[1].set_title("filtered image");
axs[1].imshow(img_filtered, cmap="gray");
../_images/ndfilters.generic_filter_0_0.png