C M a k e 创 建 O p e n C V 和 L i b t o r c h 的 综 合 项 目 CMake创建OpenCV和Libtorch的综合项目 CMakeOpenCVLibtorch

项目结果图

CMake创建OpenCV和Libtorch的综合项目_计算机视觉

CMakeLists.txt

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(my_test)
set(OpenCV_DIR E:/software/opencv/opencv/build)
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)
add_executable(example example.cpp)
target_link_libraries(example "${TORCH_LIBRARIES}")
target_link_libraries(example ${OpenCV_LIBS}) 
set_property(TARGET example PROPERTY CXX_STANDARD 11)

example.cpp

#include <torch/script.h>  // One-stop header.
#include <iostream>
#include <memory>
#include <opencv2/opencv.hpp>
using namespace cv;

int main() {
	
		/***
	IMREAD_COLOR:加载为3通道彩色图像
	IMREAD_GRAYSCALE:加载为灰度图像
	IMREAD_ANYCOLOR:加载任意颜色图像
	IMREAD_UNCHANGED:加载带透明度的四通道图像
	***/
	Mat src = imread("E:/cat.png",IMREAD_UNCHANGED); // IMREAD_COLOR:加载为3通道彩色图像

	if (src.empty()) {
		printf("image is empty!!!");
		return -1;
	}
	printf("image is empty!!!");
	/***
	WINDOW_AUTOSIZE:适配为图像大小,大小不可变
	WINDOW_FREERATIO:可任意设置图像大小
	WINDOW_NORMAL:可任意设置图像大小
	***/
	namedWindow("image", WINDOW_FREERATIO); // WINDOW_NORMAL:可任意设置图像大小
	imshow("image", src);
	imwrite("E:/cat_cat_imwrite.png", src);
	waitKey(0);
	destroyAllWindows();
  using torch::jit::script::Module;
  Module module =
      torch::jit::load("D:\\workplace\\python\\OOP\\unet.pt");

  std::cout << "ok\n";
  // Create a vector of inputs.
  std::vector<torch::jit::IValue> inputs;
  inputs.push_back(torch::ones({1, 3, 512, 512}));

  // Execute the model and turn its output into a tensor.
  at::Tensor output = module.forward(inputs).toTensor();

  std::cout << output << '\n';
    
}


建立项目

cmake -DCMAKE_PREFIX_PATH=E:\software\libtorch  ..

CMake创建OpenCV和Libtorch的综合项目_计算机视觉_02

编译结果

cmake --build .

CMake创建OpenCV和Libtorch的综合项目_人工智能_03

复制需要库(运行的时候缺什么拿什么)

CMake创建OpenCV和Libtorch的综合项目_#include_04

运行结果

CMake创建OpenCV和Libtorch的综合项目_人工智能_05
CMake创建OpenCV和Libtorch的综合项目_opencv_06