[컴퓨터비전 STUDY / KOCW 한동대학교 황성수 교수님 강의 Review]
Mat(행렬) 은 openCV에서 사용되는 기본적인 자료 구조이다.
Mat를 표현하는 방법은 여러가지가 있다.
Mat (int rows, int cols, int type)
Mat (Size size, int type)
Mat (const Mat & m)
Mat (Size size, int type, const Scalar & s)
type : 각 픽셀의 data type을 나타낸다.
Pixel type에는 다음과 같은 종류들이 있다.
다채널 배열은 다음과 같다.
EX)
Mat mtx(3, 3, CV_32F);
// make a 3x3 floating-point matrix
Mat cmtx(10, 1, CV_64FC2);
// make a 10x1 2-channel floating-point matrix
(10-element complex vector)
Mat
img(1080, 1920, CV_8UC3);
// make a 3-channel (color) image of 1920 columns and 1080 rows.
Mat
img(Size(1920, 1080), CV_8UC3);
// make a 3-channel (color) image of 1920 columns and 1080 rows.
다음은 화면을 띄우는 openCV C++ 코드이다.
#include "cv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
int w = 150, h = 100; // 가로, 세로 크기
// 8bit unsigned char 타입의 단일 채널, 모든 Pixel이 흰색으로 처리
Mat image(h, w, CV_8UC1, Scalar(255));
// 생성된 이미지 크기 출력
cout << "Size: " << image.size().height << "," << image.size().width << endl; //
imshow("image", image);
waitKey(0);
return 0;
}
다채널에서는 Scalar(255, 0, 0) 형태로 표현하다. BGR 순이다.
Mat imread( const string & filename, int flags = 1)
flags가 1이면 칼라 이미지를, 0이면 흑백 이미지로 읽겠다는 의미이다.
다음은 이미지를 읽는 C++ 코드이다.
// 라이브러리 생략
int main() {
Mat gray_image, color_image;
// 0 on the 2nd parameter means read imgin grayscale
gray_image= imread("lena.png", 0);
// blank 2nd parameter means 1, which means read imgin colors
color_image= imread("lena.png");
imshow("gray image", gray_image);
imshow("color image", color_image);
waitKey(0);
return 0;
}
다음은 영상을 읽는 C++ 코드이다.
int main() {
Mat frame;
VideoCapture cap;
// 비디오 파일을 성공적으로 열면 true를, 실패하면 false를 반환함
// check if file exists. if none program ends
if (cap.open("background.mp4") == 0) {
cout << "no such file!" << endl;
waitKey(0);
}
while (1) {
// 비디오 스트림에서 다음 프레임을 읽어 frame 변수에 저장
cap >> frame;
// 읽은 프레임이 비어 있는지 확인함, 비디오 끝에 도달
if (frame.empty()) {
cout << "end of video" << endl;
break;
}
imshow("video", frame); // 새로운 frame의 화면을 띄워 비디오를 재생함
waitKey(33); # 33ms동안 대기, 우리 눈이 자연스럽게 영상을 인지할 수 있도록 하는 역할
}
}
다음은 웹캠에서 영상을 읽는 코드이다.
int main() {
Mat frame;
// capture from webcam
// whose device number=0, 연결된 webcam을 사용하도록 설정
VideoCapture cap(0);
while (1) {
cap >> frame;
imshow("web cam", frame);
waitKey(16);
}
}

다음은 Video Capture을 수행하는 코드이다.
int main() {
Mat frame;
VideoCapture cap;
// mp4 비디오 파일을 열록 시도하고, 파일을 열 수 없으면, 프로그램을 종료함
if (cap.open("background.mp4") == 0) return -1;
double fps = cap.get(CAP_PROP_FPS); // 비디오 프레임 속도를 가져옴
double time_in_msec = 0; int curr_frame = 0;
int total_frames = cap.get(CAP_PROP_FRAME_COUNT); // 비디오 전체 프레임 가져옴
// video stops after 3 sec, 3초 미만인 동안 반복됨
while (time_in_msec < 3000) {
cap >> frame; // 비디오에서 다음 프레임을 읽어 frame 변수에 저장함
if (frame.empty()) break;
// 현재 비디오의 재생 위치를 가져옴
time_in_msec = cap.get(CAP_PROP_POS_MSEC);
// 현재 프레임 번호를 가져옴
curr_frame = cap.get(CAP_PROP_POS_FRAMES);
// printing current frames over total frames
cout << "frames: " << curr_frame << " / " << total_frames << endl;
imshow("video", frame);
// calculating the right delay from given fps
waitKey(1000 / fps);
}
waitKey(0);
return 0;
}