Skip to main content
 首页 » 编程设计

python之存储落在一定半径内的相邻单元格的索引

2024年10月24日16mayingbao

我有一个由 1 和 0 组成的非常大的 numpy 数组。我想逐行查找所有的 1。一旦遇到 1,我想存储落在五行半径内的条目的索引。这在图片中得到了更好的说明:

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

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  

你能给我一个如何完成这个的建议吗?

请您参考如下方法:

您描述的操作称为 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()