CMakeLists.txt与OpenCV

在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

 

posted @ 2020-03-27 22:02  巨鹿王十二  阅读(1931)  评论(0编辑  收藏  举报