官方文档:
https://pytorch.org/cppdocs/installing.html
参考博客:
https://zhuanlan.zhihu.com/p/68901339
https://zhuanlan.zhihu.com/p/104225144
https://www.cnblogs.com/carsonzhu/p/11197048.html
一保存模型:
这一步比较简单一般不会存在问题
简单来说就是把模型转换为序列化的格式 并 保存下来
二cmake编译过程:
1编译的文件目录结构:
分别含义:
build空文件夹 用来保存cmake 编译的结果
libtorch官方的工具包 直接下载解压的,是cpu版本 release方式。
cmake.txt 编译路径 之类的
cpp文件 自己编写运行C++ 版本网络的demo(第三步给出)
2编写cmake.txt文件
这一步我查找了好几个博客 每个博客里面的cmake.txt 编写的文件 都是不同的,
我的问题主要是编译过程中找不到opencv 等相关的库 。
原因的find_pachage 写的不太队 请教别人后改为下面:
其中我运行的demo 项目名为net_test 代码文件为 net_test.cpp
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(net_test)
find_package(OpenCV REQUIRED PATHS D:/alllib/opencv/build NO_DEFAULT_PATH)
find_package(Torch REQUIRED)
add_executable(net_test net_test.cpp)
target_link_libraries(net_test ${TORCH_LIBRARIES})
set_property(TARGET net_test PROPERTY CXX_STANDARD 11)
另附cmake 编译的路径:
三使用C++运行网络模型:
cmake 编译后 build文件夹会生成这些文件:
运行sln后缀的文件就可以运行我们编写demo(现在是包含torch库的)
demo程序:
#include <torch/script.h> // One-stop header.
#include <iostream>
#include <memory>
int main() {
// Deserialize the ScriptModule from a file using torch::jit::load().
std::shared_ptr<torch::jit::script::Module> module = std::make_shared<torch::jit::Module>(torch::jit::load("E:/save_module/resnet_18_model.pt"));
assert(module != nullptr);
std::cout << "ok\n";
// Create a vector of inputs.
std::vector<torch::jit::IValue> inputs;
inputs.push_back(torch::ones({ 1, 3, 224, 224 }));
// Execute the model and turn its output into a tensor.
at::Tensor output = module->forward(inputs).toTensor();
std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n';
while (1);
}
运行结果:
我下载的是release版本的包 选择对应方式运行
除了使用cmake 编译方式 还有一种直接在项目工程导入torch库的方式 不过我没有实现.
希望可以帮助到你
踩坑1:没有为torch.cpu.dll 加载的符号文件
报错是加载模型的地方
原因是在python保存模型的过程中设置在GPU 上运行。
四使用C++加载序列化模型
//加载模型
std::shared_ptr<torch::jit::script::Module> module = std::make_shared<torch::jit::Module>(torch::jit::load(module_path));
cv::Mat image_transfomed;
cv::resize(image, image_transfomed, cv::Size(80, 250));
//cv::Mat -> Tensor
//h,w,3 -> 1,3,h,w
torch::Tensor tensor_image = torch::from_blob(image_transfomed.data,
{ image_transfomed.rows, image_transfomed.cols,3 }, 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);
//forward 获得output
std::cout << tensor_image.sizes() << std::endl;
at::Tensor output = module->forward({ tensor_image }).toTensor();
auto prediction = output.argmax(1);
std::cout << "mouth prediction:" << prediction << std::endl;
std::cout <<prediction.item().toInt()<< prediction << std::endl;
Normalize操作
模型输出的Tensor 转换为 cv::Mat