컴퓨터 비전

OpenCV 기초

Jagbbum 2023. 10. 17. 11:51

OpenCV 기본 코드

#include <iostream>
#include "opencv2/opencv.hpp" //OpenCV 헤더

using namespace std;
using namespace cv;

int main()
{
	Mat img = imread("lenna.bmp"); // lenna.bmp 읽어옴
    // 저장은 imwrite

	if (img.empty()) { // 이미지 없을 시 동작
		cerr << "Image laod failed!" << endl;
		return -1;
	}

	namedWindow("image"); // image라는 윈도우 생성
	imshow("image", img); // image에 읽어온 데이터 보여줌
	waitKey(); // 키보드 입력 대기
	destroyAllWindows();
}

OpenCV 주요 클래스

Point_ 클래스 :  2차원 점의 좌표 표현을 위한 템플릿 클래스

+, -, *, /, += 등의 연산 제공
norm(Point(x,y)) // 영점에서 죄표까지의 대각선 거리

Size_ 클래스 : 영상 또는 사각형의 크기 표현을 위한 템플릿 클래스

Rect_ 클래스 :  2차원 사각형 표현을 위한 템플릿 클래스

Rect rect(10,10,60,40) // 10,10 위치에 60*40의 사각형을 그림
Size, Point 객체의 덛셈 뺄셈, Rect 끼리의 논리연산 지원

 

Vec 클래스 : 같은 자료형 원소 여러 개로 구성된 데이터 형식

Scalar 클래스 : 크기가 4인 double 배열을 멤버 변수로 가지는 클래스

Mat 클래스 : n차원 1채널 또는 다채널 행렬 표현을 위한 클래스

Mat::depth() : 행렬 원소가 사용하는 자료형 정보를 가리키는 매크로 상수
Mat::channels() : 원소 하나가 몇 개의 값으로 구성되는지 상수
Mat::type() : 깊이와 채널 수를 한꺼번에 나타내는 상수

 - Mat 영상의 픽셀 값 접근

Mat::at() : 좌표 지정이 직관적. 임의 좌표에 접근할 수 있음

예제
Mat::at(int y(행), int x(열))

Mat mat1 = Mat::zeros(3,4,CV_8UC1);
for(int y=0; y<mat1.rows; y++){
	for (int x=0; x<mat1.cols; x++){
    	mat1.at<unchar>(y,x)++;
    }
}


Mat::ptr() : at보다 빠르게 동작. 행 단위 연산에 유리

예제
Mat::ptr(int y(행))

Mat mat1 = Mat::zeros(3,4,CV_8UC1);
for(int y=0; y<mat1.rows; y++){
	unchar* p = mat1.ptr<unchar>(y);

	for (int x=0; x<mat1.cols; x++){
        p[x]++;
    }
}


MatIterator : 좌표를 지정하지 않아 안전하지만 성능 느림

예제

for (MatIterator_<nuchar> it = mat1.begin<unchar>(); it != mat1.end<unchar>(); ++it) {
	(*it)++;
}

VideoCapture 클래스

카메라와 동영상으로부터 프레임을 받아오는 작업을 처리

 

카메라 열기
VideoCapture::VideoCapture(int index, int spiPreference = CAP_ANY);
bool VideoCapture::open(int index,int spiPreference = CAP_ANY);

동영상 파일 열기
VideoCapture::VideoCapture(const String& filename, int spiPreference = CAP_ANY);
bool VideoCapture::open(const String& filename, int spiPreference = CAP_ANY);

현재 프레임 받아오기
bool VideoCapture::read(OutputArray image);
VideoCapture&VideoCapture::operator>>(Mat& image);

 

VideoWriter 클래스

일련의 정지 영상을 동영상 파일로 저장할 수 있는 클래스

VideoWriter::VideoWriter(const String& filename, int fourcc, double fps, Size frameSize, 
						bool isColor = true)
bool VideoWriter::open(const String& filename, int fourcc, double fps, Size frameSize, 
						bool isColor = true)

그리기 함수

직선

void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color,
		 int thickness = 1, int linetype = LINE_8, int shift = 0);

사각형

void rectangle(InputOutputArray img, Rect rec, const Scalar& color,
		 int thickness = 1, int linetype = LINE_8, int shift = 0);

void circle(InputOutputArray img, Point center, int radius, const Scalar& color,
		 int thickness = 1, int linetype = LINE_8, int shift = 0);

다각형

void polylines(InputOutputArray img, InputOutputArray pts, bool isClosed, const Scalar & color,
		       int thickness = 1, int linetype = LINE_8, int shift = 0);

문자열

void putText(InputOutputArray img, const String& text, Point org, int fontFace,
             double fontScale, Scalar color, int thickness = 1,
             int linetype = LINE_8, bool bottomLeftOrigin = false);

이벤트 처리

int waitKey(int delay = 0); // 키보드 이벤트

void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0);
// 마우스 이벤트 - 사용전 윈도우 생성 필요, onMouse 함수 필요

 

트랙바 사용하기

- 영상 출력 창에 부착되어, 프로그램 동작 중에 사용자가 지정된 범위 안의 값을 선택할 수 있는 GUI

int createTrackbar(const Strinf& trackbarname, const String& winname, int* value,
				  int count, TrackbarCAllback onChange = 0, void* userdata = 0);
                  
onChange : void (*TrackbarCallback)(int pos, void* userdata);