Opencv 例程講解8 ----如何實現Mat以及自定義類型的讀寫操作

   今天學習一下Opencv中一個用處很廣泛的功能,xml/yml 格式文件的輸入和輸出,這在特徵,算法參數等數據類型的保存和載入中肯定需要用到,掌握opencv中文件的輸入輸出類,會使這一個過程十分簡單愉快。當然文件的輸入輸出功能用處很廣,有待大家去挖掘。對應的例程是 (TUTORIAL) file_input_output

先來看下程序的運行結果,這裏我們設置的xml輸出路徑爲 f:\image_set\test.xml

可以看出,例程先將數據寫入到文件中,然後再從文件中讀出數據,並打印出來。下面具體看下是怎麼操作的。

    { //write
        Mat R = Mat_<uchar>::eye(3, 3),
            T = Mat_<double>::zeros(3, 1);
        MyData m(1);

        FileStorage fs(filename, FileStorage::WRITE);   // 構造一個 FileStorage對象,只提供寫操作

        fs << "iterationNr" << 100;                       
        fs << "strings" << "[";                              // text - string sequence    // 用 [ ] 作爲字符串的輸入開始和結束標記
        fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
        fs << "]";                                           // close sequence

        fs << "Mapping";                              // text - mapping                     // 用 { }作爲map 索引的輸入開始和結束標記
        fs << "{" << "One" << 1;
        fs <<        "Two" << 2 << "}";

        fs << "R" << R;                                      // cv::Mat                         // 輸出Mat,“R”作爲Mat的名稱
        fs << "T" << T;

        fs << "MyData" << m;                                // your own data structures    // 輸出自定義類型 , 需要自己編寫函數重載

        fs.release();                                       // explicit close                                // 寫完後,要釋放文件資源
        cout << "Write Done." << endl;
    }
Opencv中用一個類 FileStorage 提供文件輸入輸出的方法,下面是例程中用到的構造函數原型

    //! the full constructor that opens file storage for reading or writing
    CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string());
可以看出,利用這個構造函數,需要提供兩個參數

1. 文件路徑,類型爲string

2. flag參數,用來決定對象的存儲模式,包括一下幾種模式

    //! file storage mode
    enum
    {
        READ=0, //! read mode
        WRITE=1, //! write mode
        APPEND=2, //! append mode
        MEMORY=4,
        FORMAT_MASK=(7<<3),
        FORMAT_AUTO=0,
        FORMAT_XML=(1<<3),
        FORMAT_YAML=(2<<3)
    };
打開xml,可以看到寫入文件的數據,如下圖所示

<?xml version="1.0"?>
<opencv_storage>
<iterationNr>100</iterationNr>
<strings>
  image1.jpg Awesomeness baboon.jpg</strings>
<Mapping>
  <One>1</One>
  <Two>2</Two></Mapping>
<R type_id="opencv-matrix">
  <rows>3</rows>
  <cols>3</cols>
  <dt>u</dt>
  <data>
    1 0 0 0 1 0 0 0 1</data></R>
<T type_id="opencv-matrix">
  <rows>3</rows>
  <cols>1</cols>
  <dt>d</dt>
  <data>
    0. 0. 0.</data></T>
<MyData>
  <A>97</A>
  <X>3.1415926535897931e+000</X>
  <id>mydata1234</id></MyData>
</opencv_storage>
我們在回頭看下如何利用FileStorage 讀寫自定義類型,源碼如下

class MyData
{
public:
    MyData() : A(0), X(0), id()
    {}
    explicit MyData(int) : A(97), X(CV_PI), id("mydata1234") // explicit to avoid implicit conversion
    {}
    void write(FileStorage& fs) const                        //Write serialization for this class
    {
        fs << "{" << "A" << A << "X" << X << "id" << id << "}";
    }
    void read(const FileNode& node)                          //Read serialization for this class
    {
        A = (int)node["A"];
        X = (double)node["X"];
        id = (string)node["id"];
    }
public:   // Data Members
    int A;
    double X;
    string id;
};

