2 minute read

Mac OS OpenCV 설치 방법

1. Homebrew를 사용하여 OpenCV 설치하기

  • Homebrew로 OpenCV를 설치하려면
brew install opencv
  • 이미 OpenCV가 설치되어 있다면, 아래 명령어를 실행해 OpenCV 설치 상태를 확인할 수 있다.
pkg-config --modversion opencv4

2. VSCode 확장 프로그램 설치

  • C/C++(Microsoft)
  • Code Runner(옵션)
  • CMake Tools

  • CMake Tools를 사용하기 때문에 설치해줬다.

3. CMakeLists.txt 설정

  • CMakeLists.txt 파일을 가장 상위 디렉토리에 생성하여 아래 내용을 작성해준다.
cmake_minimum_required(VERSION 3.10)
project(OpenCVStudy)

# C++ 표준 설정
set(CMAKE_CXX_STANDARD 17)

# OpenCV 패키지 찾기
find_package(OpenCV REQUIRED)

# 명령행 변수로 실행할 챕터와 파일 지정 (기본값 설정)
set(CHAPTER "chapter1" CACHE STRING "Chapter folder name")
set(EXERCISE "ex1" CACHE STRING "Exercise file name")

# 실행 파일 경로 설정
set(SOURCE_FILE "${CMAKE_SOURCE_DIR}/chapters/${CHAPTER}/${EXERCISE}.cpp")

# 소스 파일 존재 여부 확인
if(NOT EXISTS ${SOURCE_FILE})
    message(FATAL_ERROR "Source file ${SOURCE_FILE} does not exist. Please check CHAPTER and EXERCISE settings.")
endif()

# 실행 파일 빌드
add_executable(OpenCVStudy ${SOURCE_FILE})

# OpenCV 라이브러리 연결
target_link_libraries(OpenCVStudy ${OpenCV_LIBS})
  • 본인의 디렉토리 구조는 아래와 같아서 CMake 파일을 위에처럼 설정했다.
OpenCV/
├── build/                           # CMake로 생성된 빌드 디렉토리
│   └── (빌드 아티팩트 및 실행 파일)
├── chapters/                        # 실습 파일 폴더
│   ├── chapter2/                    # 2번째 챕터
│   │   ├── ex1.cpp                  # 실습 1
│   │   ├── ex2.cpp                  # 실습 2
│   │   └── ...                      # 추가 실습 파일
│   ├── chapter3/                    # 3번째 챕터
│   │   ├── ex1.cpp                  # 실습 1
│   │   ├── ex2.cpp                  # 실습 2
│   │   └── ...
│   ├── ...                          # 추가 챕터
├── images/                          # 이미지 파일 폴더
│   ├── lenna.bmp                    # 샘플 이미지
│   ├── example.jpg                  # 다른 이미지
│   └── ...                          # 추가 이미지 파일
├── CMakeLists.txt                   # CMake 설정 파일
  • 각 실습 파일을 build할 때는 아래 코드를 통해서 build한다.
//원하는 chapter, ex번호 변경 가능
cmake -S . -B build -DCHAPTER=chapter2 -DEXERCISE=ex2 
cmake —build build
./build/OpenCVStudy
  • 매번 입력해야하는 번거로움이 있다…

4. VSCode 설정 파일 작성(.json)

  • .vscode/c_cpp_properties.json 파일이 있다면 수정하고 없다면 생성한다.
  • OpenCV 헤더 경로를 추가한다.
  • 헤더 경로의 경우 아래 명령어를 통해 확인할 수 있다.
pkg-config --cflags opencv4
  • 아래와 같이 나온 경우 /opt…부터 헤더 경로에 포함시키면 된다.
-I/opt/homebrew/opt/opencv/include/opencv4 
{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**",
                "/opt/homebrew/opt/opencv/include/opencv4" //OpenCV 헤더 경로
            ],
            "defines": [],
            "macFrameworkPath": [
                "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
            ],
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "macos-clang-arm64"
        }
    ],
    "version": 4
}
  • .vscode/tasks.json 생성(OpenCV 프로젝트를 빌드하는 명령을 설정)
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build",
      "type": "shell",
      "command": "cmake",
      "args": [
        "-S",
        ".",
        "-B",
        "build"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "detail": "Generates build files using CMake"
    },
    {
      "label": "compile",
      "type": "shell",
      "command": "cmake",
      "args": [
        "--build",
        "build"
      ],
      "group": {
        "kind": "build",
        "isDefault": false
      }
    }
  ]
}
  • .vscode/launch.json 생성(디버그 환경 설정)
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "C++ Debug",
      "type": "cppdbg",
      "request": "launch",
      "program": "${workspaceFolder}/build/OpenCVProject",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "lldb",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ]
    }
  ]
}

5. 테스트 코드 작성

#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;

int main(void){
    cout<<"Hello OpenCV"<<CV_VERSION<<endl;
    return 0;
}