1 目标
(1)在OpenCV中怎样使用XML和YAML文件打印和输出文本
(2)怎样对OpenCV数据结构进行输入和输出
(3)自定义数据结构怎样操作
(4)OpenCV数据结构,诸如FileStorage,FileNode或FileNodeIterator的使用。
2 源代码
#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"];
}
// Data Members
public:
int A;
double X;
string id;
};
// 这些读写函数必须用FileStorage定义读写序列化
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);
}
// 实现用户自定义类打印到控制台
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" << "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;
}
3 解释
在这里,我们只讨论XML和YAML文件的输入。它们有两类你可以序列化的数据结构:映射(像STL map)和元素序列(像STL vector)。它们的不同在于,对于映射map,每一个元素都有唯一的名称,你可以通过它访问。对于序列,你需要遍历才能访问指定的一个。
(1)XML/YAML文件的打开和关闭。
同所有的文件读写一样。首先,你必须先打开文件;末尾,还要关闭文件。OpenCV有专门的控制这类文件的类FileStorage。使用其open()函数或者构造函数打开你硬件驱动上对应的文件。
string filename = "I.xml";
FileStorage fs(filename,FileStorage::WRITE);
\\...
fs.open(filename,FileStorage::READ);
上面的两种方法,同普通文件的读写控制没有什么大的区别。第二个参数指定对文件的操作类型:读,写和附加。文件名中的扩展格式决定了输出格式。如果使用诸如.xml.gz的扩展格式,那么输出就会被压缩。
当FileStorage对象被销毁时,文件会自动关闭。当然了,你也可以显式地调用release函数进行释放:
fs.release(); // 显式地关闭
(2)文本和数字的输入输出。
该数据结构使用和STL标准模板库相同的”<<”输出操作符。为了输出任何类型的数据结构,我们首先需要指定它的名称。在这里,我们只需简单的打印输出它的名称就可以了。对于基本的数据类型,只需按照下面的格式输出就OK:
fs << "iterationNr" << 100;
读取:通过[]操作符,访问其地址;然后通过>>操作符或者转换操作,得到想要的值。
int itNr;
fs["iterationNr"] >> itNr;
itNr = (int) fs["iterationNr"];
(3)OpenCV数据结构的输入输出。
行为类似基本的C++类型:
Mat R = Mat_<uchar >::eye (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;
(4)矢量 (数组) 和 关联映射的输入输出:
正如我们事先提到的,我们当然也能输出映射和序列(矢量,数组)。首先,我们打印变量的名称,然后我们必须指定我们的输出是序列还是映射。
对于序列,第一个元素之前打印“[“,以“]“字符结束:
fs << "strings" << "["; // 字符串序列
fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
fs << "]"; // 关闭序列
对于映射是一样的,只是用“{“,“}“指定而已:
fs << "Mapping"; // 映射
fs << "{" << "One" << 1;
fs << "Two" << 2 << "}";
当需要读取时,我们使用 FileNode 和 FileNodeIterator 数据结构进行操作。类FileStorage 的操作符[] 返回FileNode数据类型。如果是序列,可以使用 FileNodeIterator 去迭代所有的项:
// 读字符串序列 - 首先获取节点
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"]; // 从一个序列中读取映射
cout << "Two " << (int)(n["Two"]) << "; ";
cout << "One " << (int)(n["One"]) << endl << endl;
class MyData
{
public:
MyData() : A(0),X(0),id() {}
public: // Data Members
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 MyData& x)
{
x.write(fs);
}
void read(const FileNode& node,const MyData& default_value = MyData())
{
if(node.empty())
x = default_value;
else
x.read(node);
}
具体实例:
MyData m(1);
fs << "MyData" << m; // your own data structures
fs["MyData"] >> m; // Read your own structure_
或者尝试读取不存在的节点:
fs["NonExisting"] >> m;
// Do not add a fs << "NonExisting" << m command for this to work
cout << endl << "NonExisting = " << endl << m << endl;
4 结果
执行程序,看到如下输出:
Write Done.
Reading:
100image1.jpg
Awesomeness
baboon.jpg
Two 2; One 1
R = [1,0,0;
0,1,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.
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>
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,1,1 ]
T: !!opencv-matrix
rows: 3
cols: 1
dt: d
data: [ 0.,0.,0. ]
MyData:
A: 97
X: 3.1415926535897931e+000
id: mydata1234