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

如何获取Meta Segment Anything生成的Mask坐标?

获取SAM生成的Mask像素坐标

实现思路

SAM生成的masks是布尔数组(或二值数组),其中为True(或255)的像素位置就是分割掩码的区域。我们可以通过numpy的np.where()方法直接提取这些像素的坐标。

具体代码实现

  1. 首先确保导入numpy(如果环境中未导入):
import numpy as np
  1. 遍历所有Mask,提取坐标:
# 初始化列表存储所有Mask的坐标
all_mask_coords = []

for mask in masks:
    # 提取Mask中有效区域的坐标(返回格式为(y轴坐标, x轴坐标))
    y_indices, x_indices = np.where(mask)
    # 转换为(x, y)格式的坐标对并存储,若需要(y, x)可直接用zip(y_indices, x_indices)
    coords = list(zip(x_indices, y_indices))
    all_mask_coords.append(coords)

注意事项

  • 如果你的masks是二值图像数组(像素值为0和255),需要把np.where(mask)改为np.where(mask == 255)。
  • all_mask_coords的索引和原masks列表的索引一一对应,方便对应到每个分割掩码。

可选:保存坐标到文件

如果需要将坐标导出到CSV文件,可使用以下代码:

import csv

for idx, coords in enumerate(all_mask_coords):
    with open(f"mask_{idx}_coordinates.csv", "w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["x坐标", "y坐标"])
        writer.writerows(coords)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:32:39