假设我有一个称为“网格”的矩阵:
grid = [ [1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1] ]
我想尝试定义一个函数,该函数以1个单元格的半径获取每个邻居的内容,并将这些值添加到新的矩阵中,如下所示:
grid = [ [3, 5, 5, 3],
[5, 8, 8, 5],
[5, 8, 8, 5],
[3, 5, 5, 3] ]
答案 0 :(得分:1)
一种方法是将其视为2-D卷积问题。您只需要定义适当的掩码即可。
在这种情况下,您可以使用一个3x3的矩阵,其中1为零,而中心元素为零。
import numpy as np
mask = np.ones((3, 3))
mask[1, 1] = 0
print(mask)
#[[1. 1. 1.]
# [1. 0. 1.]
# [1. 1. 1.]]
现在开始卷积:
from scipy.signal import convolve2d
print(convolve2d(grid, mask, mode='same'))
#[[3. 5. 5. 3.]
# [5. 8. 8. 5.]
# [5. 8. 8. 5.]
# [3. 5. 5. 3.]]
答案 1 :(得分:1)
我找到了解决方案-快速又脏:)
grid = [ [1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1] ]
rows = len(grid)
cols = len(grid[0])
def get_sum_of_neighbours(grid, r, c):
neighbours = [
(r - 1, c - 1), (r - 1, c), (r - 1, c + 1),
(r, c - 1), (r, c + 1),
(r + 1, c - 1), (r + 1, c), (r + 1, c + 1),
]
return sum([grid[r_n][c_n]
for r_n, c_n in neighbours
if 0 <= r_n < rows and 0 <= c_n < cols])
resultgrid = []
for r in range(rows):
row = []
for c in range(cols):
row.append(get_sum_of_neighbours(grid, r, c))
resultgrid.append(row)
for row in resultgrid:
print(row)
没有scipy或numpy等第三方工具...