1

我正在尝试编写一个 python 函数来删除 2D 图像数据中的热像素。我正在尝试创建一个函数,该函数将获取 2D 数组中每个元素周围的邻居的平均值,并在其值超过其邻居的平均值特定数量(例如 3 sigma)时有条件地覆盖该元素。这就是我所在的位置:

def myFunction(values):
    if np.mean(values) + 3*np.std(values) < origin:
        return np.mean(values)

footprint = np.array([[1,1,1],
                      [1,0,1],
                      [1,1,1]])
correctedData = ndimage.generic_filter(data, myFunction, footprint = footprint)

上面代码中的“起源”是示范性的。我知道这是不正确的,我只是想展示我正在尝试做的事情。有没有办法将当前元素的值传递给 generic_function?

谢谢!

4

1 回答 1

1

footprint没有将中心值传递回您的函数。

我发现它更容易使用size(相当于使用足迹中的所有),然后在回调函数中处理所有内容。所以在你的情况下,我会在回调函数中提取中心值。像这样的东西:

from scipy.ndimage import generic_filter

def despike(values):
    centre = int(values.size / 2)
    avg = np.mean([values[:centre], values[centre+1:]])
    std = np.std([values[:centre], values[centre+1:]])
    if avg + 3 * std < values[centre]:
        return avg
    else:
        return values[centre]

让我们制作一些假数据:

data = np.random.randint(0, 10, (5, 5))
data[2, 2] = 100

这产生(例如):

array([[  2,   8,   4,   2,   4],
       [  9,   4,   7,   6,   5],
       [  9,   9, 100,   7,   3],
       [  0,   1,   0,   8,   0],
       [  9,   9,   7,   6,   0]])

现在您可以应用过滤器:

correctedData = generic_filter(data, despike, size=3)

这消除了我添加的尖峰:

array([[2, 8, 4, 2, 4],
       [9, 4, 7, 6, 5],
       [9, 9, 5, 7, 3],
       [0, 1, 0, 8, 0],
       [9, 9, 7, 6, 0]])
于 2018-02-12T17:33:41.873 回答