你能存储各种OpenCV数据结构到XML/YAML格式的文件中或者从中恢复数据。也能存储和加载任意的复杂的数据结构,包括OpenCV数据结构,原始的数据类型(整形、浮点数和文本串)。
写数据到XML/YAML文件的步骤:
例子:
#include <opencv2/opencv.hpp> #include <time.h> using namespace cv; int main() { FileStorage fs("test.yaml", FileStorage::WRITE); fs << "frameCount" << 5; time_t rawtime; time(&rawtime); fs << "calibrationDate" << asctime(localtime(&rawtime)); Mat cameraMatrix = (Mat_<double>(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1); Mat distCoeffs = (Mat_<double>(5,1) << 0.1, 0.01, -0.001, 0, 0); fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs; fs << "features" << "["; for( int i = 0; i < 3; i++ ) { int x = rand() % 640; int y = rand() % 480; uchar lbp = rand() % 256; fs << "{:" << "x" << x << "y" << y << "lbp" << "[:"; for( int j = 0; j < 8; j++ ) fs << ((lbp >> j) & 1); fs << "]" << "}"; } fs << "]"; fs.release(); return 0; }
上面这个例子存储数据到yml,整形,文本串(标准时间),2个矩阵,一个包含特征坐标和lbp值的自定义结构“features”。
例子的输出如下:
%YAML:1.0 frameCount: 5 calibrationDate: "Fri Jun 17 14:09:29 2011\n" cameraMatrix: !!opencv-matrix rows: 3 cols: 3 dt: d data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ] distCoeffs: !!opencv-matrix rows: 5 cols: 1 dt: d data: [ 1.0000000000000001e-01, 1.0000000000000000e-02, -1.0000000000000000e-03, 0., 0. ] features: - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] } - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] } - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] }
作为一个练习,你可以使用“.yaml”或者“.xml”替换上面的文件的扩展名。
对于代码和程序的输出,需要注意几点:
opencv_source_code/samples/cpp/filestorage.cpp-是一个完整的例子。
读取先前写入到xml或者yaml文件的数据的步骤:
例子:
#include <opencv2/opencv.hpp> #include <time.h> #include <string> #include <iostream> using namespace cv; using namespace std; int main() { FileStorage fs("test.yaml", FileStorage::READ); int frameCount = (int)fs["frameCount"]; std::string date; fs["calibrationDate"] >> date; Mat cameraMatrix, distCoeffs; fs["cameraMatrix"] >> cameraMatrix; fs["distCoeffs"] >> distCoeffs; cout << "frameCount: " << frameCount << endl; cout << "calibrationDate: " << date << endl; cout << "cameraMatrix: " << cameraMatrix << endl; cout << "distCoeffs: " << distCoeffs << endl; FileNode features = fs["features"]; FileNodeIterator it = features.begin(), it_end = features.end(); int idx = 0; std::vector<uchar> lbpval; for (; it != it_end; ++it, ++idx) { cout << "feature #" << idx << ": "; cout << "x=" << (int)(*it)["x"] << ",, y=" << (int)(*it)["y"] << ", lbp: ("; (*it)["lbp"] >> lbpval; for(int i = 0; i < (int)lbpval.size(); ++i) { cout << " " << (int)lbpval[i]; } cout << ")" << endl; } fs.release(); return 0; }