我有一组2d数组,用于保存地图区域的经度和纬度,并带有表示陆地(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)。
让我们尝试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]))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句