LoginSignup
7
3

More than 3 years have passed since last update.

MacにOpenCV(C++)環境を構築する

Posted at

環境

  • macOS Catalina version 10.15.6
  • Homebrew 2.4.8
  • cmake 3.18.0

OpenCVのインストール

ソースコードからビルドしたほうが詳細なオプションを変更することが可能ですが、依存関係など面倒な点が多いのでbrewでインストールします。

brew install opencv

2020.7.28現在、上のコマンドを実行するとOpenCV4.4.0がインストールされます。2系3系をインストールしたい場合はそれぞれ以下のようにします。

2系

brew install opencv@2

3系

brew install opencv@3

テスト

正常にインストールできているかテストします。
以下のようなディレクトリ構造をとります。

opencv_test/
├── CMakeLists.txt
├── build
├── main.cpp
└── sample.jpg

sample.jpgはてきとうに画像ファイルを用意してください。

画像を読み込んで表示するだけのシンプルなプログラムです。

main.cpp
#include <opencv2/opencv.hpp>
int main() {
    cv::Mat img = cv::imread("sample.jpg");
    if(img.empty()) {
        return -1;
    }
    cv::namedWindow("test", cv::WINDOW_AUTOSIZE);
    cv::imshow("test", img);
    cv::waitKey(0);
    cv::destroyWindow("test");
    return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.1)
project (test)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall")
find_package(OpenCV REQUIRED)
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable(main main.cpp)
target_link_libraries(main ${OpenCV_LIBS})

実行

cmakeをインストールしていなかった人は

brew install cmake

でインストールしてください。

cd build
cmake .. .
make
cd ..
./build/main

画像が表示されれば成功です。

7
3
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
7
3