使用 convolve2d 查找二维数组中的邻居数

Find number of neighbours in 2D array using convolve2d

我有一个具有固定边界的二维点阵 (L*L),并将 N-S-W-E 站点视为每个站点的 4 个邻居。每个站点都分配有一个浮点值。对于每个站点,我都在计算其相邻站点的平均值加上它自己的值。我想使用 scipy.signal 的 convolv2d 解决这个问题。以下是我的代码:

# xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours

import numpy as np
from scipy.signal import convolve2d

L = 6  # each side of 2D lattice
a, b = (0.1, 0.5) # two constants
arr = np.random.rand(L, L) # example 2D array
# (3,3) window representing 4 neighbours which slides over 'arr'
kernel = np.array([[0, b, 0],
                   [b, a, b],
                   [0, b, 0]])
neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0)
print(neighbors_sum)

我找不到将每个站点的相邻值之和除以其邻居数的方法。

通过以下方式,我可以找到每个站点的邻居数量,但不知道如何将这些值合并到 'result' 中。有人可以建议我如何实现吗?或者 convolve2d 中是否有更简单的内置方法来做到这一点?

arr = np.ones((L,L), dtype=np.int)
kernel = np.array([[0, 1, 0],
                   [1, 0, 1],
                   [0, 1, 0]])
neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0)
print(neighbors_count)

要将一个数组逐个元素地除以另一个数组,请使用 np.divide

np.divide(result, neighbours_count)

看起来这就是需要添加到您的代码中的全部内容;我认为它很好。

通常,要找到某种加权平均值,可以执行以下操作:

  1. 对输入数组执行权重求和。
  2. 对与输入大小相同的数组执行相同的操作。
  3. 将 1 的结果除以 2 的结果
import numpy as np
from scipy.signal import convolve2d

L = 6
a, b = 0.1, 0.5

arr = np.random.rand(L, L)
arrb = arr.astype(bool)
kernel = np.array([[0, 1, 0],
                   [1, 0, 1],
                   [0, 1, 0]])

neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0)
neighbors_count = convolve2d(arrb, kernel, mode='same', boundary='fill', fillvalue=0)
neighbors_mean = np.divide(neighbors_sum, neighbors_count)
res = a * arr + b * neighbors_mean
print(res)