沈阳seo网站推广,可以兼职做设计的网站,稿定设计在线ps,vatage wordpress主题Clibtorch实现模型部署推理
模型
全连接模型#xff1a;公开mnist手写识别数字的十分类卷积模型#xff1a;自行采集的鲜花四分类
部署
语言环境#xff1a;C
对比Python
python是解释性语言#xff0c;效率很慢#xff0c;安全性很低
系统开发一般是java、C/Clibtorch实现模型部署推理
模型
全连接模型公开mnist手写识别数字的十分类卷积模型自行采集的鲜花四分类
部署
语言环境C
对比Python
python是解释性语言效率很慢安全性很低
系统开发一般是java、C/Cpython无法直接部署到系统上
pytorch部署
原生部署不会丢失精度
环境
下载torch-c±cpu-release版本下载点击 注意debug版本用于模型开发 opencv-c版本传送门Releases - OpenCV
推荐安装带星号版本的windows版本
下载CLion并配置环境具体步骤可参考之前笔记传送门安装CLion配置opencv和torch环境
模型打包
torch.jit进行打包
traced_model jit.trace(model, data)
traced_model.save(model.pt)C实现推理
全连接模型推理
#include opencv2/opencv.hpp
#include torch/torch.h
#include torch/script.h
#include vector
#include stringint main() {cv::Mat image cv::imread(img/0.jpg,cv::IMREAD_GRAYSCALE);torch::Tensor tensor_image torch::from_blob(image.data,{1,image.rows*image.cols},torch::kByte).toType(torch::kFloat);tensor_image / 255.;// std::couttensor_imagestd::endl;auto model torch::jit::load(model/mnist.pt);std::vectortorch::jit::IValue inputs;inputs.push_back(tensor_image);auto rst model.forward(inputs).toTensor();std::cout rst std::endl;std::cout torch::argmax(rst,1) std::endl;
}卷积模型推理
#include torch/script.h // 包含TorchScript头文件
#include torch/torch.h
#include opencv2/opencv.hpp
#include iostream
#include memoryint main() {// 加载模型torch::jit::script::Module module;module torch::jit::load(model/model.pt);// 读取并处理图像cv::Mat image cv::imread(img/flower_1.jpg);// 根据模型输入大小调整cv::resize(image, image, cv::Size(224, 224)); // 将BGR转换为RGBcv::cvtColor(image, image, cv::COLOR_BGR2RGB); // 转换图像为Tensortorch::Tensor img_tensor torch::from_blob(image.data,{1, 3, image.rows, image.cols},torch::kByte);// 转换为浮点img_tensor img_tensor.to(torch::kFloat); // 归一化到[0, 1]img_tensor img_tensor.div(255.0); // 准备输入std::vectortorch::jit::IValue inputs;inputs.push_back(img_tensor);// 执行模型推理at::Tensor output module.forward(inputs).toTensor();// 输出结果std::cout Model output: output \n;return 0;
}鲜花四分类模型输出四个结果如下即为成功转换模型