当前位置:   article > 正文

python训练的模型怎么在C++使用?_c++调用python训练好的模型

c++调用python训练好的模型

假设我现在已经训练好了一个模型,效果挺好,想用C++调。流程就是这么个流程:

  • 配置libtorch

  • pytorch模型转化

  • 编写C++调用程序

这里就先看一下第一步。怎么配置libtorch。

首先去官网下载 

PyTorchhttps://pytorch.org/

 解压后是这个样子

使用方法呢和一般的库一样

包含目录两个

 库目录一个

链接器->输入->附加依赖项,这里刚开始没写,一堆错误。干脆写全了

就是libtorch\lib目录下的所有lib文件名

 然后就行了。

测试一下

  1. #include <iostream>
  2. #include <torch/torch.h>
  3. int main()
  4. {
  5. torch::Tensor tensor = torch::rand({ 5,3 });
  6. std::cout << tensor << std::endl;
  7. return 0;
  8. }

 

下面是一个C++调用模型的例子,可以参考一下在C++中如何将待检测图像转换为模型的输入以及输出:

  1. #include "torch/script.h" // One-stop header.
  2. #include <iostream>
  3. #include <opencv2\opencv.hpp>
  4. #include <opencv2\imgproc\types_c.h>
  5. using namespace cv;
  6. using namespace std;
  7. int main()
  8. {
  9. //Deserialize the ScriptModule from a file
  10. torch::jit::script::Module module = torch::jit::load("caoxie_weight.pt");
  11. //assert(module != nullptr);
  12. auto image = imread("D:\\UNET\\data\\org\\2.bmp");
  13. if (!image.data)
  14. {
  15. cout << "image imread failed" << endl;
  16. }
  17. cvtColor(image, image, CV_BGR2RGB);
  18. Mat img_transfomed;
  19. resize(image, img_transfomed, Size(480, 320));
  20. /*cout << img_transfomed.data;*/
  21. //img_transfomed.convertTo(img_transfomed, CV_16FC3, 1.0f / 255.0f);
  22. //Mat to tensor,
  23. torch::Tensor tensor_image = torch::from_blob(img_transfomed.data, { img_transfomed.rows, img_transfomed.cols, img_transfomed.channels() }, torch::kByte);
  24. tensor_image = tensor_image.permute({ 2, 0, 1 });
  25. tensor_image = tensor_image.toType(torch::kFloat);
  26. tensor_image = tensor_image.div(255);
  27. tensor_image = tensor_image.unsqueeze(0);
  28. std::vector<torch::jit::IValue> inputs;
  29. inputs.push_back(tensor_image);
  30. torch::Tensor output = module.forward(inputs).toTensor();
  31. torch::Tensor output_max = output.argmax(1);
  32. //tensor to Mat
  33. output_max = output_max.squeeze();
  34. output_max = output_max.mul(255).to(torch::kU8);
  35. output_max = output_max.to(torch::kCPU);
  36. Mat result_img(Size(480, 320), CV_8UC1);
  37. memcpy((void*)result_img.data, output_max.data_ptr(), sizeof(torch::kU8) * output_max.numel());
  38. imshow("result", result_img);
  39. imwrite("result.bmp", result_img);
  40. system("pause");
  41. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/423050
推荐阅读
相关标签
  

闽ICP备14008679号