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

如何提取二值图像中白色多边形掩码的上下左右坐标点?

提取二值图像白色多边形的边界坐标点

先修正原代码的问题

你原代码里存在两个关键问题:

  1. 直接读取的是彩色三通道图像,img==(255,255)的判断不完整(白色在三通道中是(255,255,255)),且更稳妥的方式是转灰度图处理;
  2. np.where返回的是**(行索引, 列索引)**,对应图像的(y, x)坐标,你搞反了x和y的顺序。

单连通白色区域的处理代码

import numpy as np 
import cv2 

# 读取图像并转为灰度图(二值图直接读灰度即可)
img = cv2.imread('Image.png', cv2.IMREAD_GRAYSCALE)

# 提取白色区域的坐标(灰度图中白色像素值为255)
y_coords, x_coords = np.where(img == 255)

# 计算顶部点(y坐标最小的点)
top_y = y_coords.min()
top_x = x_coords[y_coords == top_y][0]
top_point = (top_x, top_y)

# 计算底部点(y坐标最大的点)
bottom_y = y_coords.max()
bottom_x = x_coords[y_coords == bottom_y][0]
bottom_point = (bottom_x, bottom_y)

# 计算左侧点(x坐标最小的点)
left_x = x_coords.min()
left_y = y_coords[x_coords == left_x][0]
left_point = (left_x, left_y)

# 计算右侧点(x坐标最大的点)
right_x = x_coords.max()
right_y = y_coords[x_coords == right_x][0]
right_point = (right_x, right_y)

# 输出结果
print("顶部点:", top_point)
print("底部点:", bottom_point)
print("左侧点:", left_point)
print("右侧点:", right_point)

多连通白色区域的处理方式

如果图像中有多个不连通的白色多边形,需要先提取轮廓再分别处理每个区域:

import numpy as np 
import cv2 

img = cv2.imread('Image.png', cv2.IMREAD_GRAYSCALE)
# 提取所有外部轮廓
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 遍历每个轮廓,计算边界点
for idx, cnt in enumerate(contours):
    # 简化轮廓点格式,去掉冗余维度
    cnt_points = cnt.squeeze()
    # 分离x、y坐标
    x = cnt_points[:, 0]
    y = cnt_points[:, 1]
    
    # 计算当前轮廓的四个边界点
    top_y = y.min()
    top_x = x[y == top_y][0]
    bottom_y = y.max()
    bottom_x = x[y == bottom_y][0]
    left_x = x.min()
    left_y = y[x == left_x][0]
    right_x = x.max()
    right_y = y[x == right_x][0]
    
    print(f"第{idx+1}个多边形的边界点:")
    print(f"顶部: ({top_x}, {top_y}),底部: ({bottom_x}, {bottom_y})")
    print(f"左侧: ({left_x}, {left_y}),右侧: ({right_x}, {right_y})")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:35:23