//These write and read functions must be defined for the serialization in FileStorage to work
static void write(FileStorage& fs, const std::string&, const MyData& x)
{
    x.write(fs);
}
static void read(const FileNode& node, MyData& x, const MyData& default_value = MyData()){
    if(node.empty())
        x = default_value;
    else
        x.read(node);
}

// This function will print our custom class to the console
static ostream& operator<<(ostream& out, const MyData& m)
{
    out << "{ id = " << m.id << ", ";
    out << "X = " << m.X << ", ";
    out << "A = " << m.A << "}";
    return out;
}
可以看出,這是一個簡單的類型,包括int,double和string類型的三個成員變量,在自定義類型中定義了read 和write的方法,值得注意的是這裏另外定義了3個靜態函數,write,read 以及<<操作,它們是起橋樑作用的,提供一個接口,可以將fs類的<<操作轉換成各種類型各自的write和read方法。看FileStorage中定義的<<操作會根據清楚

template<typename _Tp> static inline FileStorage& operator << (FileStorage& fs, const _Tp& value)
{
    if( !fs.isOpened() )
        return fs;
    if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP )
        CV_Error( CV_StsError, "No element name has been given" );
    write( fs, fs.elname, value );
    if( fs.state & FileStorage::INSIDE_MAP )
        fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP;
    return fs;
}

這是一個模板函數,通過一個重載函數write實現不同類型的寫操作,而這個write函數只是提供一個接口,具體的文件寫入操作,在各種類型中有分別的實現。同理,FileStorage 的read也是利用類似的技巧實現的。這樣做的目的也是爲了提供代碼的重載性和擴展性,這樣FileStorage就可以爲任意的自定義類型提供接口,實現在各自的類型中實現,但用戶新添加一種類型時,不需要改動FileStorage中的任何代碼,這是個很高明的技巧。

下面看下FileStorage 的read操作

    {//read
        cout << endl << "Reading: " << endl;
        FileStorage fs;
        fs.open(filename, FileStorage::READ);  構造一個FileStorage,只提供讀操作

        int itNr;
        //fs["iterationNr"] >> itNr;
        itNr = (int) fs["iterationNr"];              //利用[ ]查找iterationNr的值
        cout << itNr;
        if (!fs.isOpened())
        {
            cerr << "Failed to open " << filename << endl;
            help(av);
            return 1;
        }

        FileNode n = fs["strings"];                         // Read string sequence - Get node  // 尋找名爲 strings的節點
        if (n.type() != FileNode::SEQ)                                                                               // 判斷節點的值類型  FileNode::SEQ代表字符串類型
        {
            cerr << "strings is not a sequence! FAIL" << endl;
            return 1;
        }

        FileNodeIterator it = n.begin(), it_end = n.end(); // Go through the node     // 遍歷節點,輸出所有字符串,迭代的風格
        for (; it != it_end; ++it)
            cout << (string)*it << endl;


        n = fs["Mapping"];                                // Read mappings from a sequence
        cout << "Two  " << (int)(n["Two"]) << "; ";                                                     // 查找"Two"的值
        cout << "One  " << (int)(n["One"]) << endl << endl;


        MyData m;
        Mat R, T;

        fs["R"] >> R;                                      // Read cv::Mat   // 查找到“R”的Mat,並讀入到 R中
        fs["T"] >> T;
        fs["MyData"] >> m;                                 // Read your own structure_    自定義類型的讀取

        cout << endl
            << "R = " << R << endl;
        cout << "T = " << T << endl << endl;
        cout << "MyData = " << endl << m << endl << endl;

        //Show default behavior for non existing nodes
        cout << "Attempt to read NonExisting (should initialize the data structure with its default).";
        fs["NonExisting"] >> m;
        cout << endl << "NonExisting = " << endl << m << endl;
    }
讀入的操作和寫入很類似,FileStorage提供[ ]下標直接查找某個名字的數據或者節點,FileStorage::SEQ類型的節點,可以通過迭代進行字符串的遍歷。

同樣的,自定義類型的讀入操作需要自己定義。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章