简体   繁体   English

获取 numpy 二维数组中与零相邻的所有元素的索引

[英]Get indices for all elements adjacent to zeros in a numpy 2d array

I have a set of 2d arrays that hold latitudes and longitudes for a map area, with a binary mask that denotes land (0) or ocean (1).我有一组 2d arrays 包含 map 区域的纬度和经度,带有表示陆地(0)或海洋(1)的二进制掩码。 What I am interested in doing is extracting the indices for all coastal ocean elements (mask elements 1 that are adjacent to a 0, including diagonally) so that I can use those indices to extract the lats+lons of all coastal elements from the other arrays.我感兴趣的是提取所有沿海海洋元素的索引(与 0 相邻的掩码元素 1,包括对角线),以便我可以使用这些索引从其他 arrays 中提取所有沿海元素的纬度 + 经度.

Given an array:给定一个数组:

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]])

I'm looking for a way to return:我正在寻找一种返回方式:

(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]))

where each array has the indices for each axis.其中每个数组都有每个轴的索引。

This output format is similar to np.where(), I guess what I'm trying to do is np.where(a == adjacent to 0).这个 output 格式类似于 np.where(),我想我要做的是 np.where(a == 与 0 相邻)。

Let's try convolve2d :让我们试试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))

Output: Output:

(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]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM