#include <iostream>
#include "torch/script.h"
#include "torch/torch.h"
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <vector>
int main()
{
//加载pytorch模型
std::shared_ptr<torch::jit::script::Module> module = torch::jit::load("/home/zhuoshi/ZSZT/Geoffrey/opencvTest/m
assert(module != nullptr);
// 创建一个Tensor
//std::vector<torch::jit::IValue> inputs;
//inputs.emplace_back(torch::ones({1, 3, 256, 128}));
//测试前向
//at::Tensor output = module->forward(inputs).toTensor();
//std::cout << output;
// 转换为int8类型
//vector<int16_t> feature(2048);
//for (int i = 0;i<128;i++)
//{
// 转化成Float
//int temp = output[0][i].item().toInt();
// if (temp != 0){
// temp = 1;
// }
// feature[i] = temp;
//}
//std::cout << feature;
//读取图片
IplImage* pmg = cvLoadImage("/home/zhuoshi/ZSZT/Geoffrey/opencvTest/test.jpg");
cv::Mat image(pmg, true);
//cv::Mat imageRGB = cv::cvtColor(image, imageRGB, cv::COLOR_BGR2RGB);
cv::cvtColor(image, image, CV_BGR2RGB);
//IplImage转换成Tensor
cv::Mat img_float;
image.convertTo(img_float, CV_32F, 1.0 / 255);
cv::resize(img_float, img_float, cv::Size(256, 128));
torch::Tensor tensor_image = torch::from_blob(img_float.data, {1, 3, 256, 128}, torch::kFloat32);
//前向
std::vector<torch::jit::IValue> input;
input.emplace_back(tensor_image);
at::Tensor output_image = module->forward(input).toTensor();
//std::cout << output_image;
//Tensor 转 array
std::vector<float> feature(2048);
for (int i=0; i<2048; i++){
// feature[i] = output_image[i]
std::cout << output_image[0][i].item().toFloat();
}
return 0;
}
原文:https://www.cnblogs.com/geoffreyone/p/10827010.html