VS2019CMake新建/打开OpenCV项目(引用自定义OpenCV路径)

一、新建

1.打开VS2019选择创建新项目,选择Cmake项目
VS2019CMake新建/打开OpenCV项目(引用自定义OpenCV路径)_第1张图片
2.选择路径,设置名称
VS2019CMake新建/打开OpenCV项目(引用自定义OpenCV路径)_第2张图片
3.新建好项目后,将自己的源文件放在CMakeList.txt同一路径下
VS2019CMake新建/打开OpenCV项目(引用自定义OpenCV路径)_第3张图片

4.修改CMakeList

cmake_minimum_required (VERSION 3.8)

project ("LearningOpenCV3_examples")

set(OpenCV_DIR D:/OpenCV/opencv/build)#由于下载OpenCV时是自定义路径,所以要set OpenCV_DIR
find_package( OpenCV REQUIRED )#找到OpenCV的位置
include_directories( ${OpenCV_INCLUDE_DIRS} ${OPENGL_INCLUDE_DIRS} )#引用

# 将源代码添加到此项目的可执行文件。
add_executable (LearningOpenCV3_examples "LearningOpenCV3_examples.cpp" )
add_executable( example_02-01 example_02-01.cpp )
# TODO: 如有需要,请添加测试并安装目标。

target_link_libraries(LearningOpenCV3_examples ${OpenCV_LIBS})#链接
target_link_libraries(example_02-01 ${OpenCV_LIBS})

自定义OpenCV路径时,要通过set告诉CMake去哪里找OpenCV。OpenCV_DIR目录下要有OpenCVConfig.cmake,cmake才能找到opencv。然后通过find_package找到OpenCV包,再对头文件进行include。在将源代码添加到此项目的可执行文件后,通过target_link_libraries将动态链接库链接到可执行文件中。

1.windows下,cmake添加opencv依赖:https://blog.csdn.net/u014015324/article/details/106304522
2.Cmake之深入理解find_package()的用法:https://zhuanlan.zhihu.com/p/97369704
3.VS2019CMake项目的简单使用:https://xiaojujiang.blog.csdn.net/article/details/101388984?spm=1001.2101.3001.6650.4&depth_1-utm_relevant_index=9

5.编写源文件

//Example 2-1. A simple OpenCV program that loads an image from disk and displays it
//on the screen
#include 

void help(char** argv ) {
	std::cout << "\n"
	<< "A simple OpenCV program that loads and displays an image from disk\n"
	<< argv[0] <<" \n"
	<< "For example:\n"
	<< argv[0] << " ../fruits.jpg\n"
	<< std::endl;
}
	

int main( int argc, char** argv ) {
	
	if (argc != 2) {
		help(argv);
		return 0;
	}
		

  cv::Mat img = cv::imread( argv[1], -1 );

  if( img.empty() ) return -1;

  cv::namedWindow( "Example 2-1", cv::WINDOW_AUTOSIZE );
  cv::imshow( "Example 2-1", img );
  cv::waitKey( 0 );
  cv::destroyWindow( "Example 2-1" );

  return 0;
}

不要忘记#include

二、打开

VS2019直接编译cmake项目:https://blog.csdn.net/v759291707/article/details/104270896

根据自己的实际情况修改CMakeLists.txt

你可能感兴趣的:(CMake,c++,opencv)