首页 > 解决方案 > 获取 numpy 二维数组中与零相邻的所有元素的索引

问题描述

我有一组二维数组,其中包含地图区域的纬度和经度,带有表示陆地(0)或海洋(1)的二进制掩码。我感兴趣的是提取所有沿海海洋元素的索引(与 0 相邻的掩码元素 1,包括对角线),以便我可以使用这些索引从其他数组中提取所有沿海元素的纬度 + 经度.

给定一个数组:

a = np.array([[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 0, 0, 0, 1],
[1, 1, 0, 1, 1],
[1, 1, 1, 1, 1]])

我正在寻找一种返回方式:

(array([0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4]), 
array([1, 2, 3, 0, 1, 3, 4, 0, 4, 0, 1, 3, 4, 1, 2, 3]))

其中每个数组都有每个轴的索引。

这种输出格式类似于np.where(),我想我要做的是np.where(a == 与0 相邻)。

标签: pythonarraysnumpy

解决方案


让我们试试convolve2d

from scipy.signal import convolve2d

kernel = np.full((3,3), 1)

# remove center of kernel -- not count 1 at the center of the square
# we may not need to remove center
# in which case change the mask for counts
kernel[1,1]=0

# counts 1 among the neighborhoods
counts = convolve2d(a, kernel, mode='same', 
                    boundary='fill', fillvalue=1)

# counts==8 meaning surrounding 8 neighborhoods are all 1
# change to 9 if we leave kernel[1,1] == 1
# and we want ocean, i.e. a==1
np.where((counts != 8) & (a==1))

输出:

(array([0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4]),
 array([1, 2, 3, 0, 1, 3, 4, 0, 4, 0, 1, 3, 4, 1, 2, 3]))

推荐阅读