Hi i tried to write multiple objects to a single XML file using openCV XML/YAML persistence. See example code below.
#include "opencv2/opencv.hpp"
using namespace cv;
struct User_point
{
int x,y;
};
void WritePoint(User_point& pnt,CvFileStorage* fs)
{
cvStartWriteStruct(fs,"User_point",CV_NODE_SEQ);
cvWriteInt(fs,0,pnt.x);
cvWriteInt(fs,0,pnt.y);
cvEndWriteStruct(fs);
}
void main()
{
User_point point;
point.x = 20;
point.y = 20;
CvFileStorage* fs = cvOpenFileStorage("user.xml",0,CV_STORAGE_WRITE);
if(fs)
{
WritePoint(point,fs);
point.x=10;
point.y = 10;
cvStartNextStream(fs);
WritePoint(point,fs);
}
cvReleaseFileStorage( &fs );
return;
}
The resulting xml file looks like this
="1.0"
<opencv_storage>
<User_point>
20 20</User_point>
<User_point>
10 10</User_point>
</opencv_storage>
The problem occurs when openCV tries to parse the file when opening it. The code for reading the xml file is shown below.
#include "opencv2/opencv.hpp"
#include "iostream"
using namespace cv;
using namespace std;
struct User_point
{
int x,y;
};
bool ReadPoint(User_point& pnt,CvFileStorage* fs,CvFileNode* fn=0)
{
CvFileNode* fn2 = cvGetFileNodeByName(fs,fn,"User_point");
if(fn2)
{
pnt.x = cvReadInt((CvFileNode*)cvGetSeqElem(fn2->data.seq,0));
pnt.y = cvReadInt((CvFileNode*)cvGetSeqElem(fn2->data.seq,1));
}
else
return false;
return true;
}
void main()
{
User_point point;
CvFileStorage* fs = cvOpenFileStorage("user.xml",0,CV_STORAGE_READ);
CvFileNode* fn = cvGetRootFileNode(fs,0);
if(fn)
{
ReadPoint(point,fs,fn);
cout<<point.x<<":"<<point.y<<"\n";
}
fn = cvGetRootFileNode(fs,1);
if(fn)
{
ReadPoint(point,fs,fn);
cout<<point.x<<":"<<point.y<<"\n";
}
cvReleaseFileStorage( &fs );
return;
}
The openCV reports an error "Duplicate Key" during parsing. My question is how do i write multiple user defined objects to an xml file using openCV without such an error popping up? I tried nesting them but nesting is limited to a certain number.
Would appreciate any contribution.