티스토리 뷰

* 앞으로 작성할 글은 "openCV 3 computer vision application programming cookbook" 서적을 바탕으로 학습하고 추가 스터디하여 작성할 것이다.

 

opencv에서 이미지를 읽어오는 imread 함수에 대해 알아보겠다.

내용은 문서를 기준으로 작성하였으며, 예제 코드를 실행해보았다.


함수의 형태는 다음과 같다.

Mat cv::imread ( const String &  filename, int  flags = IMREAD_COLOR)

문서의 설명은 다음과 같다.

특이사항은 다음과 같다.
- 파일이 없거나, 퍼미션 등으로 read가 실패할 경우 empty matrix를 리턴한다. -> 반드시 제대로 reading이 되었는지 확인이 필요하다.
- flag를 통해 image read type을 설정할 수 있다.

flag의 종류는 다음과 같다.

다른 부분은 사실 사용할 일이 많이 없을 것 같고, GRAYSCALE의 경우만 살펴보았다. (Gray scale을 사용한다면, 리소스 양을 줄일 수 있으며, 계산 측면에서도 더 빠르게 처리할 수 있다는 장점이 있다.)

실제 코드는 아래와 같이 구성되어 있었다.

 
//! Imread flags
enum ImreadModes {
       IMREAD_UNCHANGED            = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
       IMREAD_GRAYSCALE            = 0,  //!< If set, always convert image to the single channel grayscale image (codec internal conversion).
       IMREAD_COLOR                = 1,  //!< If set, always convert image to the 3 channel BGR color image.
       IMREAD_ANYDEPTH             = 2,  //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
       IMREAD_ANYCOLOR             = 4,  //!< If set, the image is read in any possible color format.
       IMREAD_LOAD_GDAL            = 8,  //!< If set, use the gdal driver for loading the image.
       IMREAD_REDUCED_GRAYSCALE_2  = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2.
       IMREAD_REDUCED_COLOR_2      = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2.
       IMREAD_REDUCED_GRAYSCALE_4  = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4.
       IMREAD_REDUCED_COLOR_4      = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4.
       IMREAD_REDUCED_GRAYSCALE_8  = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8.
       IMREAD_REDUCED_COLOR_8      = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8.
       IMREAD_IGNORE_ORIENTATION   = 128 //!< If set, do not rotate the image according to EXIF's orientation flag.
     };


예제를 만들어보았다.

영상은 2가지, 컬러 개(dog.jpg)와 흑백 개(gray_dog.jpg)를 사용하였다. 

 

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>

using namespace std;
using namespace cv;

int main() {
	// Mat imread( const String& filename, int flags = IMREAD_COLOR );

	// original
	Mat original = imread("dog.jpg");
	if (!original.empty()) {
		cout << "original channel : " << original.channels() << endl;
		namedWindow("original");
		imshow("original", original);
		waitKey(0);
	}
	else
		cout << "original image read fail";

	// color -> gray scale read
	Mat grayScaleRead = imread("dog.jpg", IMREAD_GRAYSCALE);
	if (!grayScaleRead.empty()) {
		cout << "grayScaleRead channel : " << grayScaleRead.channels() << endl;
		namedWindow("grayScaleRead");
		imshow("grayScaleRead", grayScaleRead);
		waitKey(0);
	}
	else
		cout << "grayScaleRead image read fail";

	// original gray image, without flag
	Mat grayDefault = imread("gray_dog.jpg");
	if (!grayDefault.empty()) {
		cout << "grayDefault channel : " << grayDefault.channels() << endl;
		namedWindow("grayDefault");
		imshow("grayDefault", grayDefault);
		waitKey(0);
	}
	else
		cout << "gray_dog image read fail";

	// original gray image, with flag
	Mat grayUnchanged = imread("gray_dog.jpg", IMREAD_UNCHANGED);
	if (!grayUnchanged.empty()) {
		cout << "grayUnchanged channel : " << grayUnchanged.channels() << endl;
		namedWindow("grayUnchanged");
		imshow("grayUnchanged", grayUnchanged);
		waitKey(0);
	}
	else
		cout << "gray_dog image read fail";
}

총 4번 이미지를 불러온 후 channel을 출력하고, 화면에 뿌려보았다.
1번 : color 이미지, flag 없이 사용
2번 : color 이미지, GRAYSCALE 사용
3번 : gray 이미지, flag 없이 사용
4번 : gray 이미지, UNCHANGED 사용

결과는 다음과 같다.

1번과 2번의 결과는 당연해보인다. color 이미지를 default와 grayscale로 read했기 때문에 채널은 각각 3, 1이 출력된다.하지만 gray level의 영상을 read하는 경우 주의가 필요해보인다. flag 없이 불러온 경우 channel이 1이 아닌 3이 출력되었다. 원인을 분석해보면 다음과 같다.
 
 Mat imread( const String& filename, int flags = IMREAD_COLOR );

imread 함수의 flag는 지정해주지 않으면 IMREAD_COLOR flag를 사용한다. input이 gray level이지만, 해당 flag를 사용하면 RGB로 변환하게 된다. (물론 RGB 각 채널의 값은 동일할 것이다.) 
gray level의 이미지를 gray 그대로 불러오기 위해서는 "IMREAD_GRAYSCALE" 혹은 "IMREAD_UNCHANGED" flag를 넣어줘야 한다.

 

*가장 좋은 방법은 항상 flag를 용도에 맞게 적어주는 습관을 갖자.

'영상처리 > OpenCV' 카테고리의 다른 글

05. Scanning with iterator  (0) 2019.04.15
04.Scanning with pointer  (0) 2019.04.10
03. Accessing pixel values  (0) 2019.04.07
02. Mat 클래스 structure  (0) 2019.04.01
00. OpenCV 설치  (0) 2019.03.26
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함