OpenCV文件輸入和輸出使用XML和YAML文件

2018-08-30 11:45 更新

目標(biāo)

您會(huì)找到以下問(wèn)題的答案:

  • 如何使用YAML或XML文件打印和讀取文本和OpenCV文本條目?
  • OpenCV數(shù)據(jù)結(jié)構(gòu)如何做同樣的操作?
  • 如何為您的數(shù)據(jù)結(jié)構(gòu)做這個(gè)?
  • OpenCV數(shù)據(jù)結(jié)構(gòu)的使用,如cv :: FileStorage,cv :: FileNodecv :: FileNodeIterator。

源代碼

您可以從這里下載,也可以在samples/cpp/tutorial_code/core/file_input_output/file_input_output.cppOpenCV源代碼庫(kù)中找到它。

以下是如何實(shí)現(xiàn)目標(biāo)列表中枚舉的所有內(nèi)容的示例代碼。

#include <opencv2/core.hpp>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
static void help(char** av)
{
    cout << endl
        << av[0] << " shows the usage of the OpenCV serialization functionality."         << endl
        << "usage: "                                                                      << endl
        <<  av[0] << " outputfile.yml.gz"                                                 << endl
        << "The output file may be either XML (xml) or YAML (yml/yaml). You can even compress it by "
        << "specifying this in its extension like xml.gz yaml.gz etc... "                  << endl
        << "With FileStorage you can serialize objects in OpenCV by using the << and >> operators" << endl
        << "For example: - create a class and have it serialized"                         << endl
        << "             - use it to read and write matrices."                            << endl;
}
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 main(int ac, char** av)
{
    if (ac != 2)
    {
        help(av);
        return 1;
    }
    string filename = av[1];
    { //write
        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" << "[";                              // text - string sequence
        fs << "image1.jpg" << "Awesomeness" << "../data/baboon.jpg";
        fs << "]";                                           // close sequence
        fs << "Mapping";                              // text - mapping
        fs << "{" << "One" << 1;
        fs <<        "Two" << 2 << "}";
        fs << "R" << R;                                      // cv::Mat
        fs << "T" << T;
        fs << "MyData" << m;                                // your own data structures
        fs.release();                                       // explicit close
        cout << "Write Done." << endl;
    }
    {//read
        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;
            help(av);
            return 1;
        }
        FileNode n = fs["strings"];                         // Read string sequence - Get node
        if (n.type() != 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"]) << "; ";
        cout << "One  " << (int)(n["One"]) << endl << endl;
        MyData m;
        Mat R, T;
        fs["R"] >> R;                                      // Read cv::Mat
        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;
    }
    cout << endl
        << "Tip: Open up " << filename << " with a text editor to see the serialized data." << endl;
    return 0;
}

說(shuō)明

這里我們僅談?wù)揦ML和YAML文件輸入。您的輸出(及其相應(yīng)的輸入)文件可能只有這些擴(kuò)展中的一個(gè)和結(jié)構(gòu)來(lái)自此。它們是可以序列化的兩種數(shù)據(jù)結(jié)構(gòu):映射(如STL映射)和元素序列(如STL向量)。這些之間的區(qū)別是,在地圖中,每個(gè)元素都有一個(gè)唯一的名稱(chēng),通過(guò)您可以訪(fǎng)問(wèn)它。對(duì)于序列,您需要通過(guò)它們查詢(xún)特定項(xiàng)目。

  • XML / YAML文件打開(kāi)和關(guān)閉。在將任何內(nèi)容寫(xiě)入此類(lèi)文件之前,您需要將其打開(kāi)并結(jié)束關(guān)閉。OpenCV中的XML / YAML數(shù)據(jù)結(jié)構(gòu)是cv :: FileStorage。要指定文件在硬盤(pán)驅(qū)動(dòng)器上綁定的結(jié)構(gòu),您可以使用其構(gòu)造函數(shù)或open()函數(shù):
string filename = "I.xml";
FileStorage fs(filename, FileStorage::WRITE);
//...
fs.open(filename, FileStorage::READ);

您使用第二個(gè)參數(shù)中的任何一個(gè)是一個(gè)常數(shù),指定您可以在其上執(zhí)行的操作類(lèi)型:WRITE,READ或APPEND。文件名中指定的擴(kuò)展名也可以確定要使用的輸出格式。如果指定擴(kuò)展名,例如* .xml.gz *,輸出可能會(huì)被壓縮。

當(dāng)cv :: FileStorage對(duì)象被銷(xiāo)毀時(shí),文件會(huì)自動(dòng)關(guān)閉。但是,您可以使用發(fā)布功能顯式地調(diào)用此功能:

fs.release();                                       // explicit close
  • 文本和數(shù)字的輸入和輸出。數(shù)據(jù)結(jié)構(gòu)使用與STL庫(kù)相同的<<輸出運(yùn)算符。為了輸出任何類(lèi)型的數(shù)據(jù)結(jié)構(gòu),我們首先需要指定其名稱(chēng)。我們只需打印出這個(gè)名稱(chēng)即可。對(duì)于基本類(lèi)型,您可以使用值的打印符號(hào):
