> 文章列表 > # visual studio 2022 + cuda版本的libtorch

# visual studio 2022 + cuda版本的libtorch

# visual studio 2022 + cuda版本的libtorch

1. 根据显卡版本下载libtorch

例如cuda11.3+torch1.12.0: 点击下载

2. visual studio 2022 配置属性

  1. 属性管理器->Release->右键添加新项目属性表

  2. 双击打开属性表,添加头文件目录
    2.1 c/c++ -> 常规 -> 附加包含目录, 添加:
    xxx\\libtorch\\include
    xxx\\libtorch\\include\\torch\\csrc\\api\\include
    (xxx是你解压所在的路径)
    2.2 添加库目录。链接器 -> 常规 -> 附加库目录,添加:
    xxx\\libtorch\\lib
    2.3 添加库文件。链接器 -> 输入 -> 附加依赖项。将lib文件夹下所有的lib文件都添加进去。可以在当前目录下的cmd窗口中使用命令dir /b *.lib>1.txt生成txt文件,将txt文件的内容全部复制粘贴到附加依赖项里面。
    2.4 添加命令行。链接器 -> 命令行 -> 其他选项, 复制以下内容粘贴进去:

    /INCLUDE:?warp_size@cuda@at@@YAHXZ /INCLUDE:?_torch_cuda_cu_linker_symbol_op_cuda@native@at@@YA?AVTensor@2@AEBV32@@Z

2.5 配置动态链接库。将lib文件夹的路径配置到环境变量中(这个默认很简单)。重启电脑。

3. 测试

#include<iostream>
#include<opencv2/opencv.hpp>
#include<torch/script.h>
#include<torch/torch.h>using namespace std;
using namespace cv;using torch::jit::script::Module;int main()
{c10::InferenceMode guard;string pt_path = "E:/torch_projs/simple_net/model.pt";string test_image_path = "E:/torch_projs/simple_net/five.jpg";/* 读取图像 */Mat img = imread("E:/torch_projs/simple_net/five.jpg");resize(img, img, Size(28, 28));Mat img_binary;threshold(img, img_binary, 127, 255, THRESH_BINARY_INV);/*imshow("w", img_binary);waitKey();*/if(torch::cuda::is_available()){cout << "可以使用gpu" << endl;}auto input_tensor = torch::from_blob(img_binary.data, { 1, 1,28,28 });input_tensor = input_tensor.to(at::kCUDA);input_tensor.print();return 0;
}