상세 컨텐츠

본문 제목

#OpenCV 4로 배우는 컴퓨터 비전과 머신 러닝 - 6

Programing/OpenCV

by CouqueD'asse 2022. 5. 26. 16:19

본문

4.3 이벤트 처리

 

4.3.1 키보드 이벤트 처리

int main(void)
{
	Mat img = imread("char.png");
	namedWindow("img");
	imshow("img", img);

	while (true)
	{
		if (waitKey() == 27)
		{
			break;
		}
	}
	destroyAllWindows();
	return 0;
}

 

4.3.2 마우스 이벤트 처리

void on_mouse(int event, int x, int y, int flags, void*);
int main(void)
{
	img = imread("char.png");
	namedWindow("img");
	imshow("img", img);

	while (true)
	{
		if (waitKey() == 27)
		{
			break;
		}
	}

	destroyAllWindows();
	return 0;
}

void on_mouse(int event, int x, int y, int flags, void*)
{
	switch (event)
	{
	case EVENT_LBUTTONDOWN :
		pt = Point(x, y);
		cout << "EVENT_LBUTTONDOWN" << x << ", " << y << endl;
		break;
	case EVENT_LBUTTONUP:
		pt = Point(x, y);
		cout << "EVENT_LBUTTONUP" << x << ", " << y << endl;
		break;
	case EVENT_MOUSEMOVE:
		if (flags & EVENT_FLAG_LBUTTON)
		{
			line(img, pt, Point(x, y), Scalar(0, 255, 0), 2);
			imshow("img", img);
			pt = Point(x, y);
		}
		break;
	}
}

 

4.3.3 트랙바 사용하기

void on_level_change(int pos, void* userdata);
int main(void)
{
	Mat img = Mat::zeros(400, 400, CV_8UC1);

	namedWindow("img");
	createTrackbar("level", "img", 0, 16, on_level_change, (void*)&img);

	imshow("img", img);
	waitKey();

	return 0;
}

void on_level_change(int pos, void* userdata)
{
	Mat img = *(Mat*)userdata;

	img.setTo(pos * 16);
	imshow("img", img);
}

 

4.4 OpenCV 데이터 파일 입출력

 

4.4.1 FileStorage 클래스

virtual bool FileStorage::open(const String& filename, int flags, 
		const String& encoding = String());
virtual bool FileStorage::isOpened() const;
virtual bool FileStorage::release(); // 파일을 닫고 메모리 버터를 해제

 

4.4.2 데이터 파일 저장하기

void writeData()
{
	String name = "Jane";
	int age = 10;
	Point pt1(100, 200);
	vector<int> scores = { 80, 90, 50 };
	Mat mat = (Mat_<float>(2, 2) << 1.0f, 1.5f, 2.0f, 3.2f);

	FileStorage fs(filename, FileStorage::WRITE);

	if (!fs.isOpened())
	{
		return;
	}

	fs << "name" << name;
	fs << "age" << age;
	fs << "point" << pt1;
	fs << "scores" << scores;
	fs << "data" << mat;

	fs.release();
}

 

4.4.3 데이터 파일 불러오기

void readData()
{
	String name;
	int age;
	Point pt1;
	vector<int> scores;
	Mat mat;

	FileStorage fs(filename, FileStorage::READ);

	if (!fs.isOpened())
	{
		return;
	}

	fs["name"] >> name;
	fs["age"] >> age;
	fs["point"] >> pt1;
	fs["scores"] >> scores;
	fs["data"] >> mat;

	fs.release();

	cout << "name " << name << endl;
	cout << "age " << age << endl;
	cout << "point " << pt1 << endl;
	cout << "scores " << Mat(scores).t() << endl;
	cout << "data \n" << mat << endl;

}

 

관련글 더보기