In this tutorial we go to show how to save our custom structures with opencv functions.
We go to imagine we have this structure in our program.
[c language="++"]typedef struct
unsigned char var2;
Opencv can save data in two formats: XML or YAML. This formats are markup languages.
For write or read a file, we go to use cvOpenFileStorage function, the functions returns a CvFileStorage structure pointer. This pointer we use to read or write values into.
We can open a file in two ways: for read or write. The function to open file is cvOpenFileStorage
[c language="++"]CvFileStorage* storage = cvOpenFileStorage( file, 0, CV_STORAGE_WRITE_TEXT );[/c]
One time we have our CvFileStorage initialized then we can save our data. To save the data we need create Nodes. XML and YAML are markup languages, and they are defined with nodes.
First we go to create one node that contains all structure data. And inside of this node we need create one node for each variable.
For create a node we need open and close this node, as we do with xml, then we use cvStartWriteStruct and cvEndWriteStruct.
[c language="++"]cvStartWriteStruct(storage, "MyStructure", CV_NODE_MAP, NULL, cvAttrList(0,0));
Between the start and end node we go to insert each new node with asigned variable. The variable we must save as some of this types: int, raw (array), real or string with this functions:
Then for save our structure we go to create this code:
CvFileStorage* storage = cvOpenFileStorage( file, 0, CV_STORAGE_WRITE_TEXT );
//Create our node for structure
cvStartWriteStruct(storage, "MyStructure", CV_NODE_MAP, NULL, cvAttrList(0,0));
//Write our float
cvWriteReal( storage, "var1", MyStructure->var1 );
//Write our array
cvStartWriteStruct(storage, "var2", CV_NODE_SEQ, NULL, cvAttrList(0,0));
//End node structure
About David Millán Escrivá
David completed his studies in Universidad Politecnica de Valencia in IT with a Master's degree in artificial intelligence, computer graphics, and pattern recognition, focusing on pattern recognition and Computer Vision. David has more than 15 years of experience in IT, with more than ten years of experience in Computer Vision, computer graphics, and pattern recognition, working on different projects and start-ups, applying his knowledge of Computer Vision, optical character recognition, and augmented reality. Co-Author of two OpenCV books and reviewer of few more.