存储落在特定半径内的相邻小区的索引

时间:2016-02-04 18:19:26

标签: python arrays numpy

我有一个非常大的nsy数组1和0。我想逐行去寻找所有的1。一旦遇到1,我想存储半径为五行的条目索引。图中更好地说明了这一点:

enter image description here

(在图片中我只显示了半个圆圈,在实际情况下我需要整个圆圈内的值的索引) 收集索引后,我转到数组中的下一个并执行相同操作。一旦我完成了数组的循环,我想设置所收集的索引的所有值,这些值不是1到1.从某种意义上说,我在半径为5列的所有1周围创建一个缓冲区。

for row in myarray: 
    for column in myarray:
        dist = math.sqrt(row**2+column**2) 
        if dist <= 5  
        .........store the indices of the neighbouring cells 

你能告诉我一个如何做到这一点的建议吗? enter image description here

1 个答案:

答案 0 :(得分:2)

您描述的操作称为dilation。我有scipy,你可以使用ndimage.binary_dilation来获得结果:

import numpy as np
import scipy.ndimage as ndimage
import matplotlib.pyplot as plt

arr = np.zeros((21, 21))
arr[5, 5] = arr[15, 15] = 1

i, j = np.ogrid[:11, :11]
# struct = ((i-5)**2 + (j-5)**2 <= 40)
struct = np.abs(i-5)+ np.abs(j-5) <= 8

result = ndimage.binary_dilation(arr, structure=struct)
plt.imshow(result, interpolation='nearest')
plt.show()

enter image description here