c++ opencv读/写yaml文件(相机参数,外参矩阵等)
参考博文:"OpenCV —数据持久化: FileStorage类的数据存取操作与示例"
https://blog.****.net/iracer/article/details/51339377
注意:使用FileStorage的前提是yaml文件必须遵循以下格式:%YAML:1.0
fx: 100.
fy: 101.
否则无法使用,会提示找不到输入文件
使用FileStorage读取yaml存储的外参矩阵:
写入操作:
cv::FileStorage fs("test.yml", FileStorage::WRITE);
int imageWidth= 5;
int imageHeight= 10;
fs << "imageWidth" << imageWidth;
fs << "imageHeight" << imageHeight;
cv::Mat m1= Mat::eye(3,3, CV_8U);
cv::Mat m2= Mat::ones(3,3, CV_8U);
cv::Mat resultMat= (m1+1).mul(m1+2);
fs << "resultMat" << resultMat;
cv::Mat cameraMatrix = (Mat_<double>(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
cv::Mat distCoeffs = (Mat_<double>(5,1) << 0.1, 0.01, -0.001, 0, 0);
fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs;
time_t rawtime; time(&rawtime); //#include <time.h>
fs << "calibrationDate" << asctime(localtime(&rawtime));
fs.release(); //close the file opened
打开文件的两种方式:
1. cv::FileStorage fs;
fs.open("test.yml",FileStorage::WRITE);
......
fs.release()
2.cv::FileStorage fs("test.yml", FileStorage::WRITE);
读取操作
// read data using operator []
cv::FileStorage fs("test.yml", FileStorage::READ);
int width;
int height;
fs["imageWidth"]>>width;
fs["imageHeight"]>>height;
cout<<"width readed = "<<width<<endl;
cout<<"height readed = "<<height<<endl<<endl;
// read Mat
cv::Mat resultMatRead;
fs["resultMat"]>>resultMatRead;
cout<<"resultMat readed = "<<resultMatRead<<endl<<endl;
cv::Mat cameraMatrixRead,distCoeffsRead;
fs["cameraMatrix"]>>cameraMatrixRead;
fs["distCoeffs"]>>distCoeffsRead;
cout<<"cameraMatrix readed = "<<cameraMatrixRead<<endl;
cout<<"distCoeffs readed = "<<distCoeffsRead<<endl<<endl;
// read string
string timeRead;
fs["calibrationDate"]>>timeRead;
cout<<"calibrationDate readed = "<<timeRead<<endl<<endl;
fs.release();