반응형



Ubuntu에 설치된 Visual Studio Code에서 CMake를 사용하여 OpenCV 코드를 컴파일 하는 방법을 설명합니다. 



2019. 5. 9 : CMakeLists.txt 오류 수정

2019. 7. 8

2023. 8. 9 




1. 다음 포스팅을 참고하여 Visual Studio Code 설치 및 C/C++ 개발환경 설정을 진행합니다.

 

Visual Studio Code를 사용한 C/C++ 개발환경 만들기-(Windows/Ubuntu)

https://webnautes.tistory.com/1854




2. cmake를 설치해줍니다. 

 

$ sudo apt-get install cmake




3. Visual Studio Code 메뉴에서 파일 > 폴더 열기를 선택합니다. 

폴더 열기 창에서 오른쪽 위에 보이는 폴더 만들기 아이콘을 클릭합니다. 

 




생성할 폴더 이름을 입력하고 만들기 버튼을 클릭합니다. 

 



생성된 폴더로 이동됩니다. OK 버튼을 클릭합니다. 

 




4. 폴더 이름 옆에 마우스 커서를 가져가면 보이는 새파일 아이콘을 클릭하고  

 



입력란이 아래 보이면 파일이름( main.cpp)을 입력하고 엔터를 누릅니다. 파일이 생성되면서 편집기에 열립니다. 

 




다음 코드를 복사해서 붙여넣기합니다.  Ctrl + S를 눌러서 저장합니다. 

 

#include "opencv2/opencv.hpp"
#include <iostream> 
 
using namespace cv; 
using namespace std
 
 
 
int main(int, char**) 


    VideoCapture cap(0); 
    if (!cap.isOpened()) 
    { 
        printf("카메라를 열수 없습니다. \n"); 
    } 
 
 
    Mat frame; 
    namedWindow("camera1", 1); 
 
 
    for (;;) 
    { 
 
        cap >> frame; 
 
        imshow("camera1", frame); 
 
        if (waitKey(20) >= 0) break
    } 
 
 
    return 0
}  




5. 앞에서 했던 방식으로 CMakeLists.txt 파일을 생성하고 다음 내용을 복사합니다. Ctrl + S를 눌러서 저장합니다. 

 

get_filename_component(ProjectId ${CMAKE_CURRENT_LIST_DIR} NAME)
string(REPLACE " " "_" ProjectId ${ProjectId})
project(${ProjectId} C CXX)
set (CMAKE_CXX_STANDARD 11)
cmake_minimum_required(VERSION 3.0)
find_package( OpenCV REQUIRED )

file(GLOB SOURCES  *.cpp)

add_executable(${PROJECT_NAME} ${SOURCES}  )
target_link_libraries( ${PROJECT_NAME} ${OpenCV_LIBS} )
 




6. 메뉴에서 Terminal > Configure Tasks를 선택합니다.  목록에서 “템플릿에서 tasks.json 파일 만들기(Create tasks.json file from template)”를 선택합니다. 




Others를 선택합니다.

 



tasks.json 파일이 열립니다. 



tasks.json 파일을 다음 내용으로 변경하고 Ctrl + S를 눌러서 저장합니다. 

 

{
    "version": "2.0.0",
    "runner": "terminal",
    "type": "shell",
    "echoCommand": true,
    "presentation" : { "reveal": "always" },
    "tasks": [
          //C++ 컴파일
          {
            "label": "compile for C++",
            "command": "cd ${fileDirname} && cmake . && make",
            "group": "build",

            //컴파일시 에러를 편집기에 반영
            //참고:   https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher

            "problemMatcher": {
                "fileLocation": [
                    "relative",
                    "${workspaceRoot}"
                ],
                "pattern": {
                    // The regular expression.
                  //Example to match: helloWorld.c:5:3: warning: implicit declaration of function 'prinft'
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        // 바이너리 실행(Ubuntu)

        {

            "label": "execute",

            "command": "cd ${fileDirname} && ./${workspaceFolderBasename} ",

            "group": "test"

        }

    ]
}




7. 소스 코드 파일 main.cpp을 선택한 상태에서 Ctrl + Alt + C를 누르면 보이는 메뉴에서 compile for C++를 선택합니다. 

 



잠시후 컴파일이 진행됩니다. 

 

 *  Executing task: cd /home/webnautes/opencv_test && cmake . && make 

 

-- The C compiler identification is GNU 11.4.0

-- The CXX compiler identification is GNU 11.4.0

-- Detecting C compiler ABI info

-- Detecting C compiler ABI info - done

-- Check for working C compiler: /usr/bin/cc - skipped

-- Detecting C compile features

-- Detecting C compile features - done

-- Detecting CXX compiler ABI info

-- Detecting CXX compiler ABI info - done

-- Check for working CXX compiler: /usr/bin/c++ - skipped

-- Detecting CXX compile features

-- Detecting CXX compile features - done

-- Configuring done

-- Generating done

-- Build files have been written to: /home/webnautes/opencv_test

[ 50%] Building CXX object CMakeFiles/opencv_test.dir/main.cpp.o

[100%] Linking CXX executable opencv_test

[100%] Built target opencv_test




8. Ctrl + Alt + R를 누르고 메뉴에서 execute를 선택합니다. 

 



프로그램이 실행되어 웹캠에서 캡처된 영상이 보이게 됩니다.




9. OpenCV 헤더파일을 추가하여 관련 함수나 클래스의 정의를 볼 수 있도록 합니다.



현재 opencv2/opencv.hpp 파일에 대한 정보를 가져올 수 없어서 초록색 줄이 보입니다. 

OpenCV 함수나 클래스의 정의를 볼 수도 없습니다.

 



초록색으로 보이는 헤더파일에 마우스 커서를 가져갔을 때 보이는 노란색 전구를 클릭하면 메뉴가 보입니다.

첫번째 항목인 Add to를 선택합니다.

 



잠시후 OpenCV 헤더파일에 보이던 초록색 줄이 사라집니다.

 



이제 OpenCV의 함수나 클래스의 정의를 볼 수 있습니다.  

VideoCapture에 마우스 커서를 가져가면 클래스 정의가 보이며 F12를 누르면 VideoCapture가 정의된 파일로 이동합니다. 

 








반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts