首页 > 编程语言 > 详细

pytorch模型, 使用C++调用

时间:2019-05-07 17:58:31      阅读:1233      评论:0      收藏:0      [点我收藏+]
#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;
}  

pytorch模型, 使用C++调用

原文:https://www.cnblogs.com/geoffreyone/p/10827010.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!