LoginSignup
0
0

OpenCVをビルドしてg++で実行する

Last updated at Posted at 2023-08-17

はじめに

この記事ではOpenCVをソースからビルドして、C++ファイルをg++でコンパイルし、実行するまでを扱う。

ビルド

依存パッケージのインストール

sudo apt install cmake g++ wget unzip libgtk2.0-dev -y

ソースのダウンロードと解凍

wget -O opencv.zip https://github.com/opencv/opencv/archive/4.x.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.x.zip
unzip opencv.zip
unzip opencv_contrib.zip

構成

mkdir build && cd build
cmake -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib-4.x/modules ../opencv-4.x

ビルド(時間がかかる)

cmake --build .

終了したらインストール

sudo make install

コンパイルと実行

~/.bashrcに以下を追記する

.bashrc
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

test.cppを適当な場所に作り同じ場所にimage.pngを置く

test.cpp
#include <opencv2/opencv.hpp>

int main()
{
    cv::Mat img = cv::imread("./image.png"); // image.pngをimgに代入.
    cv::imshow("img", img); // imgの表示.
    cv::waitKey(0); // キーが押されるまで待機.
    return 0;
}

コンパイルして実行

g++ test.cpp -I/usr/local/include/opencv4 \
    -lopencv_core \
    -lopencv_highgui \
    -lopencv_imgcodecs
./a.out

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0