opencv 从C++中读取onnx模型的元数据的最佳方法是什么?

tcomlyy6  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(133)

我有一个onnx的模型,包含属性"list_classes"。我用opencv dnn运行它。我需要用C++读取这个列表。

  • 我试过opencv dnn库,但似乎没有工具。
  • 我尝试了onnxruntime,但我甚至不能创建一个会话。我不是很熟悉它的语法,所以可能我做错了什么。下面是测试程序:
#include <onnxruntime_cxx_api.h>
#include <iostream>

int main()
{
    auto model_path = L"model.onnx";
    std::unique_ptr<Ort::Env> ort_env;
    Ort::SessionOptions session_options;
    Ort::Session session(*ort_env, model_path, session_options);

    return 0;
}

字符串
这段代码抛出

hmtdttj4

hmtdttj41#

我算是明白了

#include <iostream>
#include "onnxruntime_cxx_api.h"

std::vector<std::string> split(std::string str, std::string delimiter) {
    size_t pos = 0;
    std::string token;
    while ((pos = str.find(delimiter)) != std::string::npos) {
        token = str.substr(0, pos);
        output.push_back(token);
        str.erase(0, pos + delimiter.length());
    }
    output.push_back(str);
    return output;
}

int main() {
    std::string model_path = "path/to/model.onnx";
    std::wstring widestr = std::wstring(model_path.begin(), model_path.end());
    const wchar_t* widecstr = widestr.c_str();
    Ort::Env env;
    Ort::SessionOptions ort_session_options;
    Ort::Session session = Ort::Session(env, widecstr, ort_session_options);
    Ort::AllocatorWithDefaultOptions ort_alloc;

    std::cout << "CLASS NAMES: " << std::endl;
    Ort::ModelMetadata model_metadata = session.GetModelMetadata();
    Ort::AllocatedStringPtr search = model_metadata.LookupCustomMetadataMapAllocated("classes", ort_alloc);
    std::vector<std::string> classNames;
    if (search != nullptr) {
        const std::array<const char*, 1> list_classes = { search.get() };
        classNames = split(std::string(list_classes[0]), ",");
        for (int i = 0; i < classNames.size(); i++)
            std::cout << "\t" << i << " | " << classNames[i] << std::endl;
    }

    return 0;
}

字符串
输出如下所示:

CLASS NAMES:
    0 | class_1
    1 | class_2
    2 | class_3

相关问题