在 Ubuntu 安裝 OpenCV 與建置 C++ 編譯環境

跟著以下步驟, 將指令複製貼上執行, 就可以在你的 Ubuntu 上建置編譯 OpenCV C/C++ 的環境

更新系統

1
2
3
sudo apt-get update

sudo apt-get upgrade


下載 OpenCV 的相依套件

1
2
3
4
5
sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev

sudo apt-get install python3.5-dev python3-numpy libtbb2 libtbb-dev

sudo apt-get install libjpeg-dev libpng-dev libtiff5-dev libjasper-dev libdc1394-22-dev libeigen3-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev sphinx-common libtbb-dev yasm libfaac-dev libopencore-amrnb-dev libopencore-amrwb-dev libopenexr-dev libgstreamer-plugins-base1.0-dev libavutil-dev libavfilter-dev libavresample-dev


下載 OpenCV

1
2
3
4
5
6
7
sudo su

cd /opt

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

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


編譯與安裝 OpenCV

因為要編譯 OpenCV 以及建置環境, 所以這個環節需要一點時間呦

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
cd opencv

mkdir release

cd release

cmake -D BUILD_TIFF=ON -D WITH_CUDA=OFF -D ENABLE_AVX=OFF -D WITH_OPENGL=OFF -D WITH_OPENCL=OFF -D WITH_IPP=OFF -D WITH_TBB=ON -D BUILD_TBB=ON -D WITH_EIGEN=OFF -D WITH_V4L=OFF -D WITH_VTK=OFF -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=/opt/opencv_contrib/modules /opt/opencv/

make -j4

make install

ldconfig

exit

cd ~


查看你的 OpenCV 版本

1
pkg-config --modversion opencv


寫個簡單的程式來編譯看看

1
2
3
4
5
6
7
8
9
10
11
12
13
/* test.cpp */
#include "opencv2/opencv.hpp"

using namespace cv;

int main(void){
Mat srcImg = imread("picture.jpg");

imshow("srcImg", srcImg);
waitKey(0);

return 0;
}

使用以下指令將 test.cpp 編譯成可執行檔

1
g++ test.cpp -o output `pkg-config --cflags --libs opencv`

執行

1
./output


Reference