python - 填充numpy数组中的相邻元素

标签 python numpy matrix

不确定标题这个问题的最佳方式是什么,但基本上我想根据提供的位置和指定的距离用一个值填充一个现有的 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 ,但包装带来了问题。幸运的是,scipygrey 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/

相关文章:

python - 在 OpenCv 中以给定角度测量轮廓宽度

Python 身份验证 API

python - 当 View 函数中修改表单字段的属性时,validate_on_submit 在 POST 上失败

python - Python 中具有负指数的多项式

python - 如何找到 NumPy 数组中的第一个局部最大值?

python - 除以矩阵的向量列

MATLAB 函数 findchangepts 的 Python 等价物

python - 文本转列功能

c - 布拉斯 : Matrix product in C?

python - 如何在 python 中使用 numpy.linalg.matrix_power 将矩阵提升为大幂?