输入输出XML和YAML文件

来源:互联网 发布:深圳网络安防培训学校 编辑:程序博客网 时间:2024/04/26 19:57
#include "opencv2/core/core.hpp"#include "opencv2/highgui/highgui.hpp"#include "iostream"#include "string"using namespace std;using namespace cv;class MyData{public:MyData(): A(0), X(0), id(){}explicit MyData(int) : A(97), X(CV_PI), id("mydata1234")// explicit构造函数是用来防止隐式转换的{}     void write( FileStorage& fs ) const{  //对自定义类进行写序列化fs << "{" << "A" << A << "X" << X << "id" << id << "}";}void read( const FileNode& node ){  //从序列读取自定义类A = (int)(node["A"]);X = (int)(node["X"]);id = (string)(node["id"]);}public:int A;double X;string id;};void write(FileStorage& fs, const std::string&, const MyData& x){x.write(fs);}void read(const FileNode& node, MyData& x, const MyData& default_value = MyData()){if(node.empty())x = default_value;elsex.read(node);}ostream& operator << ( ostream& out, const MyData& m){  //对"<<"运算符的重载 ,返回值类型为引用,将数据显示到屏幕上用到out << "{ id = " << m.id << ", ";out << "X = " << m.X << ", ";out << "A = " << m.A << "}";return out;}int main(int argc, char* argv[]){if ( argc != 2){return -1;}string filename = argv[1];{ //writeMat R = Mat_<uchar>::eye( 3, 3 );Mat T = Mat_<double>::zeros( 3, 1);MyData m(1); //显式调用MyData的构造函数,初始化的时候调用有参数的那个FileStorage fs( filename, FileStorage::WRITE );fs << "iterationNr" << 100;fs << "string" << "[";  //对于序列,在第一个元素前输出”[“字符,并在最后一个元素后输出”]“字符fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";fs << "]";fs << "Mapping";  //对于maps使用相同的方法,但采用”{“和”}“作为分隔符fs << "{" << "one" << 1;  //fs << "two" << 2 << "}";fs << "R" << R;fs << "T" << T;fs << "MyData" << m;  //写入自己的数据fs.release();cout << "Write Done" << endl;  //写入完成}{ //readcout << endl << "Reading" << endl;FileStorage fs;fs.open( filename, FileStorage::READ );int itNr;itNr = (int)fs["iterationNr"];cout << itNr;if ( !fs.isOpened() ){cout << "Fail to open" << filename <<endl;return -1;}FileNode n = fs["string"];if ( n.type() != FileNode::SEQ ){cout << "strings is not a sequence! FAIL" << endl;return -1;}FileNodeIterator it = n.begin(), it_end = n.end();for (;it != it_end; ++it){cout << (string)*it << endl;}n = fs["Mapping"]; //将节点定位到Maping处cout << "one" << (int)(n["one"]) << ";";cout << "two" << (int)(n["two"]) << endl;MyData m; //读取自己的数据结构Mat R, T;fs["R"] >> R;fs["T"] >> T;fs["MyData"] >> m;cout << endl << "R=" << R << endl;cout  << "T=" << endl << T << endl << endl;cout  << "MyData=" << endl << m << endl << endl;fs["NonExistint"]  >> m; //尝试读取一个不存在的值cout << endl << "NonExisting=" << endl << m <<endl; }cout << endl << "Tip: Open up " << filename << " with a text editor to see the serialized data." << endl;return 0;}

0 0