더북(TheBook)

Stitcher 클래스를 이용하여 여러 장의 영상을 이어 붙이는 예제 코드를 코드 14-9에 나타냈습니다. 코드 14-9 프로그램은 명령행 인자로부터 여러 개의 영상 파일 이름을 입력으로 받고, 파노라마 결과 영상을 생성합니다. 코드 14-9의 소스 파일과 사용된 영상 파일은 내려받은 예제 파일 중 ch14/stitching 프로젝트에서 확인할 수 있습니다.

코드 14-9 영상 이어 붙이기 예제 프로그램 [ch14/stitching]

01    #include "opencv2/opencv.hpp"
02    #include <iostream>
03     
04    using namespace cv;
05    using namespace std;
06     
07    int main(int argc, char* argv[])
08    {
09        if (argc < 3) {
10            cerr << "Usage: stitching.exe <image_file1> <image_file2> [<image_file3> ...]" << endl;
11            return -1;
12        }
13     
14        vector<Mat> imgs;
15        for (int i = 1; i < argc; i++) {
16            Mat img = imread(argv[i]);
17     
18            if (img.empty()) {
19                cerr << "Image load failed!" << endl;
20                return -1;
21            }
22     
23            imgs.push_back(img);
24        }
25     
26        Ptr<Stitcher> stitcher = Stitcher::create();
27     
28        Mat dst;
29        Stitcher::Status status = stitcher->stitch(imgs, dst);
30     
31        if (status != Stitcher::Status::OK) {
32            cerr << "Error on stitching!" << endl;
33            return -1;
34        }
35     
36        imwrite("result.jpg", dst);
37     
38        imshow("dst", dst);
39     
40        waitKey();
41        return 0;
42    }

 

9~12행 명령행 인자 개수가 3보다 작으면 프로그램 사용법을 콘솔 창에 출력하고 프로그램을 종료합니다.

14~24행 명령행 인자로 전달된 영상 파일을 각각 불러와서 vector<Mat> 타입의 변수 imgs에 추가합니다. 만약 영상 파일을 불러오지 못하면 에러 메시지를 출력하고 프로그램을 종료합니다.

26행 Stitcher 객체를 생성합니다.

28~29행 imgs에 저장된 입력 영상을 이어 붙여서 결과 영상 dst를 생성합니다.

31~34행 영상 이어 붙이기가 실패하면 에러 메시지를 출력하고 프로그램을 종료합니다.

36행 결과 영상을 result.jpg 파일로 저장합니다.

38행 결과 영상을 dst 창에 나타냅니다.