Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在c++;?_C++_Machine Learning_Neural Network_Pytorch_Torch - Fatal编程技术网

C++ 如何在c++;?

C++ 如何在c++;?,c++,machine-learning,neural-network,pytorch,torch,C++,Machine Learning,Neural Network,Pytorch,Torch,我得到了经过训练的keras模型,并使用。然后我尝试用C++代码: #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <torch.h> int main() { cv::Mat image; image= cv::imread("test_img.png", cv::IMRE

我得到了经过训练的keras模型,并使用。然后我尝试用C++代码:

#include <iostream>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <torch.h>

int main()
{
    cv::Mat image;
    image= cv::imread("test_img.png", cv::IMREAD_GRAYSCALE);   // Read the file

try
{
    torch::jit::script::Module module;
    module = torch::jit::load("my_model.pth");

    torch::IntArrayRef input_dim = std::vector<int64_t>({ 1, 2, 256, 256});

    cv::Mat input_img;
    image.convertTo(input_img, CV_32FC3, 1 / 255.0);
    torch::Tensor x = torch::from_blob(input_img.data, { 1, 2, 256, 256 }, torch::kFloat);
    torch::NoGradGuard no_grad;

    auto output = module.forward({ x });

    float* data = static_cast<float*>(output.toTensor().data_ptr());

    cv::Mat output_img = cv::Mat(256, 256, CV_32FC3, data);
    cv::imwrite("output_img.png", output_img);
}
catch (std::exception &ex)
{
    std::cout << "exception! " << ex.what() << std::endl;
}

    return 0;
}
#包括
#包括
#包括
#包括
int main()
{
cv::Mat图像;
image=cv::imread(“test_img.png”,cv::imread_GRAYSCALE);//读取文件
尝试
{
torch::jit::script::Module;
module=torch::jit::load(“my_model.pth”);
torch::IntArrayRef input_dim=std::vector({1,2,256,256});
cv::Mat input\u img;
image.convertTo(输入img,CV_32FC3,1/255.0);
torch::Tensor x=torch::from_blob(输入{1,2,256,256},torch::kFloat);
火炬:NoGradGuard no_grad;
自动输出=module.forward({x});
float*data=static_cast(output.toTensor().data_ptr());
cv::Mat output_img=cv::Mat(256,256,cv_32FC3,数据);
cv::imwrite(“output\u img.png”,output\u img);
}
捕获(标准::异常和例外)
{

std::cout在这种情况下,模型的答案是两幅图像的元组。我们可以通过以下方式提取它们:

torch::Tensor t0 = output.toTuple()->elements()[0].toTensor();
torch::Tensor t1 = output.toTuple()->elements()[1].toTensor();
变量
t0
t1
包含带有模型输出的张量