OpenCV作为优秀的C/C++开源项目,它的CMake写法堪称典范。
目前能下载到的OpenCV的Visual Studio预编译版本中,只有OpenCV 3.0.0需要手动包含${OpenCV_INCLUDE_DIRS}
:
- 如果你用2.x版本,可以用2.4.9,也可以用2.4.13.6。相信你不会去用2.3.1这么老的版本的
- 如果你用3.x版本,建议用>=3.4.2的,因为[3.0.0, 3.4.1]区间内默认的jpeg编解码结果和其他范围的不一致
- 如果你用4.x版本,需要开启C++11,建议用最新的4.4.0
OK,废话说了很多,贴一个鲁棒性比较强的CMakeLists.txt吧,展示了查找和链接OpenCV时处理各种版本的情况的用法:
cmake_minimum_required(VERSION 3.15)
project(demo)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(OpenCV_DIR "D:/lib/opencv/4.3.0" CACHE PATH "Directory that contains OpenCVConfig.cmake")
find_package(OpenCV QUIET COMPONENTS opencv_world)
# for opencv 2.4 on ubuntu 16.04, there is no opencv_world but OpenCV_FOUND will be TRUE
if("${OpenCV_LIBS}" STREQUAL "")
set(OpenCV_FOUND FALSE)
endif()
if(NOT OpenCV_FOUND)
find_package(OpenCV QUIET COMPONENTS core highgui imgproc imgcodecs videoio)
endif()
if(NOT OpenCV_FOUND)
find_package(OpenCV QUIET COMPONENTS core highgui imgproc)
endif()
if(OpenCV_FOUND)
message(STATUS "OpenCV library: ${OpenCV_INSTALL_PATH}")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
if(${OpenCV_VERSION_MAJOR} GREATER 3)
set(CMAKE_CXX_STANDARD 11)
endif()
else()
message(FATAL_ERROR "Error! OpenCV not found!")
endif()
add_executable(demo
src/demo.cpp
)
target_link_libraries(demo ${OpenCV_LIBS})
# opencv 3.0.0 requires manually including header files and MT(static) linking
if(${OpenCV_VERSION_MAJOR} EQUAL 3 AND
${OpenCV_VERSION_MINOR} EQUAL 0 AND
${OpenCV_VERSION_PATCH} EQUAL 0)
target_include_directories(demo PUBLIC ${OpenCV_INCLUDE_DIRS})
if(MSVC AND NOT CMAKE_VERSION VERSION_LESS "3.15")
set_property(TARGET demo PROPERTY
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
)
endif()
endif()