Apparently, the CMake "find_package scripts" for OpenCV installed by ROS rely on their own path to find OpenCV:
# Extract the directory where *this* file has been installed (determined at cmake run-time)
get_filename_component(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_FILE}" PATH CACHE)
set(OpenCV_INSTALL_PATH "${OpenCV_CONFIG_PATH}/../../..")
If you use your own FindOpenCV.cmake
instead, you should be able to find your actual OpenCV installation without relying on hardcoded values in your CMakeLists.txt
.
You can try to get a generic FindOpenCV.cmake (maybe this one), put it in your CMake modules directory, and then (before calling find_package
):
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/path/to/your/cmake_modules/directory ${CMAKE_MODULE_PATH})
find_package(OpenCV REQUIRED)
...
target_link_libraries(foo ${OpenCV_LIBS})
Note that you need to make sure that the first FindOpenCV.cmake
CMake finds is yours, else it will fall back on ROS' OpenCV. You can check this Stack Overflow post for more information. The rest depends on your FindOpenCV.cmake
, you just need to read the documentation at the beginning to see the variables that may need to be set.
Another solution would be to use pkg-config
if OpenCV 3 is installed with pkg-config
support.
# You can set PKG_CONFIG_PATH if opencv.pc is in an unusual location. Note that pkg-config will
# look for opencv.pc in all the directories in this path, and stop at the first opencv.pc file found.
# You can probably try something like:
# set(ENV{PKG_CONFIG_PATH} ${OpenCV_DIR}/lib/pkgconfig:ENV{PKG_CONFIG_PATH})
find_package(PkgConfig REQUIRED)
pkg_check_modules(OpenCV REQUIRED opencv >= 3)
# OpenCV_FOUND: OpenCV found on the system
# OpenCV_INCLUDE_DIRS: OpenCV include directories
# OpenCV_LIBRARIES: libraries for linking in order to use OpenCV
# OpenCV_LIBRARY_DIRS: OpenCV library directories
If you have both opencv.pc
installed (one for OpenCV 2, one for OpenCV 3), you may want to rename OpenCV 3's file opencv3.pc
, and use pkg_check_modules(OpenCV REQUIRED opencv3)
instead. You could also use this pkg-config
method and put that in a FindOpenCV3.cmake
script (e.g. this script that can be adapted easily).