In Windows environment, the cmake project imports the OpenCV library

        Table of contents

1. Download the OpenCV library

2. Add search path

3. Add environment variables

4. CmakeLists.txt configuration

(1) Configuration steps

(2) CmakeLists.txt complete configuration


1. Download the OpenCV library

OpenCV official download address: download | OpenCV 4.6.0

After downloading, unzip it and you will get the following file

2. Add search path

find_package will look for findxxx.cmake or xxxConfig.cmake files. We need to specify the search path for the .cmake file in advance.

  • OpenCVConfig.cmake :D:\\Download\\opencv4_6_0\\build\\x64\\vc15\\lib
# list(APPEND CMAKE_PREFIX_PATH 搜索路径)
list(APPEND CMAKE_PREFIX_PATH D:\\Download\\opencv4_6_0\\build\\x64\\vc15\\lib)

3. Add environment variables

In the Windows environment, the lib file is used to compile and pass, and the dll file is used to run. The search path added above is just to allow the project to be compiled and passed. We also need to add an environment variable - the path to the bin directory of OpenCV, which will be needed when the project is run. OpenCV dll file is used.

  • OpenCV bin directory : D:\Download\opencv4_6_0\build\x64\vc15\bin

4. CmakeLists.txt configuration

(1) Configuration steps

OpenCV's  OpenCVConfig.cmake file provides detailed header file introduction methods and library file linking methods.

${OpenCV_INCLUDE_DIRS}    # OpenCV 预定义变量,表示头文件目录的完整路径
${OpenCV_LIBS}            # OpenCV 预定义变量,表示lib库文件的完整路径

 Add header file search path:

Let the sub-project link the OpenCV static library file (lib file)

(2) CmakeLists.txt complete configuration

cmake_minimum_required(VERSION 3.0)

PROJECT (opencv_test)

# 添加搜索路径
list(APPEND CMAKE_PREFIX_PATH D:\\Download\\opencv4_6_0\\build\\x64\\vc15\\lib)

# 引入 OpenCV 库
find_package(OpenCV REQUIRED)

# 添加 OpenCV 库头文件搜索路径
include_directories(${OpenCV_INCLUDE_DIRS})

file(GLOB ALL_SRCS *.cpp)

add_executable(${PROJECT_NAME} ${ALL_SRCS})

# 判断是否找到 OpenCV 库
if(OpenCV_FOUND)
    target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})   
endif()

Guess you like

Origin blog.csdn.net/challenglistic/article/details/129093311