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

tcomlyy6  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(327)

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

  • 我试过opencv dnn库,但似乎没有工具。
  • 我尝试了onnxruntime,但我甚至不能创建一个会话。我不是很熟悉它的语法,所以可能我做错了什么。下面是测试程序:
  1. #include <onnxruntime_cxx_api.h>
  2. #include <iostream>
  3. int main()
  4. {
  5. auto model_path = L"model.onnx";
  6. std::unique_ptr<Ort::Env> ort_env;
  7. Ort::SessionOptions session_options;
  8. Ort::Session session(*ort_env, model_path, session_options);
  9. return 0;
  10. }

字符串
这段代码抛出

hmtdttj4

hmtdttj41#

我算是明白了

  1. #include <iostream>
  2. #include "onnxruntime_cxx_api.h"
  3. std::vector<std::string> split(std::string str, std::string delimiter) {
  4. size_t pos = 0;
  5. std::string token;
  6. while ((pos = str.find(delimiter)) != std::string::npos) {
  7. token = str.substr(0, pos);
  8. output.push_back(token);
  9. str.erase(0, pos + delimiter.length());
  10. }
  11. output.push_back(str);
  12. return output;
  13. }
  14. int main() {
  15. std::string model_path = "path/to/model.onnx";
  16. std::wstring widestr = std::wstring(model_path.begin(), model_path.end());
  17. const wchar_t* widecstr = widestr.c_str();
  18. Ort::Env env;
  19. Ort::SessionOptions ort_session_options;
  20. Ort::Session session = Ort::Session(env, widecstr, ort_session_options);
  21. Ort::AllocatorWithDefaultOptions ort_alloc;
  22. std::cout << "CLASS NAMES: " << std::endl;
  23. Ort::ModelMetadata model_metadata = session.GetModelMetadata();
  24. Ort::AllocatedStringPtr search = model_metadata.LookupCustomMetadataMapAllocated("classes", ort_alloc);
  25. std::vector<std::string> classNames;
  26. if (search != nullptr) {
  27. const std::array<const char*, 1> list_classes = { search.get() };
  28. classNames = split(std::string(list_classes[0]), ",");
  29. for (int i = 0; i < classNames.size(); i++)
  30. std::cout << "\t" << i << " | " << classNames[i] << std::endl;
  31. }
  32. return 0;
  33. }

字符串
输出如下所示:

  1. CLASS NAMES:
  2. 0 | class_1
  3. 1 | class_2
  4. 2 | class_3

展开查看全部

相关问题