1. 程式人生 > >通過opencv的封裝函式實現對xml、yml檔案的儲存跟讀取操作

通過opencv的封裝函式實現對xml、yml檔案的儲存跟讀取操作

通過使用Opencv的封裝函式介面”FileStorage“可以很方便的實現xml、yml檔案的讀取操作。從而方便進行資料的儲存。其相應的程式碼為:

#include"opencv2//opencv.hpp"
#include"opencv2//highgui//highgui.hpp"
using namespace std;
using namespace cv;
typedef struct
{
	int x;
	int y;
	string s;
}test_t;

void data_info_dump(test_t outt, map<string, int>outm, int a1, int a2, string str, vector<int>out)
{
	cout << "a1:" << a1 << endl;
	cout << "a2:" << a2 << endl;
	cout << "str:" << str << endl;
	cout << "outt.x" << outt.x << endl;
	cout << "outt.y" << outt.y << endl;
	cout << "outt.s" << outt.s << endl;
	cout << "curry" << outm["curry"] << endl;
	cout << "kobe" << outm["kobe"] << endl;
	cout << "james" << outm["james"] << endl;
	for (int i = 0; i < out.size(); i++)
	{
		cout << out[i] << endl;
	}

}



int main()
{
	//檔案可以儲存為xml、yml.兩者的讀取方法都一樣
	FileStorage fs("test.xml", FileStorage::WRITE);
	//FileStorage fs("test.yml", FileStorage::WRITE);
	int a1 = 2;
	char a2 = -1;
	string str = "hello sysu!";
	int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	test_t t = { 3, 4, "hi sysu" };
	map<string, int>m;
	m["kobe"] = 100;
	m["james"] = 99;
	m["curry"] = 98;
	fs << "int_data" << a1;
	fs << "char_data" << a2;
	fs << "string_data" << str;
	//這個是進行陣列的儲存,
	fs << "array_data" << "[";
	for (int i = 0; i < 10; i++)
	{
		fs << arr[i];
	}
	fs << "]";
	//寫入結構體,其值是有對應的鍵值的
	fs << "struct_data" << "{";
	fs << "x" << t.x;
	fs << "y" << t.y;
	fs << "s" << t.s;
	fs << "}";
	//map的寫入
	fs << "map_data" << "{";
	map<string, int>::iterator it = m.begin();
	for (; it != m.end(); it++)
	{
		fs << it->first << it->second;
	}
	fs << "}";
	fs.release();

	//進行資料的讀取。
	test_t read_t;
	map<string, int>readmap;
	FileStorage readfs("test.xml", FileStorage::READ);
	vector<int>arrvalue;
	a1 = (int)readfs["int_data"];
	a2 = (int)readfs["cahr_data"];
	str = (string)readfs["string_data"];
	FileNode arr_node = readfs["array_data"];
	FileNodeIterator fni = arr_node.begin();
	FileNodeIterator fniEnd = arr_node.end();
	int count = 0;
	for (; fni != fniEnd; fni++)
	{
		arrvalue.push_back((int)(*fni));
	}
	//資料節點,其中通過“[”或者“{”進行儲存的資料
	FileNode readmap_node = readfs["map_data"];
	readmap["curry"] = (int)readmap_node["curry"];
	readmap["james"] = (int)readmap_node["james"];
	readmap["kobe"] = (int)readmap_node["kobe"];
	FileNode readstruct_node = readfs["struct_data"];
	read_t.x = (int)readstruct_node["x"];
	read_t.y = (int)readstruct_node["y"];
	read_t.s = (int)readstruct_node["s"];
	//把讀取的結果顯示到控制檯
	data_info_dump(read_t, readmap, a1, a2, str, arrvalue);

	while (true)
	{

	}
	return 0;
}