假设我现在已经训练好了一个模型,效果挺好,想用C++调。流程就是这么个流程:
这里就先看一下第一步。怎么配置libtorch。
首先去官网下载
解压后是这个样子
使用方法呢和一般的库一样
包含目录两个
库目录一个
链接器->输入->附加依赖项,这里刚开始没写,一堆错误。干脆写全了
就是libtorch\lib目录下的所有lib文件名
然后就行了。
测试一下
#include
#include
int main()
{
torch::Tensor tensor = torch::rand({ 5,3 });
std::cout << tensor << std::endl;
return 0;
}
下面是一个C++调用模型的例子,可以参考一下在C++中如何将待检测图像转换为模型的输入以及输出:
#include "torch/script.h" // One-stop header.
#include
#include
#include
using namespace cv;
using namespace std;
int main()
{
//Deserialize the ScriptModule from a file
torch::jit::script::Module module = torch::jit::load("caoxie_weight.pt");
//assert(module != nullptr);
auto image = imread("D:\\UNET\\data\\org\\2.bmp");
if (!image.data)
{
cout << "image imread failed" << endl;
}
cvtColor(image, image, CV_BGR2RGB);
Mat img_transfomed;
resize(image, img_transfomed, Size(480, 320));
/*cout << img_transfomed.data;*/
//img_transfomed.convertTo(img_transfomed, CV_16FC3, 1.0f / 255.0f);
//Mat to tensor,
torch::Tensor tensor_image = torch::from_blob(img_transfomed.data, { img_transfomed.rows, img_transfomed.cols, img_transfomed.channels() }, torch::kByte);
tensor_image = tensor_image.permute({ 2, 0, 1 });
tensor_image = tensor_image.toType(torch::kFloat);
tensor_image = tensor_image.div(255);
tensor_image = tensor_image.unsqueeze(0);
std::vector inputs;
inputs.push_back(tensor_image);
torch::Tensor output = module.forward(inputs).toTensor();
torch::Tensor output_max = output.argmax(1);
//tensor to Mat
output_max = output_max.squeeze();
output_max = output_max.mul(255).to(torch::kU8);
output_max = output_max.to(torch::kCPU);
Mat result_img(Size(480, 320), CV_8UC1);
memcpy((void*)result_img.data, output_max.data_ptr(), sizeof(torch::kU8) * output_max.numel());
imshow("result", result_img);
imwrite("result.bmp", result_img);
system("pause");
}