从yaml文件问题中读取数据 - opencv

时间:2016-03-22 18:23:15

标签: c++ opencv yaml

我有一个.yml文件格式的数据,如下所示:

 %YAML:1.0
 rotMatrix1:
 - !!opencv-matrix
  rows: 3
  cols: 1
  dt: d
  data: [ -2.3829520379560337e-01, -3.7857313177578661e-01, -1.2002438267340013e-01 ]
- !!opencv-matrix
  rows: 3
  cols: 1
  dt: d
  data: [ -1.9532717166408006e-01, -1.9842197713512208e-01, -2.4142492122139054e-02 ]
- !!opencv-matrix
  rows: 3
  cols: 1
  dt: d
  data: [ 7.0848561493555007e-02, -1.5300625945509461e-01, -2.2789227495909796e-03 ]
- !!opencv-matrix
  rows: 3
  cols: 1
  dt: d
  data: [ -6.4432249078642076e-02, 2.6156730119463567e-01, -1.0216960054886982e-01 ]

该文件只包含一个节点名称(rotMatrix1),但在此节点下存储了10个不同的数据。如何使用opencv访问各个1x3矩阵?

我已经尝试过使用cv :: FileNodeIterator,但我注意到了

FileStorage fs(inputData, CV_STORAGE_READ)
FileNode fn= fs["rotMatrix1"];

for(cv::FileNodeIterator it= fn.begin(); it!= fn.end(); ++it)
{
  cv::FileNode node= *it;
  double data= (double)node
}
fs.release();

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码解析文件(完整文件已在评论中链接,并且可用here)。

我建议您按照herehere教程熟悉FileStorageFileNodeFileNodeIterator的概念。

注意我必须复制&将文件内容粘贴到新文件中,因为原始文件存在一些编码问题。

代码:

#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;

int main()
{
    FileStorage fs("calib.yml", FileStorage::READ);

    string time;
    int calibrationImageWidth;
    int calibrationImageHeight;
    int numberOfCrossPointsInWidth;
    int numberOfCrossPointsInHeight;
    double squareSize;
    int numberOfCalibratedImages;
    Mat cameraMatrix1;
    Mat distortionCoefficient1;
    vector<Mat> rotationMatrix1;
    vector<Mat> translationMatrix1;

    // Read data
    FileNode fn_time = fs.root();
    time = fn_time["time"];

    calibrationImageWidth = fs["calibrationImageWidth"];
    calibrationImageHeight = fs["calibrationImageHeight"];
    numberOfCrossPointsInWidth = fs["numberOfCrossPointsInWidth"];
    numberOfCrossPointsInHeight = fs["numberOfCrossPointsInHeight"];
    squareSize = fs["squareSize"];
    numberOfCalibratedImages = fs["numberOfCalibratedImages"];

    fs["cameraMatrix1"] >> cameraMatrix1;
    fs["distortionCoefficient1"] >> distortionCoefficient1;

    FileNode fn_rot = fs["rotationMatrix1"];
    FileNodeIterator fn_rot_it = fn_rot.begin(), fn_rot_it_end = fn_rot.end();
    for (; fn_rot_it != fn_rot_it_end; ++fn_rot_it)
    {
        Mat tmp;
        (*fn_rot_it) >> tmp;

        rotationMatrix1.push_back(tmp.clone());
    }

    FileNode fn_tr = fs["translationMatrix1"];
    FileNodeIterator fn_tr_it = fn_tr.begin(), fn_tr_it_end = fn_tr.end();
    for (; fn_tr_it != fn_tr_it_end; ++fn_tr_it)
    {
        Mat tmp;
        (*fn_tr_it) >> tmp;

        translationMatrix1.push_back(tmp.clone());
    }

    return 0;
}