具有缺失数据的 numpy 数组的局部均值滤波器

fou*_*nes 5 python numpy convolution scipy scikit-image

我想对存储为 numpy 数组的图像进行局部平均滤波器。图像在边缘附近有一些缺失的像素,用有效的掩码(布尔数组)表示。

我可以使用skimage.filters.rank,但我的图像超出了[-1, 1]范围,出于某种原因,scikit-image 要求这样做。

还有astropy.convolution,但它会插入缺失的数据。对于简单的均值,无需进行插值。仅平均有效像素。输入和输出有效掩码相同。

简单地将无效像素设置为零不是一种选择,因为它会污染附近的有效像素平均值。

还有这个 question,但它不是重复的,因为它询问更通用的卷积(这只是平均)。

Pau*_*sen 1

@stefan-van-der-walt 所指的方法,即使用scipy.ndimage.generic_filterwith numpy.nanmean(尚未针对速度进行优化)。

import numpy as np
from scipy.ndimage import generic_filter

def nanmean_filter(input_array, *args, **kwargs):
    """
    Arguments:
    ----------
    input_array : ndarray
        Input array to filter.
    size : scalar or tuple, optional
        See footprint, below
    footprint : array, 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
        to ``footprint=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).
    output : array, optional
        The `output` parameter passes an array in which to store the
        filter output. Output array should have different name as compared
        to input array to avoid aliasing errors.
    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'
    cval : scalar, optional
        Value to fill past edges of input if `mode` is 'constant'. Default
        is 0.0
    origin : scalar, optional
        The `origin` parameter controls the placement of the filter.
        Default 0.0.

    See also:
    ---------
    scipy.ndimage.generic_filter
    """
    return generic_filter(input_array, function=np.nanmean, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)