--- title: Linux環境下安裝OpenCV 4.5.3 (C++) tags: Linux, Ubuntu, OpenCV, C++ description: View the slide with "Slide Mode". --- # Linux環境下安裝OpenCV 4.5.3 (C++) <!-- Put the link to this slide here so people can follow --> --- 寫作日期 : 2021/10/3 紀錄著建OpevCV環境一天的故事。 ## 安裝步驟 ### Step1 事前準備 - 安裝cmake, pkg-config, lib* ```typescript= $sudo apt-get install gcc g++ cmake pkg-config build-essential $sudo apt-get install libgtk2.0-dev libavcodec-dev libavformat-dev libtiff5-dev libswscale-dev ``` - 從github下載opencv ```typescript= $cd ~ $git clone https://github.com/opencv/opencv.git ``` - 建立build資料夾 ```typescript= $cd opencv $mkdir build ``` --- ### Step2 編譯lib - 使用cmake產生makefile ```typescript= $cd build $cmake -D CMAKE_BUILD_TYPE=Release -D OPENCV_GENERATE_PKGCONFIG=YES -D CMAKE_INSTALL_PREFIX=/usr/local .. ``` - make ```typescript= $make -j4 //cpu的核心數 $sudo make install ``` - 配置pkg-config ```typescript= $sudo vim /etc/ld.so.conf 加入Path: /usr/local/lib $sudo ldconfig -v $export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig ``` - 確認 opencv 安裝版本 ```typescript= $pkg-config --modversion opencv4 ``` --- ### Step3 驗證 - 創建一個專案資料夾 ```typescript= $cd ~ $mkdir cvtest ``` - 使用vs code 在cvtest資料夾下建立 - [x] cvtest.cpp - [x] lena.jpg (#從網路下載) - 複製貼上以下code ```typescript= #include <opencv2/highgui.hpp> #include <iostream> int main( int argc, char** argv ) { cv::Mat image; image = cv::imread("lena.jpg",cv::IMREAD_COLOR); if(! image.data) { std::cout<<"Could not open file" << std::endl; return -1; } cv::namedWindow("lena", cv::WINDOW_AUTOSIZE); cv::imshow("lena", image); cv::waitKey(0); return 0; } ``` - 在vs code 按下"ctrl+shift+p" 搜尋 “C/C++: Edit Configurations(JSON)” - 在"c_cpp_properties.json"的include path 加入 "/usr/local/include/opencv4/**"![](https://i.imgur.com/UDP9Wwg.png) - 在cvtest資料夾下,使用vs code創建一個Makefile(#建議自己打,不然可能會有error) ```typescript= CC = g++ PROJECT = cvtest SRC = cvtest.cpp LIBS = `pkg-config --cflags --libs opencv4` $(PROJECT) : $(SRC) $(CC) $(SRC) -o $(PROJECT) $(LIBS) ``` - 回到terminal ```typescript= $make $./cvtest ``` ![](https://i.imgur.com/tGyNpmG.png) ### 到此處都沒有異常,則大功告成啦! --- ## #除錯 - cmake的時候遇到 "In-source builds are not allowed" in cmake" 代表在過程中不小心產生 "CMakeCache.txt",需先刪除 ```typescript= $rm ../CMakeCache.txt ``` - 執行過程產生 Gtk-Message: Failed to load module “canberra-gtk-module” ```typescript= $sudo apt install libcanberra-gtk-module libcanberra-gtk3-module ``` --- ### Thank you! :sheep: You can find me on - GitHub - Twitter - or email me