You need to enable JavaScript to run this app. PyTorch Detectron2高效获取DefaultPredictor掩码的像素坐标方法
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch Detectron2高效获取DefaultPredictor掩码的像素坐标方法

Detectron2掩码像素坐标高效提取指南

当前存在的性能痛点

  • 原始逐像素遍历方案效率极低:针对3200×1600分辨率图像,单张图遍历提取掩码坐标的耗时约4秒,批量处理待推理目标时完全无法满足性能要求
  • 此前基于compress模块的X坐标筛选优化,仅能将循环阶段耗时降低3倍,后处理环节整体开销仍然过高,无法实现在预测流程侧直接获取掩码像素坐标的目标
  • Detectron2输出的pred_masks为布尔型张量,形状为[检测目标数, 图像高度, 图像宽度],布尔值直接标记对应像素是否属于目标掩码区域,初始实现需要转成多层列表逐点判断

原始参考实现代码

from __future__ import print_function

from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
from detectron2.data.datasets import register_coco_instances


import cv2
import time


# 读取输入图像
start = time.time()
im = cv2.imread("inputImage.jpg")

# 初始化模型配置
cfg = get_cfg()
cfg.merge_from_file("detectron2_repo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # 设置推理置信度阈值
cfg.MODEL.WEIGHTS = "model_final.pth"  # 设置模型权重路径
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1
cfg.MODEL.DEVICE='cpu'

register_coco_instances("dataset_test",{}, "testval.json", "Images_path")
test_metadata = MetadataCatalog.get("dataset_test")

# 初始化预测器并执行推理
predictor = DefaultPredictor(cfg)
outputs = predictor(im)

# 逐像素遍历提取坐标(性能瓶颈点)
outputnump = outputs["instances"].pred_masks.numpy()
true_cords_list = []
x_length = range(len(outputnump[0][0]))
for y_cord in range(len(outputnump[0])):
    for x_cord in x_length:
        if str(outputnump[0][y_cord][x_cord]) == "True":
            inputcoords = (x_cord, y_cord)
            true_cords_list.append(inputcoords)

print(str(true_cords_list))
end = time.time()
print(f"程序运行总耗时: {end - start}")  # 实测耗时约14.3秒

前期优化的循环实现(基于compress模块)

y_length = len(outputnump[0])
x_length = len(outputnump[0][0])
true_cords_list = []
for y_cord in range(y_length):
    x_cords = list(compress(range(x_length), outputnump[0][y_cord]))
    if x_cords:
        for x_cord in x_cords:
            inputcoords = (x_cord, y_cord)
            true_cords_list.append(inputcoords)

毫秒级高效实现方案

完全替代纯Python逐像素循环,依托PyTorch张量底层向量化逻辑完成坐标提取,无Python层循环开销

import torch

# 直接在原始预测张量上操作,无需提前转为numpy数组
pred_masks = outputs["instances"].pred_masks
# 针对单个目标(取第0个检测结果)提取掩码坐标
target_mask = pred_masks[0]
# 由PyTorch底层C++/CUDA实现全掩码遍历,定位所有值为True的坐标
y_coords, x_coords = torch.where(target_mask)
# 整理为(x,y)格式的像素元组列表,可直接用于后续业务逻辑
true_cords_list = list(zip(x_coords.tolist(), y_coords.tolist()))

补充优化提示

  • 上述方案在3200×1600分辨率下的坐标提取耗时仅为毫秒级,相比原逐像素Python循环性能提升超过100倍
  • 若需要提取多个检测目标的掩码坐标,仅需在目标维度做少量遍历,每个目标的坐标提取依然走向量化逻辑,无逐像素循环开销
  • 若后续核心需求是提取掩码对应的多边形顶点,无需存储全量像素坐标,可直接基于掩码张量调用OpenCV轮廓查找接口,直接输出简化后的多边形顶点,进一步减少内存占用与计算开销:
    import numpy as np
    # 掩码转为8位单通道图
    mask_np = (target_mask.numpy() * 255).astype(np.uint8)
    # 查找外轮廓并做顶点简化
    contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    polygon_vertices = contours[0].reshape(-1,2).tolist()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 09:36:02