You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NumPy数组(二值图像矩阵)中定位值为0的元素的行列位置?

获取二值矩阵中0元素的行列位置

你的代码目前只能输出每行中0元素的列索引,但丢失了对应的行号信息,无法得到完整的(行,列)坐标。下面是两种高效的解决方法:

方法一:直接用np.where处理整个矩阵(推荐)

这是最简洁高效的方式,np.where处理二维数组时会直接返回所有满足条件元素的行、列索引数组:

import numpy as np

array = np.array(binary_img)
# 获取所有值为0的元素的行、列索引
rows, cols = np.where(array == 0)

# 将索引配对为(行, 列)坐标列表
zero_coords = list(zip(rows, cols))

# 输出结果
for r, c in zero_coords:
    print(f"行: {r}, 列: {c}")

rows数组存储所有0元素的行下标,cols数组存储对应位置的列下标,用zip可以把两者一一配对成完整的坐标元组,方便后续使用。

方法二:带行号的循环遍历(不推荐大矩阵)

如果一定要用循环,需要用enumerate获取每行的索引,才能把行号和列号对应起来:

import numpy as np

array = np.array(binary_img)
for row_idx, row in enumerate(array):
    # 获取当前行中0元素的列索引
    col_indices = np.where(row == 0)[0]
    for col_idx in col_indices:
        print(f"行: {row_idx}, 列: {col_idx}")

这种方法效率远低于方法一,仅适合小矩阵测试使用。

内容的提问来源于stack exchange,提问作者Ghazwan Zarefa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:35:19