본문 바로가기

영상처리/OpenCV 및 영상처리 이론

OpenCV 기초 - 2. 영상처리 준비(2)

 

영상 생성, 크기 출력, 뒤집기, 복사에 대해서 알아보겠습니다.

 

 

 

 

- 멤버변수 data

imread() 함수를 통해 영상을 읽을 수 있지만 지난번에 설명드렸듯이 사진이 존재하지 않으면 문제가 발생합니다. 이러한 문제를 예방하기 위하여 영상이 잘 불러와졌는지 확인하는 절차를 습관화하여야 하며 이를 

 

if (!image.data)

{

//영상 데이터 없음

return 0;

}

 

의 형태로 간단하게 구현할 수 있습니다. 

 

※ 참고 : data는 영상 데이터가 들어갈 메모리를 가리키는 변수입니다. 영상을 읽지 못 했을 경우 0으로 값이 설정되게 되어있습니다.

 

- void flip( InputArray src, OutputArray dst, int flipCode )

flip 함수는 간단하게 원본 영상을 뒤집는 과정을 수행하게 해줍니다. 뒤집는 방향은 flipCode 값에 의해 결정되게 되며 

 

flipCode > 0 : 수평방향

 

flipCode = 0 : 수직방향

 

flipCode < 0: 수평+수직

 

의 형태로 동작하게 됩니다. src에 뒤집길 원하는 Mat을 넣어주면 되고 dst에 저장할 Mat을 넣어주면 됩니다.

 

- void Mat::copyTo( OutputArray m ) const

- void Mat::copyTo( OutputArray m,  InputArray mask) const

copyTo 함수는 위와 같이 2개의 형태로 사용이 가능한데 이번 예제에서는 첫번째 방법으로 사용하고 있습니다. 함수를 호출하는 Mat의 데이터가 파라미터로 들어가는 Mat에 복사되게 됩니다.

 

 

※ 참고 : 깊은 복사, 얕은 복사

 

- copyTo와 clone은 깊은 복사 수행

- image2 = result 의 형태로 대입해줄 경우 얕은 복사

 

차이점 : 얕은 복사는 메모리를 공유하기 때문에 원본에 변화가 생길 경우 복사본에도 영향을 끼치지만 깊은 복사의 경우 메모리를 새로 할당하기 때문에 이러한 문제가 없습니다.

 

 

-결과

 

영상을 불러오기 전과 후의 size 변화

 

 
 
 원본 이미지 flip(image, result, 1) - 수평
 
 
image2 = result; 얕은 복사
원본(result)의 변화가 영향을 끼침
copyTo를 이용한 깊은 복사
원본(result)의 변화에 영향을 받지 않음

 

 

그레이 영상 생성

 

 

 

- 코드 첨부

더보기

/*------------------------------------------------------------------------------------------*\

   This file contains material supporting chapter 1 of the cookbook:  

   Computer Vision Programming using the OpenCV Library. 

   by Robert Laganiere, Packt Publishing, 2011.

 

   This program is free software; permission is hereby granted to use, copy, modify, 

   and distribute this source code, or portions thereof, for any purpose, without fee, 

   subject to the restriction that the copyright notice may not be removed 

   or altered from any source or altered source distribution. 

   The software is released on an as-is basis and without any warranties of any kind. 

   In particular, the software is not guaranteed to be fault-tolerant or free from failure. 

   The author disclaims all warranties with regard to this software, any use, 

   and any consequent failure, is purely the responsibility of the user.

 

   Copyright (C) 2010-2011 Robert Laganiere, www.laganiere.name

\*------------------------------------------------------------------------------------------*/

 

#include <iostream>

#include <opencv2/core/core.hpp>

#include <opencv2/highgui/highgui.hpp>

 

// 영상을 생성하고 반환하는 함수

cv::Mat function() {

 

// 영상 생성

cv::Mat ima(240,320,CV_8U,cv::Scalar(100));

// 영상 반환

return ima;

}

 

int main() {

 

// 영상 생성

cv::Mat image;

// 영상 크기 출력

std::cout << "size: " << image.size().height << " , " 

          << image.size().width << std::endl;

// 영상 열기

image=  cv::imread("img.jpg");

// 영상을 성공적으로 열었는지 확인

if (!image.data) { 

// no image has been created?

return 0;

}

// 영상 크기 출력

    std::cout << "size (after reading): " << image.size().height << " , " 

          << image.size().width << std::endl;

 

// 영상 띄워 보기

cv::namedWindow("Original Image"); // 창 정의

    cv::imshow("Original Image", image); // 영상 보기

 

// 다른 영상 생성

cv::Mat result;

// 영상 뒤집기

cv::flip(image,result,1); // 수평에 대한 양수

                              // 0은 수직,  

                              // 모두 음수임

// 결과 띄워 보기

cv::namedWindow("Output Image");

cv::imshow("Output Image", result);

// 키 입려 기다리기

cv::waitKey(0);

// 파일에 영상 쓰기

cv::imwrite("output.bmp", result);

 

// 두 개의 새로운 영상 생성

cv::Mat image2, image3;

 

image2= result; // 동일한 데이터를 참조하는 두 영상

result.copyTo(image3); // 새로운 복사본이 생성됨

 

// 수직으로 뒤집기

cv::flip(result,result,0); 

 

// 결과 띄워 보기

cv::namedWindow("image 2");

cv::imshow("image 2", image2);

cv::namedWindow("image 3");

cv::imshow("image 3", image3);

 

// 명암도 영상 가져오기

cv::Mat gray= function();

// 결과 띄워 보기

cv::namedWindow("Gray Image");

cv::imshow("Gray Image", gray);

 

// 키 입력 대기

cv::waitKey(0);

return 1;

}

 

 

 

※ 해당 코드는 에이콘 출판사에서 제공하는 Robert Laganiere의 소스 코드 수정본을 사용하였습니다.