OpenCV+Ubuntu18.04环境搭建

  1. 首先更新相关的package:
sudo apt-get update  
sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev 

编译OpenCV需要用到下面的一些package:
GCC
CMake
GTK+2.x or higher
pkg-config
ffmpeg or libav development packages: libavcodec-dev, libavformat-dev, libswscale-dev
2. 下载python
Ubuntu默认带了各个版本的python
3. 下载OpenCV的源码
OpenCV官网上有linux版本的源码包可以下载,不过最好是从git上下载,这样可以保证下载得到的是最新的代码:

wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.2.0.zip  
unzip opencv.zip  
  1. 编译安装
    进入到OpenCV的文件夹中,创建一个build目录,进行编译:
cd opencv-3.2.0 

mkdir build  

cd build  

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..  

make

sudo make install  

  1. 测试OpenCV
    输入命令如下:
mkdir opencv-test

cd opencv-test

gedit DisplayImage.cpp

编辑如下代码:

#include <stdio.h>  
#include <opencv2/opencv.hpp>  
using namespace cv;  
int main(int argc, char** argv )  
{  
    if ( argc != 2 )  
    {  
        printf("usage: DisplayImage.out <Image_Path>\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;  
}  

创建CMake编译文件
gedit 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} )

编译

cmake .  
make  

执行
此时opencv-test文件夹中已经产生了可执行文件DisplayImage,随便从网上下载一张图片放在opencv-test文件夹下,此处下载了opencv.jpg,然后运行

./DisplayImage opencv.jpg