[笔记] ubuntu16.04中安装opencv

★ 安装所需软件

  • 编译工具:
sudo apt-get install build-essential

关于build-essential: https://packages.ubuntu.com/xenial/build-essential

  • 必须的软件:
sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
  • 可选的软件:
sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev

★ 下载opencv源代码

指定存放opencv代码的目录,然后执行:

git clone https://github.com/opencv/opencv
git clone https://github.com/opencv/opencv_contrib.git

opencv的文件较大,436MB左右,opencv_contrib 122MB左右,下载时需要耐心等待。
为确保稳定性,切换到某个具体的版本上。进入opencv目录:
查看branch: git branch --remote -l
查看tag: git tag -l

切换到tag 3.3.1版本: git checkout 3.3.1

★ 编译opencv

进入opencv目录

mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=Release ..

然后编译:

make -j8

安装opencv:

sudo make install

★ 测试一下

mkdir -p ~/test/opencv/displayImage
cd ~/test/opencv/displayImage

~/test/opencv/displayImage目录中,创建 DisplayImage.cpp 和 CMakeLists.txt 。

  • DisplayImage.cpp
vim DisplayImage.cpp

DisplayImage.cpp的代码:

#include 
#include 

using namespace cv; 

int main(int argc, char** argv ) {
    if (argc != 2) {
        printf("usage: DisplayImage \n");
        return -1; 
    }   
    Mat image;
    image = imread( argv[1], 1 );
    if (!image.data) {
        printf("No image data \n");
        return -1; 
    }   
    namedWindow("Display Image", WINDOW_AUTOSIZE );
    imshow("Display Image", image);
    waitKey(0);
    return 0;
}
  • CMakeLists.txt
vim CMakeLists.txt

CMakeLists.txt的内容如下:

cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
add_executable( DisplayImage DisplayImage.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )

编译:(当前目录为~/test/opencv/displayImage)

mkdir build
cd build
cmake ..
make

build目录生成DisplayImage

执行./DisplayImage ~/Downloads/sky.jpg(替换成你自己的图片),显示效果为:

[笔记] ubuntu16.04中安装opencv_第1张图片

注:此图地址: http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1504/08/c0/5126332_1428502717933_800x600.jpg

DisplayImage.cpp代码的说明:

代码 解释
Mat image; Mat 是opencv中Image数据的对象,Mat对应Matrix。更多内容可以参考: Mat
image = imread( argv[1], 1 ); 读取指定路径的图片, 参考: Reading and Writing Images
namedWindow("Display Image", WINDOW_AUTOSIZE ); 创建一个名字为”Display Image”的窗口,窗口大小根据内容而定。参考: namedWindow
imshow("Display Image", image); 将图片显示在名字为”Display Image”的窗口中。参考:imshow
waitKey(0); 等待用户按键,用户按任意键后执行后面的代码。waitKey(0)表示一直等待用户按键,如果不按键,程序一直停在这里。waitKey(25)等待25ms,如果没有按键,25ms后也会继续执行后面的代码。在读取视频文件时,可以把waitKey(25)放到while循环中,这样读取一帧后会等待25ms,然后会读下一帧,直到读完所有的帧。参考: waitKey, waitKey(0)

更多的使用说明,参考官网: https://docs.opencv.org/3.3.1/d9/df8/tutorial_root.html

★ 参考

https://docs.opencv.org/master/d7/d9f/tutorial_linux_install.html
https://cmake.org/cmake/help/v3.0/variable/CMAKE_INSTALL_PREFIX.html
https://cmake.org/cmake/help/v3.0/variable/CMAKE_BUILD_TYPE.html

你可能感兴趣的:(opencv)