赞
踩
下载并安装OpenCV,安装后的目录如下:
本文使用的是VS2019的带的VC16
版本的编译器,环境变量配置如下:
使用Clion创建C++项目,由于使用的OpenCV是VC14的库,创建时语言标准也选择14
,如下图所示:
set(OpenCV_DIR $ENV{OPENCV_HOME}/lib/)
完成上一步之后CMake会进入设置的目录中找到OpenCVConfig.cmake
文件,设置CMake需要加载读取的模块,一般第三方模块的命名方式都是xxxxConfig.cmake
。
find_package(OpenCV REQUIRED)
在测试项目运行时需要将opencv_world454.dll(release)
和opencv_world454d.dll(debug)
拷贝到.exe
文件的同级目录下。
file(GLOB COPY_DLL "$ENV{OPENCV_HOME}/bin/*.dll")
file(COPY ${COPY_DLL} DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
其中${CMAKE_CURRENT_BINARY_DIR}
是CMake内置的变量,表示当前项目编译后二进制文件输出路径。
OpenCV也有一些内置的变量可用,这些变量都是在OpenCVConfig.cmake
定义在文件中。
message(STATUS "OpenCV library status:")
message(STATUS " config: ${OpenCV_DIR}")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
在编译时需要将OpenCV的lib文件编译到exe文件中,设置如下:
target_link_libraries(OpenCVCode ${OpenCV_LIBS})
设置target_link_libraries()
函数,一定要在add_executable()前
。
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace cv;
int main() {
Mat src = imread("D:/Code/OpenCVCode/cat.jpg");
namedWindow("CAT", WINDOW_AUTOSIZE);
imshow("CAT", src);
waitKey(0);
return 0;
}
cmake_minimum_required(VERSION 3.21) project(OpenCVCode) set(CMAKE_CXX_STANDARD 14) # 设置OPENCV环境变量 set(OpenCV_DIR $ENV{OPENCV_HOME}/lib/) # 查找OPENCV模块 find_package(OpenCV REQUIRED) # 设置需要拷贝的动态库 file(GLOB COPY_DLL "$ENV{OPENCV_HOME}/bin/*.dll") file(COPY ${COPY_DLL} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) # 信息输出(非必须) message(STATUS "OpenCV library status:") message(STATUS " config: ${OpenCV_DIR}") message(STATUS " version: ${OpenCV_VERSION}") message(STATUS " libraries: ${OpenCV_LIBS}") message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}") add_executable(OpenCVCode main.cpp) # 添加链接附加库目录 target_link_libraries(OpenCVCode ${OpenCV_LIBS})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。