python - 获取 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 相邻)。
解决方案
让我们试试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]))
推荐阅读
- javascript - 单击加号时如何添加两个数值
- docker - CICD Jenkins 与 Docker 容器、Kubernetes 和 Gitlab
- javascript - Bootstrap datetimepicker 未显示日历(或无法正确格式化日期)
- java - Apache Calcite - 注册 UDF 以在 RelBuilder 中使用
- visual-studio-code - yaml的vs-code编辑器说期待地图但找到了一个序列
- go - 如何使用未导出结构的功能
- python - 通过比较两个文档的字段值来定义 Firestore 查询
- tensorflow - 使用 ml-engine 调整超参数返回状态:失败
- javascript - 在 Vuex 中将对象传递给动作时遇到问题
- node.js - 如何在 Node.js 中使用 fs.createReadStream 按单词(除以空格并返回)读取文件,例如`/\s+/g`?