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

使用Detectron2获取检测对象像素坐标及导出分割区域坐标的咨询

Detectron2 获取检测对象坐标及分割像素保存方法

获取检测对象的像素坐标

完全可以用Detectron2获取检测对象的像素坐标。模型预测返回的Instances对象中,pred_boxes字段存储了所有检测框的坐标,格式为xyxy(左上角x、左上角y、右下角x、右下角y),直接对应图像的像素位置。

示例代码:

from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg

# 初始化配置和预测器
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
predictor = DefaultPredictor(cfg)

# 运行预测
outputs = predictor(your_image)
instances = outputs["instances"].to("cpu")

# 获取所有检测框的像素坐标
boxes = instances.pred_boxes.tensor.numpy()
# 单个检测框的坐标(比如第一个)
single_box = boxes[0]  # 格式: [x1, y1, x2, y2]

保存分割区域的所有整数像素坐标到TXT/CSV

可以通过提取分割掩码(pred_masks)的非零像素坐标实现,步骤如下:

1. 提取分割区域的像素坐标

pred_masks是布尔类型的张量,形状为(N, H, W),其中N是检测到的实例数,H/W是图像高/宽。非零值对应分割区域的像素,用torch.nonzero()即可提取坐标(注意返回的是(y, x)格式,若需要(x, y)需调换顺序)。

示例代码:

import torch
import numpy as np

# 获取分割掩码(转成CPU张量)
masks = instances.pred_masks

# 遍历每个实例的掩码,提取坐标
for idx, mask in enumerate(masks):
    # 获取非零像素的坐标,转成整数
    coords = torch.nonzero(mask, as_tuple=False).int().numpy()
    # 转换为(x, y)格式(可选)
    coords = coords[:, [1, 0]]
    # 处理当前实例的坐标...

2. 保存到TXT文件

用numpy.savetxt直接保存,每行一个坐标:

# 保存单个实例的坐标到TXT
np.savetxt(f"segment_{idx}.txt", coords, fmt="%d", delimiter=",")

3. 保存到CSV文件

可以用Python内置的csv模块或pandas:

用csv模块:

import csv

with open(f"segment_{idx}.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["x", "y"])  # 写入表头
    writer.writerows(coords)

用pandas(更简洁):

import pandas as pd

df = pd.DataFrame(coords, columns=["x", "y"])
df.to_csv(f"segment_{idx}.csv", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:30:53