天天看點

Libtorch使用

1.下載下傳安裝cmake

2.安裝且永久配置opencv(debug+release)

3.安裝vs2017(開始電腦隻有vs2013, 貌似不支援, 很多編譯錯誤)

mean, std很重要,開始直接原圖沒有預處理進行inference, 效果很差, 加了就ok了...

std::shared_ptr<torch::jit::script::Module> module = torch::jit::load("model.pt");
module->to(torch::kCUDA);
assert(module != nullptr);
std::cout << "ok\n";


std::vector<torch::jit::IValue> inputs;
cv::Mat image;
image = cv::imread("pic.jpeg", 1);
cv::Mat image_resized;
cv::resize(image, image_resized, cv::Size(224, 224));
cv::cvtColor(image_resized, image_resized, cv::COLOR_BGR2RGB);
cv::Mat image_resized_float;
image_resized.convertTo(image_resized_float, CV_32F, 1.0 / 255);

auto img_tensor = torch::from_blob(image_resized_float.data, { 1, 224, 224, 3 }, torch::kFloat32);
cout << "img tensor loaded..\n";
img_tensor = img_tensor.permute({ 0, 3, 1, 2 });
img_tensor[0][0] = img_tensor[0][0].sub(0.485).div(0.229);
img_tensor[0][1] = img_tensor[0][1].sub(0.456).div(0.224);
img_tensor[0][2] = img_tensor[0][2].sub(0.406).div(0.225);

// to GPU
img_tensor = img_tensor.to(at::kCUDA);

torch::Tensor out_tensor2 = module->forward({ img_tensor }).toTensor(); //SEGFAULT
           

繼續閱讀