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

14 篇文章 0 订阅

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

  • 配置libtorch

  • pytorch模型转化

  • 编写C++调用程序

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

首先去官网下载 

PyTorchhttps://pytorch.org/

 解压后是这个样子

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

包含目录两个

 库目录一个

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

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

 然后就行了。

测试一下

#include <iostream>
#include <torch/torch.h>

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 <iostream> 
#include <opencv2\opencv.hpp> 
#include <opencv2\imgproc\types_c.h> 
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<torch::jit::IValue> 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");
}

  • 5
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值