在Linux下安裝了兩個版本的Opencv,一個2.4.9在默認路徑下:
/usr/local/share/OpenCV/OpenCVConfig.cmake
一個3.4.9安裝在自定義路徑下:
/usr/local/include/opencv3.4.9/share/OpenCV/OpenCVConfig.cmake
在調用自定義的opencv版本時CMakeLists.txt內容如下:
1 # cmake needs this line 2 cmake_minimum_required (VERSION 2.8) 3 # Define project name 4 project(TestOpencv) 5 6 # Find OpenCV, you may need to set OpenCV_DIR variable 7 # to the absolute path to the directory containing OpenCVConfig.cmake file 8 # via the command line or GUI 9 set(OpenCV_DIR /usr/local/include/opencv3.4.9/share/OpenCV) 10 find_package(OpenCV 3 REQUIRED) 11 message(STATUS "Opencv library status: ") 12 message(STATUS "> version: ${OpenCV_VERSION} ") 13 message(STATUS "> libraries: ${OpenCV_LIBS}") 14 message(STATUS "> include: ${OpenCV_INCLUDE_DIRS} ") 15 16 # Add OpenCV headers location to your include paths 17 include_directories(${OpenCV_INCLUDE_DIRS}) 18 19 20 # Declare the executable target built from your sources 21 add_executable(main main.cpp) 22 23 # Link your application with OpenCV libraries 24 target_link_libraries(main ${OpenCV_LIBS})
其中line 9 很重要,如果沒有set 路徑的話會找到默認路徑下的opencv 2.4.9,從而不匹配 find_package(OpenCV 3 REQUIRED) 而報錯。
如果只是用opencv2.4.9就不需要line 9,然后 find_package(OpenCV 3 REQUIRED) 改成 find_package(OpenCV 2 REQUIRED) 或 find_package(OpenCV REQUIRED)
文件路徑結構:
|--build | |--CMakeLists.txt | |--main.cpp
|
|--test
|
|--1.jpg
其中build是新建的文件夾。
main.cpp內容如下:
1 #include <stdio.h> 2 #include "opencv2/opencv.hpp" 3 4 int main() 5 { 6 cv::Mat image = cv::imread("../test/1.jpg"); 7 printf("image.col=%d image.raw=%d \n", image.cols, image.raws); 8 9 cv::imshow("picture",image); 10 cv::waitKey(0); 11 return 0; 12 13 }
在build目錄下執行:
cmake ..
生成nakefile文件,接着執行編譯命令:
make
這樣會生成一個可執行程序 main
執行程序:
./main