python - 根据 numpy 数组中的中心索引设置周围 block

标签 python arrays numpy

我有一个 2D numpy 零数组,代表一些平坦的表面:

field = np.zeros((10,10))

field
Out[165]: 
array([[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., 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., 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., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

然后我有一个 [row,column] 形式的坐标数组,例如:

In [166]:c = np.array([[1,2],[4,5],[7,3],[2,6]])

In [167]:c
Out[167]: 
array([[1, 2],
       [4, 5],
       [7, 3],
       [2, 6]])

我想要做的是围绕c中的坐标填充field数组的 block 。

Out[192]: 
array([[0., 1., 1., 1., 0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 0., 1., 1., 1., 0., 0.],
       [0., 1., 1., 1., 0., 1., 1., 1., 0., 0.],
       [0., 0., 0., 0., 1., 1., 1., 1., 0., 0.],
       [0., 0., 0., 0., 1., 1., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1., 1., 1., 0., 0., 0.],
       [0., 0., 1., 1., 1., 0., 0., 0., 0., 0.],
       [0., 0., 1., 1., 1., 0., 0., 0., 0., 0.],
       [0., 0., 1., 1., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

我使用 numpy 矢量化的最初尝试是:

In [168]:field[c[:,0]-1:c[:,0]+1,c[:,1]-1:c[:,1]+1] = 10
Traceback (most recent call last):

  File "<ipython-input-168-5433a2f4a5cf>", line 1, in <module>
    field[c[:,0]-1:c[:,0]+1,c[:,1]-1:c[:,1]+1] = 10

TypeError: only integer scalar arrays can be converted to a scalar index

然后我尝试先创建 c[:,0]-1c[:,1]+1 数组,但得到了相同的错误,导致我的结论是,这种类型的范围索引不能在 numpy 中完成。

我还查看了 np.ix_()但使用此方法无法在没有 for 循环的情况下设置多个坐标的周围 block 。

但是使用 for 循环我能够实现所需的输出:

for row,column in c:
        field[row-1:row+2,column-1:column+2] = 1

但不想使用 for 循环,因为在我的最终应用程序中 c 和 f 都很大且是多维的,我觉得我可以利用 numpy 矢量化带来的速度改进。

此外,我知道在图像处理中这可能被视为膨胀或腐 eclipse 问题,但我已经有了要放置在多个维度和非常大的数组处的腐 eclipse /膨胀内核的坐标。

最佳答案

这是一种简单的方法,只需要少量的 Python 循环和大量的向量化工作:

x, y = c[:,0], c[:,1]
for i in -1,0,1:
    for j in -1,0,1:
        field[x+i,y+j] = 1

一种更复杂但可能更快的方法:

offsets = np.array([[-1,-1],[-1,0],[-1,1], [0,-1],[0,0],[0,1], [1,-1],[1,0],[1,1]])
fill = (offsets + c[:,None]).reshape(-1,2)
field[fill[:,0], fill[:,1]] = 1

关于python - 根据 numpy 数组中的中心索引设置周围 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60301466/

相关文章:

python - 在 block 中迭代标准,直到读取 EOF

php - 使用数组通过 SELECT 和 PHP 进行查询

java - 算法可能的值java数独

python - 在数组中添加特定元素?

python - 如何检查 python 中的真正相等性(numpy 数组)?

python - 将 PyTorch CUDA 张量转换为 NumPy 数组

python - 深度复制触发另一个函数 - python

Python - 两个单独的条件取决于独立列的值(美国/加拿大邮政编码练习)

python - Flask test_client 去除查询字符串参数

javascript - 如何根据属性值对数组进行分组?