Open中FileStorage使用

Open中FileStorage使用介绍

  • 简介

    由于OpenCV中检测中,很多源码涉及到相关信息写入文件或从文件中读取,故将其相关内容总结如下。

    FileStorage主要作用:将相关信息写入YAML或XML文件中,或从YAML或XML文件中读取相关信息。OpenCV中FileStorage使用主要相关的数据结构是FileNode和FileNodeIterator。

    在此讨论以XML和YAML文件输入输出。XML和YAML的串行化分别采用两种不同的数据结构:mapping(STL map)和element sequence(STL vector)。

    二者之间区别:map中每个元素都有唯一的标识符供用户访问,而在sequences中必须遍历所有的元素才能找到指定元素。

  • 1)XML和YAML文件的打开和关闭

     string filename = "Mytest.xml";
     FileStorage fs(filename, FileStorage::WRITE);
     ...
     fs.open(filename, FileStorage::READ);
    

    注意:第二个参数表示对文件操作的类型,包括:WRITE、READ、APPEND。文件扩展名表示输出格式,输出格式可以是压缩文件格式。

  • 2)输入\输出文本和数字

     fs << "Mytest" << 666;         // 使用<<输出操作符实现
     ...
     int iter;
     fs["Mytest"] >> iter;          // 使用>>操作符实现
     iter = (int) fs["Mytest"];     // 使用[]操作符和强制类型转换实现
    
  • 3)输入/输出OpenCV数据结构

     Mat R = Mat_<uchar>::eye(3, 3);
     Mat T = Mat_<double>::zeros(3, 1);
     fs << "R" << R;
     fs << "T" << T;
     ...
     fs["R"] >> R;
     fs["T"] >> T;
    
  • 4)输入/输出vector(数组)和相应的maps。

     // 序列输入:使用[]分割
     fs << "strings" << "[";                          // 开始时,先输入"["
     fs << "image1.jpg" << "onews" << bools.jpg";
     fs << "]";                                       // 结束时,最后输入"]"
    
     // map输入:使用{}分割
     fs << "Mapping";
     fs << "{" << "One" << 1;
     fs <<        "Two" << 2 << "}";
    
     // 而其数据的读取,序列化数据可使用FileNode和FileNodeIterator数据结构。
     FileNode n = fs["strings"];
     if (n.type() != FileNode::SEQ)
     {   cout << "err" << endl;    return 1;  }
     FileNodeIterator it = n.begin(), it_end = n.end();
     for (; it != it_end; ++it)
         cout << (string)*it << endl;
    
     // maps类型数据,可使用[]操作符访问
     n = fs["Mapping"];
     cout << "Two" << (int) (n["Two"] << ";"
     cout << "One" << (int) (n["One"] << endl;
    

- 5)读写自己定义的数据类型。

     // 自己定义类型如下:
     class MyData
     {
      public:
           MyData() : A(0), X(0), id() {}
      public:   // 数据成员
        int A;
        double X;
        string id;
     };

     // 添加内部函数如下:
     // 对自定义类进行写序列化
     void write(FileStorage& fs) const                       
     {
       fs << "{" << "A" << A << "X" << X << "id" << id << "}";
     }

     // 从序列读取自定义类
     void read(const FileNode& node)                          
     {
       A = (int)node["A"];
       X = (double)node["X"];
       id = (string)node["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;
       else
           x.read(node);
     }

     // 读写自己定义的数据结构(如果读写的节点不存在,返回默认值)
     MyData m(1);
     fs << "MyData" << m;                    // 写自定义数据结构
     fs["MyData"] >> m;                      // 读自定义数据结构

***注意***:对自己的数据结构,必须定义类内和类外函数。
  • OpenCV中相关使用程序

    #include <opencv2/core/core.hpp>
    #include <iostream>
    #include <string>
    
    using namespace cv;
    using namespace std;
    
    // 定义自己的数据类型
    class MyData
    {
    public:
        MyData() : A(0), X(0), id()
        {}
        explicit MyData(int) : A(97), X(CV_PI), id("mydata1234") // 显示构造函数,返回隐式转换
        {}
        void write(FileStorage& fs) const                        // 序列化方式写数据
        {
            fs << "{" << "A" << A << "X" << X << "id" << id << "}";
        }
        void read(const FileNode& node)                          // 读取序列化数据
        {
            A = (int)node["A"];
            X = (double)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;
        else
            x.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()
    {
        string filename = "test.xml";
        { 
            // 写操作
            Mat R = Mat_<uchar>::eye(3, 3),
                T = Mat_<double>::zeros(3, 1);
            MyData m(1);
    
            FileStorage fs(filename, FileStorage::WRITE);
    
            fs << "iterationNr" << 100;
            fs << "strings" << "[";                                 // 文本序列开始
            fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
            fs << "]";                                              // 文本序列结束        
    
            fs << "Mapping";                                       
            fs << "{" << "One" << 1;                                // map开始
            fs <<        "Two" << 2 << "}";                         // map结束            
    
            fs << "R" << R;                                         // 写入Mat数据                                    
            fs << "T" << T;
    
            fs << "MyData" << m;                                    // 写自己的数据结构
    
            fs.release();                                           // 显示关闭函数
            cout << "Write Done." << endl;
        }
    
        {
            // 读取数据信息
            cout << endl << "Reading: " << endl;
            FileStorage fs; 
            fs.open(filename, FileStorage::READ);
    
            int itNr; 
            //fs["iterationNr"] >> itNr;
            itNr = (int) fs["iterationNr"];
            cout << itNr;
            if (!fs.isOpened())
            {
                cerr << "Failed to open " << filename << endl;
                return 1;
            }
    
            FileNode n = fs["strings"];                             // 获取读取序列节点
            if (n.type() != FileNode::SEQ)
            {
                cerr << "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"];                                      // 从序列中读取map
            cout << "Two  " << (int)(n["Two"]) << "; "; 
            cout << "One  " << (int)(n["One"]) << endl << endl; 
    
    
            MyData m;
            Mat R, T;
    
            fs["R"] >> R;                                           // 读取Mat数据
            fs["T"] >> T;
            fs["MyData"] >> m;                                      // 读取自己的数据结构
    
            cout << endl 
                << "R = " << R << endl;
            cout << "T = " << T << endl << endl;
            cout << "MyData = " << endl << m << endl << endl;
    
            // 显示默认不存在的节点
            cout << "Attempt to read NonExisting (should initialize the data structure with its default).";  
            fs["NonExisting"] >> 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;
    }
    
  • 参考文献

    http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/core/file_input_output_with_xml_yml/file_input_output_with_xml_yml.html

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值