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

Python图像处理:二值化滤波后如何将大于0的像素坐标存入numpy数组

坐标提取判断逻辑实现

方法1:适配现有循环的写法

你通过convert('LA')得到的二值化图像为双通道格式,第一个通道为亮度值,第二个为透明通道。滤波后的filtered数组维度为(高度, 宽度, 2),行对应height方向的line参数,列对应width方向的column参数,判断逻辑修改后完整代码如下:

img = Image.open('native.png').convert('RGB')
binarised = img.convert('LA')
# binarised.save('binarised.png')
filtered = ndimage.median_filter(binarised, size = 27)
# Image.fromarray(filtered).save('filtered.png')

width, height = img.size

x = np.array([])
y = np.array([])
for column in range(width):
    for line in range(height):
        # 取LA模式的亮度通道判断是否大于0
        if filtered[line, column, 0] > 0:
            x = np.append(x, column)
            y = np.append(y, line)

方法2:更高效率的numpy向量化写法(无需循环)

循环逐像素判断+np.append的写法在图像尺寸较大时效率极低,直接用numpy的np.where即可一步提取符合条件的坐标:

# 直接提取所有亮度通道大于0的坐标
y, x = np.where(filtered[..., 0] > 0)
# 输出的x、y就是你需要的坐标数组,和循环写法得到的结果完全一致

注意:np.where返回的第一个数组是行索引(对应你代码里的y/line变量),第二个数组是列索引(对应你代码里的x/column变量),不要搞反顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:45:05