fs << “iterationNr” << 100;

讀入是一個(gè)簡(jiǎn)單的尋址(通過(guò)[]操作符)和轉(zhuǎn)換操作或通過(guò)>>操作符讀取:

int itNr;
fs["iterationNr"] >> itNr;
itNr = (int) fs["iterationNr"];

  • OpenCV數(shù)據(jù)結(jié)構(gòu)的輸入/輸出。那么這些行為就像基本的C ++類(lèi)型一樣:

Mat R = Mat_<uchar >::eye  (3, 3),
    T = Mat_<double>::zeros(3, 1);
fs << "R" << R;                                      // Write cv::Mat
fs << "T" << T;
fs["R"] >> R;                                      // Read cv::Mat
fs["T"] >> T;

  • 向量(數(shù)組)和關(guān)聯(lián)圖的輸入/輸出。如前所述,我們可以輸出地圖和序列(數(shù)組,向量)。再次,我們首先打印變量的名稱(chēng),然后我們必須指定我們的輸出是序列還是地圖。
對(duì)于第一個(gè)元素之前的序列打印“[”字符,最后一個(gè)“]”字符后:

fs << "strings" << "[";                              // text - string sequence
fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
fs << "]";                                           // close sequence

對(duì)于地圖,鉆頭是一樣的,現(xiàn)在我們使用“{”和“}”分隔符:

fs << "Mapping";                              // text - mapping
fs << "{" << "One" << 1;
fs <<        "Two" << 2 << "}";

要讀取這些,我們使用cv :: FileNodecv :: FileNodeIterator數(shù)據(jù)結(jié)構(gòu)。cv :: FileStorage類(lèi)的[]運(yùn)算符返回一個(gè)cv :: FileNode數(shù)據(jù)類(lèi)型。如果節(jié)點(diǎn)是順序的,我們可以使用cv :: FileNodeIterator遍歷項(xiàng)目:

FileNode n = fs["strings"];                         // Read string sequence - Get node
if (n.type() != 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;

對(duì)于地圖,您可以再次使用[]運(yùn)算符來(lái)訪(fǎng)問(wèn)給定項(xiàng)目(或>>運(yùn)算符):

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

  • 讀寫(xiě)自己的數(shù)據(jù)結(jié)構(gòu)。假設(shè)你有一個(gè)數(shù)據(jù)結(jié)構(gòu),如:

class MyData
{
public:
      MyData() : A(0), X(0), id() {}
public:   // Data Members
   int A;
   double X;
   string id;
};

通過(guò)OpenCV I / O XML / YAML接口(就像OpenCV數(shù)據(jù)結(jié)構(gòu)一樣),可以通過(guò)在類(lèi)中添加一個(gè)讀取和寫(xiě)入函數(shù)來(lái)對(duì)其進(jìn)行序列化。對(duì)于內(nèi)部:

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"];
}

那么你需要在類(lèi)之外添加以下函數(shù)定義:

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);
}

在這里您可以看到,在閱讀部分中,我們定義了如果用戶(hù)嘗試讀取不存在的節(jié)點(diǎn)會(huì)發(fā)生什么。在這種情況下,我們只返回默認(rèn)的初始化值,但是更詳細(xì)的解決方案是返回一個(gè)對(duì)象ID的減號(hào)值。

一旦添加了這四個(gè)函數(shù),就可以使用>>操作符進(jìn)行寫(xiě)操作,而<<操作符用于讀取:

MyData m(1);
fs << "MyData" << m;                                // your own data structures
fs["MyData"] >> m;                                 // Read your own structure_

或嘗試閱讀一個(gè)不存在的閱讀:

fs["NonExisting"] >> m;   // Do not add a fs << "NonExisting" << m command for this to work
cout << endl << "NonExisting = " << endl << m << endl;

結(jié)果

主要是我們打印出定義的數(shù)字。您可以在控制臺(tái)的屏幕上看到:

Write Done.
Reading:
100image1.jpg
Awesomeness
baboon.jpg
Two  2; One  1
R = [1, 0, 0;
  0, 1, 0;
  0, 0, 1]
T = [0; 0; 0]
MyData =
{ id = mydata1234, X = 3.14159, A = 97}
Attempt to read NonExisting (should initialize the data structure with its default).
NonExisting =
{ id = , X = 0, A = 0}
Tip: Open up output.xml with a text editor to see the serialized data.

不過(guò),輸出xml文件中可能會(huì)看到的更有趣:

<?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>

或YAML文件:

%YAML:1.0
iterationNr: 100
strings:
   - "image1.jpg"
   - Awesomeness
   - "baboon.jpg"
Mapping:
   One: 1
   Two: 2
R: !!opencv-matrix
   rows: 3
   cols: 3
   dt: u
   data: [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]
T: !!opencv-matrix
   rows: 3
   cols: 1
   dt: d
   data: [ 0., 0., 0. ]
MyData:
   A: 97
   X: 3.1415926535897931e+000
   id: mydata1234
以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)