不确定标题这个问题的最佳方式是什么,但基本上我想根据提供的位置和指定的距离用一个值填充一个现有的 numpy 数组。假设沿对角线走是无效的。
例如,假设我们有一个只有 0 的数组。
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
如果我想要 (2,2) 作为距离为 1 的位置,它将在距离提供的位置(包括它自身)距离为 1 的位置处用值 1 填充矩阵。因此矩阵看起来像:
[[0 0 0 0 0]
[0 0 1 0 0]
[0 1 1 1 0]
[0 0 1 0 0]
[0 0 0 0 0]]
如果我提供的距离为 2,它看起来像:
[[0 0 1 0 0]
[0 1 1 1 0]
[1 1 1 1 1]
[0 1 1 1 0]
[0 0 1 0 0]]
基本上距离该位置 2 以内的所有内容都将填充值 1。假设对角线移动无效。
我还想支持环绕,如果相邻元素超出范围,它会环绕。
例如,如果提供的位置是距离为 1 的 (4,4),则矩阵应如下所示:
[[0 0 0 0 1]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 1]
[1 0 0 1 1]]
我尝试使用 np.ogrid 以及 1 为真的掩码,但似乎无法正常工作。
最佳答案
您尝试做的基本上是 binary dilation ,但包装带来了问题。幸运的是,scipy
的 grey dilation函数具有我们可以利用的 wrap
模式:
from scipy.ndimage.morphology import grey_dilation, generate_binary_structure, iterate_structure
st = generate_binary_structure(2,1)
# st essentially defines "neighbours",
# and you can expand n times this using iterate_structure(st, n):
# >>> st
# array([[False, True, False],
# [ True, True, True],
# [False, True, False]])
# >>> iterate_structure(st,2)
# array([[False, False, True, False, False],
# [False, True, True, True, False],
# [ True, True, True, True, True],
# [False, True, True, True, False],
# [False, False, True, False, False]])
a = np.zeros((5,5))
a[4,4] = 1
dist = 1
dilated = grey_dilation(a, footprint = iterate_structure(st,dist), mode='wrap')
作为为您创建数组的函数:
from scipy.ndimage.morphology import grey_dilation, generate_binary_structure, iterate_structure
def create(size, dist, loc):
a = np.zeros((size,size), dtype=int)
a[loc] = 1
st = generate_binary_structure(2,1)
return grey_dilation(a, footprint = iterate_structure(st,dist), mode='wrap')
示例:重现您想要的输入和输出:
>>> create(5, 1, (2,2))
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])
>>> create(5, 2, (2,2))
array([[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0]])
>>> create(5, 1, (4,4))
array([[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1],
[1, 0, 0, 1, 1]])
关于python - 填充numpy数组中的相邻元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229562/