1. 程式人生 > >ubuntu opencv開發環境配置介紹

ubuntu opencv開發環境配置介紹

文章目錄

一、原始碼包下載

  • 原始碼包從連結:https://opencv.org/releases.html 下載
  • 解壓原始碼包
    原始碼下載下來後是zip包,這裡本人下載的是3.4.3的版本,則使用unzip opencv-3.4.3.zip 解壓出來成下面樣子。
  • 原始碼包檔案列表
[email protected]:~/data/opencv/opencv-3.4.3$ tree -L 1 .
.
├── 3rdparty
├── apps
├── cmake
├── CMakeLists.txt
├── CONTRIBUTING.md
├── data
├── doc
├── include
├── LICENSE
├── modules
├── platforms
├── README.md
└── samples

二、工具集安裝

由於opencv使用cmake自動生成Makefile,所以需要安裝cmake工具。安裝後可能cmake工具版本太低,無法解析通過。就需要安裝最低版本之後的cmake

sudo apt-get update
sudo apt-get install cmake
sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff4.dev libswscale-dev libjasper-dev

本人在安裝時就遇到cmake版本過低問題。從網上下載了一個更高版本的cmake(https://cmake.org/files/v3.6/cmake-3.6.3.tar.gz).當然也可以一上來就檢查一下cmake/OpenCVMinDepVersions.cmake

,該檔案內容如下所示,可以看到最低cmake版本是2.8.12.2

set(MIN_VER_CMAKE 2.8.12.2)                                                                                                                    
set(MIN_VER_CUDA 6.5)
set(MIN_VER_PYTHON2 2.6)
set(MIN_VER_PYTHON3 3.2)
set(MIN_VER_ZLIB 1.2.3)
set(MIN_VER_GTK 2.18.0)

新版本的cmake下載下來後,請按著README.md的步驟來編譯安裝就行了,這裡就不多說了。

三、編譯-安裝opencv

1.建立編譯目錄

在編譯之前,一定要先建立一個編譯檔案,用來存放中間檔案。名字可以隨便取,這裡在原始碼根目錄下建立一個release目錄。當然從根目錄下的CMakeLists.txt檔案也可以看到,最好不要在根目錄下直接編譯。

   1 # ----------------------------------------------------------------------------                                                            
   2 #  Root CMake file for OpenCV
   3 #
   4 #    From the off-tree build directory, invoke:
   5 #      $ cmake <PATH_TO_OPENCV_ROOT>
   6 #
   7 # ----------------------------------------------------------------------------
   8 
   9 # Disable in-source builds to prevent source tree corruption.
  10 if(" ${CMAKE_SOURCE_DIR}" STREQUAL " ${CMAKE_BINARY_DIR}")
  11   message(FATAL_ERROR "
  12 FATAL: In-source builds are not allowed.
  13        You should create a separate directory for build files.
  14 ")
  15 endif()

建立release後的目錄列表。

[email protected]:~/data/opencv/opencv-3.4.3$ tree -L 1 .
.
├── 3rdparty
├── apps
├── cmake
├── CMakeLists.txt
├── CONTRIBUTING.md
├── data
├── doc
├── include
├── LICENSE
├── modules
├── platforms
├── README.md
├── release
└── samples

2.使用cmake命令生成Makefile

cd release
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..
##CMAKE_BUILD_TYPE:編譯的版本,這裡編譯釋出版本(Release).如果想編譯Debug版本,就把Release替換成Debug
##CMAKE_INSTALL_PREFIX:生成動態庫安裝路徑,可以自定義,但是一定要在系統中指定。

3.遇到的麻煩

編譯過程中遇到錯誤,會在之前(release)建立目錄下生成一個錯誤日誌檔案(release/CMakeFiles$/CMakeError.log)。可以從錯誤log日誌發現解析過程中錯誤,下面是本人本地解析過程遇到的錯誤。

  7 Run Build Command:"/usr/bin/make" "cmTC_822de/fast"
  8 /usr/bin/make -f CMakeFiles/cmTC_822de.dir/build.make CMakeFiles/cmTC_822de.dir/build
  9 make[1]: Entering directory `/home/armwind/data/opencv/opencv-3.4.3/release/CMakeFiles/CMakeTmp'
 10 Building CXX object CMakeFiles/cmTC_822de.dir/cxx11.cpp.o
 11 /usr/bin/c++     -fPIE   -o CMakeFiles/cmTC_822de.dir/cxx11.cpp.o -c /home/armwind/data/opencv/opencv-3.4.3/cmake/checks/cxx11.cpp
 12 /home/armwind/data/opencv/opencv-3.4.3/cmake/checks/cxx11.cpp:4:2: error: #error "C++11 is not supported"
 13  #error "C++11 is not supported"
 14   ^
 15 /home/armwind/data/opencv/opencv-3.4.3/cmake/checks/cxx11.cpp: In function ‘int main()’:
 16 /home/armwind/data/opencv/opencv-3.4.3/cmake/checks/cxx11.cpp:11:10: error: ‘res’ does not name a type
 17      auto res = test();
 18           ^
 19 /home/armwind/data/opencv/opencv-3.4.3/cmake/checks/cxx11.cpp:12:12: error: ‘res’ was not declared in this scope
 20      return res;
 21             ^
 22 make[1]: *** [CMakeFiles/cmTC_822de.dir/cxx11.cpp.o] Error 1
 23 make[1]: Leaving directory `/home/armwind/data/opencv/opencv-3.4.3/release/CMakeFiles/CMakeTmp'
 24 make: *** [cmTC_822de/fast] Error 2
 25 
 26 ===== END =====

上面編譯錯誤#error "C++11 is not supported"可以很清晰的看到,報的是編譯器不支援c++11,針對這個問題,要麼我們通過命令sudo apt-get install build-essential直接更新編譯器,如果不行的話,只能通過手動安裝g++4.8以上的版本了,具體如下所示:

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install g++-4.8
##建立軟連結
sudo rm /usr/bin/g++
sudo ln -s /usr/bin/g++-4.8 /usr/bin/g++

光更新到g++4.8還不行,g++4.8預設不支援c++11,需要手動指定c++11編譯規則,如下所示:

alias g++='g++-4.8 -std=c++11'

一開始本人犯了個低階錯誤,由於之前已經建立過g++軟連線,這裡就直接g++來指定,如下所示,但是一直不生效。後來才發現。
alias g++='g++ -std=c++11'
如果上面配置沒問題的話,那麼此時執行如下命令,則會生成Makefile
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..

4.編譯過程

上面如果準備工作如果ok的話,那麼在release目錄下執行make,就會啟動編譯。

.....................................
[ 98%] Built target opencv_visualisation
Scanning dependencies of target opencv_interactive-calibration
[ 98%] Building CXX object apps/interactive-calibration/CMakeFiles/opencv_interactive-calibration.dir/calibController.cpp.o
[ 98%] Building CXX object apps/interactive-calibration/CMakeFiles/opencv_interactive-calibration.dir/calibPipeline.cpp.o
[ 98%] Building CXX object apps/interactive-calibration/CMakeFiles/opencv_interactive-calibration.dir/frameProcessor.cpp.o
[ 98%] Building CXX object apps/interactive-calibration/CMakeFiles/opencv_interactive-calibration.dir/main.cpp.o
[ 98%] Building CXX object apps/interactive-calibration/CMakeFiles/opencv_interactive-calibration.dir/parametersController.cpp.o
[ 98%] Building CXX object apps/interactive-calibration/CMakeFiles/opencv_interactive-calibration.dir/rotationConverters.cpp.o
[100%] Linking CXX executable ../../bin/opencv_interactive-calibration
[100%] Built target opencv_interactive-calibration
Scanning dependencies of target opencv_version
[100%] Building CXX object apps/version/CMakeFiles/opencv_version.dir/opencv_version.cpp.o
[100%] Linking CXX executable ../../bin/opencv_version
[100%] Built target opencv_version
[email protected]:~/data/opencv/opencv-3.4.3/release$

上面是編譯成功時的log,如果編譯報錯,請檢視error log.編譯成功的話,則執行sudo make install

5.連結環境配置

  • linux連結路徑
    使用如下命令,在開始新增/usr/local/lib,因為opencv庫就存放在/usr/local/lib目錄下面。
    sudo vim /etc/ld.so.conf.d/opencv.conf
    儲存當前opencv.conf,執行sudo ldconfig這一步千萬不要忘了),自此編譯環境準備好了。

  • OPENCV配置庫路徑和標頭檔案路徑
    其實這個已經由cmake給程式猿們做好了,在編譯opencv庫時已經做好具體請檢視opencv編譯目錄,這裡我的編譯目錄是release,配置檔案在:
    opencv-3.4.3/release/OpenCVConfig.cmake
    此檔案定義編譯時需要的巨集,詳情請檢視檔案內容。

四、demo演示

  • CmakeList.txt編寫
    其實下面的CmakeList檔案也是從opencv demo中拷貝出來的。
# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(displayimage_demo_test)

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
#這一句就是查詢opencv標頭檔案路徑和庫路徑,也不用新增到系統環境變數中去了
find_package(OpenCV REQUIRED)

# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

if(CMAKE_VERSION VERSION_LESS "2.8.11")
  # Add OpenCV headers location to your include paths
  include_directories(${OpenCV_INCLUDE_DIRS})
endif()

# Declare the executable target built from your sources
#新增編譯原始檔,有多個就新增多個。
add_executable(displayimage_demo displayimage.cpp)

# Link your application with OpenCV libraries
target_link_libraries(displayimage_demo ${OpenCV_LIBS})

  • 編譯小指令碼
    這個小編譯指令碼,主要是方便cmake中間變數刪除使用,要不然還要手動指定刪除中間檔案。
BUILD_DIR = ./obj

all: build
	    cd $(BUILD_DIR);  make -j4
clean:
	    rm $(BUILD_DIR) -rf
build:
	    mkdir $(BUILD_DIR);cd $(BUILD_DIR); cmake ..

make clean
make

使用小Makefile之後主目錄比較乾淨

使用小Makefile前
├── CMakeCache.txt
├── CMakeFiles
├── cmake_install.cmake
├── CMakeLists.txt
├── displayimage.cpp
└── Makefile

使用小Makefile後
├── CMakeLists.txt
├── displayimage.cpp
├── Makefile
└── obj

  • Cmake檔案編譯過程

– The C compiler identification is GNU 4.8.5
– The CXX compiler identification is GNU 4.8.5
– Check for working C compiler: /usr/bin/cc
– Check for working C compiler: /usr/bin/cc – works
– Detecting C compiler ABI info
– Detecting C compiler ABI info - done
– Detecting C compile features
– Detecting C compile features - done
– Check for working CXX compiler: /usr/bin/c++
– Check for working CXX compiler: /usr/bin/c++ – works
– Detecting CXX compiler ABI info
– Detecting CXX compiler ABI info - done
– Detecting CXX compile features
– Detecting CXX compile features - done
– Found OpenCV: /usr/local (found version “3.4.3”)
– OpenCV library status:
– version: 3.4.3
– libraries: opencv_calib3d;opencv_core;opencv_dnn;opencv_features2d;opencv_flann;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_shape;opencv_stitching;opencv_superres;opencv_video;opencv_videoio;opencv_videostab
– include path: /usr/local/include;/usr/local/include/opencv
– Configuring done
– Generating done
– Build files have been written to: /home/armwind/data/opencv/project/helloword

  • 例項程式碼
    opencv 原生程式碼中的demo有一個開啟linux 本地攝像頭的案例(opencv-3.4.3/samples/cpp/example_cmake)。目前本地沒有攝像頭,開啟失敗。但是程式可以執行,不過可以參考一下。
#include <cv.h> 
#include <highgui.h> 
#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp> 
using namespace cv; 

int main( int argc, char** argv ) { 
	Mat image; 
	char *image_path = "/home/armwind/data/opencv/opencv-3.4.3/samples/data/lena.jpg";
	char *path = NULL;
	if(argc != 2)
		path = image_path;
	else 
		path = argv[1];
        printf("image path is %s \n", path);
	image = imread( path, 1 ); 
	if( !image.data ) { 
		printf( "No image data \n" ); 
		return -1; 
	} 
	namedWindow( "hello world", CV_WINDOW_AUTOSIZE ); 
	imshow( "hello world", image ); 
	waitKey(0); 
	return 0; 
}

  • 執行結果
    預設執行結果
    ./obj/displayimage_demo
    在這裡插入圖片描述