首页 > 代码库 > OPENCV(3) —— 对XML和YAML文件实现I/O 操作

OPENCV(3) —— 对XML和YAML文件实现I/O 操作

XML\YAML文件在OpenCV中的数据结构为FileStorage

string filename = "I.xml";FileStorage fs(filename, FileStorage::WRITE);\\...fs.open(filename, FileStorage::READ);
fs.release();

 

写入文件使用  <<  运算符 ,读取文件,使用 >> 运算符

fs << "iterationNr" << 100;
int itNr;fs["iterationNr"] >> itNr;itNr = (int) fs["iterationNr"];

 

OpenCV 数据结构的输入和输出

Mat R = Mat_<uchar >::eye (3, 3),T = Mat_<double>::zeros(3, 1);fs << "R" << R; // Write cv::Matfs << "T" << T;fs["R"] >> R; // Read cv::Matfs["T"] >> T;

 

vector要注意在第一个元素前加上“[”,在最后一个元素前加上"]"

fs << "strings" << "["; // text - string sequencefs << "image1.jpg" << "Awesomeness" << "baboon.jpg";fs << "]"; // close sequence

对于map结构的操作使用的符号是"{"和"}"

fs << "Mapping"; // text - mappingfs << "{" << "One" << 1;fs << "Two" << 2 << "}";

 

读取这些结构的时候,会用到FileNode和FileNodeIterator数据结构。对FileStorage类的[]操作符会返回FileNode数据类型,对于一连串的node,可以使用FileNodeIterator结构

FileNode n = fs["strings"]; // Read string sequence - Get nodeif (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 nodefor (; it != it_end; ++it)cout << (string)*it << endl;

 

<?xml version="1.0"?><opencv_storage><depthImg190 type_id="opencv-image"><width>320</width><height>240</height><origin>top-left</origin><layout>interleaved</layout><dt>w</dt><data>0 0 0 0 27120 27384 27120 27120 27384 27120 27120 27120 27120 2738427384 27664 27664 27944 27944 27664 27664 27944 27944 27944 2822427944 27944 28224 28224 28224 28224 28520 28816 29120 29120 2912029120 29120 29120 29120 29432 29744 30072 30072 29744 29744 3007230072 30072 30400 30400 30736 30736 31080 31080 31080 31440 3144031440 31440 31800 31800 31800 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 27120 27120 27120 27120 27384 27384 27384 27384 27384 27384</depthImg190></opencv_storage>

这种格式不能直接使用xml,而需要

IplImage* depth=(IplImage*)cvLoad("depthImg190.xml");

cvLoad 函数

 

const char* filename = "zhang.jpg";    std::ifstream file(filename);    std::vector<char> data;    file >> std::noskipws;    // noskipws 不忽略空白    std::copy(std::istream_iterator<char>(file), std::istream_iterator<char>(), std::back_inserter(data));    cv::Mat matrixJprg = cv::imdecode(cv::Mat(data), 1);    IplImage qImg;    qImg = IplImage(matrixJprg); // cv::Mat -> IplImage 可以直接强制转换    cvSaveImage("./out.jpg", &qImg);

cvSaveImage 直接把 cv::Mat 数据保存为图片会出现问题,需要以上的代码强制转换

OPENCV(3) —— 对XML和YAML文件实现I/O 操作