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

TensorFlow .PB模型推理:如何将vector<Tensor>转换为vector<Mat>

实现TensorFlow std::vector<Tensor> 到 std::vector<cv::Mat> 的转换方法

前置依赖

首先确保项目已引入对应头文件并链接OpenCV、TensorFlow库:

#include <opencv2/core.hpp>
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/core/platform/logging.h>

转换逻辑实现

单个张量转Mat函数

针对你给出的float类型2维输出张量适配,也可根据实际输出维度扩展:

cv::Mat tensorToMat(const tensorflow::Tensor& tensor) {
    auto dims = tensor.shape().dim_sizes();
    // 适配2维[rows, cols]格式张量,你的[16900,13]输出对应生成16900行13列的单通道浮点Mat
    int rows = dims[0];
    int cols = dims.size() > 1 ? dims[1] : 1;
    cv::Mat mat(rows, cols, CV_32FC1);
    // 拷贝张量数据到Mat内存,避免张量生命周期结束后野指针问题
    memcpy(mat.data, tensor.flat<float>().data(), mat.total() * mat.elemSize());
    return mat;
}

批量容器转换函数

void convertTensorVectorToMatVector(const std::vector<tensorflow::Tensor>& tensor_outputs, 
                                    std::vector<cv::Mat>& mat_outputs) {
    mat_outputs.clear();
    mat_outputs.reserve(tensor_outputs.size());
    for (const auto& tensor : tensor_outputs) {
        CHECK(tensor.dtype() == tensorflow::DT_FLOAT) << "当前仅支持float类型张量转换";
        mat_outputs.emplace_back(tensorToMat(tensor));
    }
}

接入你的现有代码

在session->Run执行成功之后调用转换逻辑即可:

// 原有代码
if (!run_status.ok()) {
    LOG(ERROR) << "Running model failed: " << run_status;
    return -1;
}
std::cout << " " << outputs[0].shape().DebugString() << std::endl;

// 新增转换代码
std::vector<cv::Mat> mat_outputs;
convertTensorVectorToMatVector(outputs, mat_outputs);

// 验证结果示例
std::cout << "检测输出Mat尺寸:" << mat_outputs[0].rows << "行 " << mat_outputs[0].cols << "列" << std::endl;
std::cout << "首个检测结果值:" << mat_outputs[0].at<float>(0,0) << std::endl;

注意事项

  • 如果是4维NHWC格式的图像类输出张量,需要调整Mat创建逻辑,对应设置通道数即可,比如[1, h, w, 3]的输出可以创建h行w列的CV_32FC3类型Mat
  • 如果追求更高性能且能保证Tensor生命周期长于Mat,可以直接复用张量内存无需拷贝,构造Mat时传入张量指针即可:cv::Mat mat(rows, cols, CV_32FC1, tensor.flat<float>().data());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:24:03