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

时间:2017-10-26 11:44:26

标签: python numpy scipy convolution scikit-image

我想将图像的局部均值滤波器存储为numpy数组。图像边缘附近有一些缺失的像素,用有效的掩码(bool数组)表示。

我可以使用skimage.filters.rank,但我的图片超出[-1, 1]范围,出于某种原因,scikit-image将其作为要求。

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

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

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

1 个答案:

答案 0 :(得分:0)

@ stefan-van-der-walt所指的方法,即使用scipy.ndimage.generic_filternumpy.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)