1. 程式人生 > >Linux下OpenCV的環境搭建

Linux下OpenCV的環境搭建

OpenCV is the most popular and advanced code library for Computer Vision related applications today, spanning from many very basic tasks (capture and pre-processing of image data) to high-level algorithms (feature extraction, motion tracking, machine learning). It is free software and provides a rich API in C, C++, Java and Python. Other wrappers are available. The library itself is platform-independent and often used for real-time image processing and computer vision.

1.移除先前安裝的ffmpeg和x264

1 sudo apt-get -qq remove ffmpeg x264 libx264-dev

2.安裝依賴項

1 sudo apt-get -qq install libopencv-dev build-essential checkinstall cmake pkg-config yasm libjpeg-dev libpng-dev libtiff5-dev libjasper-dev libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libxine-dev libgstreamer0.10
-dev libgstreamer-plugins-base0.10-dev libv4l-dev python-dev python-numpy libtbb-dev libqt4-dev libgtk2.0-dev libfaac-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev x264 v4l-utils ffmpeg cmake qt5-default checkinstall

3.下載並解壓OpenCV

1 wget -O OpenCV-$version.zip
http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/$version/opencv-"$version".zip/download 2 unzip OpenCV-$version.zip 3 cd opencv-$version

4.編譯原始碼,構建OpenCV

複製程式碼
1 mkdir build
2 cd build
3 cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON ..
4 make -j2
5 sudo make install
6 sudo sh -c 'echo "/usr/local/lib" > /etc/ld.so.conf.d/opencv.conf'
7 sudo ldconfig
複製程式碼

5.測試OpenCV是否安裝成功

轉到opencv的樣例程式碼目錄(samples/c)下,

1 chmod +x build_all.sh
2 ./build_all.sh
3 ./facedetect "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml" lena.jpg

 執行結果:

編譯OpenCV程式:

複製程式碼
 1 #!/bin/bash
 2 echo "compiling $1"
 3 if [[ $1 == *.c ]]
 4 then
 5     gcc -ggdb `pkg-config --cflags opencv` -o `basename $1 .c` $1 `pkg-config --libs opencv`;
 6 elif [[ $1 == *.cpp ]]
 7 then
 8     g++ -ggdb `pkg-config --cflags opencv` -o `basename $1 .cpp` $1 `pkg-config --libs opencv`;
 9 else
10     echo "Please compile only .c or .cpp files"
11 fi
12 echo "Output file => ${1%.*}"
複製程式碼

 將上面程式碼儲存成shell指令碼,在每次編譯程式時呼叫即可。

如果在編譯過程中出現如下錯誤:

1 [ 14%] Building CXX object modules/core/CMakeFiles/opencv_core.dir/src/system.cpp.o
2   /home/test/autobuild/instance-0/output/build/opencv-2.4.10/modules/core/src/system.cpp: In function '(static initializers for /home/test/autobuild/instance-0/output/build/opencv-2.4.10/modules/core/src/system.cpp)':
3   /home/test/autobuild/instance-0/output/build/opencv-2.4.10/modules/core/src/system.cpp:280:10: error: inconsistent operand constraints in an 'asm'

4 make[3]: *** [modules/core/CMakeFiles/opencv_core.dir/src/system.cpp.o] Error 1