您的位置:首页 > 运维架构

Opencv 例程讲解8 ----如何实现Mat以及自定义类型的读写操作

2014-01-22 14:29 711 查看
今天学习一下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类型的节点,可以通过迭代进行字符串的遍历。

同样的,自定义类型的读入操作需要自己定义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