【OpenCV学习】XML的读写

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

 

#include "highgui.h"
#include "cv.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main(void)
{
    int a=1;
    float b=2.;
    double c[]={4.5,6.7,8.9};
    CvMat *mat=cvCreateMat(3,3,CV_32SC1);
    cvSetIdentity(mat);//初始化这个矩阵
    CvFileStorage *fs=cvOpenFileStorage("test.xml",0,CV_STORAGE_WRITE);
    cvWriteComment(fs,"my data",1);
    //开始写数据
    cvStartWriteStruct(fs,"DATA",CV_NODE_MAP,0,cvAttrList(0,0));
   
    //写入数据c数组
    cvStartWriteStruct(fs,"c",CV_NODE_SEQ,0,cvAttrList(0,0));
    cvWriteRawData(fs,c,3,"d");
    cvEndWriteStruct(fs);
    //写入单位矩阵mat
    cvSave("mat.xml",mat);
    //写入整型数据a
    cvWriteInt(fs,"a",a);
    //写入浮点型数据b
    cvWriteReal(fs,"b",b);
    cvStartWriteStruct(fs,"c",CV_NODE_SEQ,0,cvAttrList(0,0));
    cvWriteRawData(fs,c,3,"d");
    cvEndWriteStruct(fs);
    cvEndWriteStruct(fs);
    cvReleaseFileStorage(&fs);
    cvReleaseMat(&mat);
/**********读取XML***********/
    int i,j;
    CvMat *readbyname,*readbynode;
    CvFileNode *mat_node;//文件结点
    CvFileStorage *fs_read=NULL;//文件存储
    fs_read=cvOpenFileStorage("mat.xml",0,CV_STORAGE_READ);
    readbyname = (CvMat *)cvReadByName(fs_read,NULL,"mat",NULL);
    mat_node = cvGetFileNodeByName(fs_read,NULL,"mat");
    readbynode = (CvMat *)cvRead(fs_read,mat_node);
    for (i=0;i<3;i++)
    {
        for (j=0;j<3;j++)
        {
            cout<<CV_MAT_ELEM(*readbynode,int,i,j);
        }
        cout<<endl;
    }
    cvReleaseFileStorage(&fs_read);
    cvReleaseMat(&readbynode);
    cvReleaseMat(&readbyname);
   
    return 0;
}

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

posted @ 2012-10-08 22:33  gnuhpc  阅读(5635)  评论(2编辑  收藏  举报