OpenCV 2.4.13 installed in Ubuntu 14 and CMakeLists Demo

1. 配置编译器环境

1 [compiler] sudo apt-get install build-essential

2. 安装OpenCV的依赖包

1 [required] sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
2 [optional] sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev

3. cmkae 外部构建

mkdir build 
cd build 
cmake
-D CMAKE_BUILD_TYPE=RELEASE -D BUILD_TIFF=ON -D CMAKE_INSTALL_PREFIX=/usr/local ..

(注意:必须加上-D BUILD_TIFF=ON,否则编译caffe的时候会有这样的错误/usr/lib/libopencv_highgui.so.2.4: undefined reference to XXXXXX)

4. 安装在主机上

make -j8
sudo make install

5. CMakeLists.txt的写法

//OpenCV 检查程序

#include <cv.h>  
#include <highgui.h>  
  
using namespace cv;  
  
int main(int argc, char* argv[])  
{  
    Mat image;  
    image = imread(argv[1], 1);  
  
    if (argc != 2 || !image.data)   
    {  
        printf("No image data\n");  
        return -1;  
    }  
  
    namedWindow("Display Image", CV_WINDOW_AUTOSIZE);  
    imshow("Display Image", image);  
    waitKey(0);  
    return 0;  
}

在同一目录下创建CMakeLists.txt,并写入编译规则

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(test) 
FIND_PACKAGE(OpenCV REQUIRED)  
ADD_EXECUTABLE(opencv_test main.cpp)  
TARGET_LINK_LIBRARIES(opencv_tes ${OpenCV_LIBS})  

之后利用CMakeLists.txt创建Makefile并完成实例构建

mkdir build 
cd build 
cmake ../
make 

编译完成后,在build文件夹下会创建一个opencv_test的可执行文件 

./opencv_test filename

运行文件,将会显示图片内容

6. 如果对makefile的规则不太熟悉,也可以直接配置gcc的编译选项

g++ main.cpp -Wl,-rpath=/usr/local/lib -I /usr/local/include/ -L /usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -o opencv_test  

7.或者安装pkg-config并配置opencv可以避免重复配置opencv

sudo apt-get install pkg-config
sudo gedit ~/.bashrc

#最后一行输入
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH
#执行以下命令使配置立即生效
source /etc/profile

#打开文件,配置opencv lib库路径
sudo gedit /etc/ld.so.conf.d/opencv.conf
#opencv的库一般安装在"/usr/local/lib"文件夹下,在文件内添加
/usr/local/lib

#执行下列命令使之立刻生效
sudo ldconfig
g++ main.cpp -Wl,-rpath=/usr/local/lib 'pkg-config --libs opencv --cflags opencv' -o test  //`不是单引号,而是数字1左边的`符号

注意,如果不添加-Wl, -rpath=/usr/local/lib, 编译是可以通过的,但是相对应的链接库并没有写入到可执行文件内,运行可执行文件时候,会遇到 ./test: error while loading shared libraries: libopencv_core.so.2.4: cannot open shared object file: No such file or directory的错误,虽然添加上了-I和-L和以保证编译成功,但是可执行文件仍然找不到需要连接的动态库。

 

posted @ 2017-11-08 21:01  采男孩的小蘑菇  阅读(915)  评论(0编辑  收藏  举报