OpenCV中读取YAML文件方法

  在CV处理中,一般要用到一个甚至多个相机参数,所谓的相机参数,也就是指相机外参、内参、畸变参数等,它们一般以矩阵的形式存在,如果都写在代码里面,一来显得臃肿拖沓,二来也不方便修改参数,OpenCV提供了YAML文件扩展配置的功能,也就是FileStorage类,下面用一段代码展示它的基本用法。

下面这个名为myCamera.yml的YAML文件中按顺序存储了四个相机的内参和畸变参数:

%YAML:1.0
calibrateTime: "2017年09月07日 Zuo丶\n"
n_camera: 4
cam_0_matrix: !!opencv-matrix
   rows: 3
   cols: 3
   dt: d
   data: [ 4.0601703e+02, 0., 3.195e+02, 0.,
       4.0508811e+02, 2.395e+02, 0., 0., 1. ]
cam_0_distcoeffs: !!opencv-matrix
   rows: 5
   cols: 1
   dt: d
   data: [ -3.3078e-01, 9.913e-02, 2.31e-03, -1.49e-03,
       0 ]
cam_1_matrix: !!opencv-matrix
   rows: 3
   cols: 3
   dt: d
   data: [ 4.0601703e+02, 0., 3.195e+02, 0.,
       4.0508811e+02, 2.395e+02, 0., 0., 1. ]
cam_1_distcoeffs: !!opencv-matrix
   rows: 5
   cols: 1
   dt: d
   data: [ -3.3078e-01, 9.913e-02, 2.31e-03, -1.49e-03,
       0 ]
cam_2_matrix: !!opencv-matrix
   rows: 3
   cols: 3
   dt: d
   data: [ 4.0601703e+02, 0., 3.195e+02, 0.,
       4.0508811e+02, 2.395e+02, 0., 0., 1. ]
cam_2_distcoeffs: !!opencv-matrix
   rows: 5
   cols: 1
   dt: d
   data: [ -3.3078e-01, 9.913e-02, 2.31e-03, -1.49e-03,
       0 ]
cam_3_matrix: !!opencv-matrix
   rows: 3
   cols: 3
   dt: d
   data: [ 4.0601703e+02, 0., 3.195e+02, 0.,
       4.0508811e+02, 2.395e+02, 0., 0., 1. ]
cam_3_distcoeffs: !!opencv-matrix
   rows: 5
   cols: 1
   dt: d
   data: [ -3.3078e-01, 9.913e-02, 2.31e-03, -1.49e-03,
       0 ]              

接下来用下面的loadParams函数去读取上面的YAML文件。

bool loadParams(std::string filename, std::vector& vcameraMatrix, std::vector& vdistCoeffs)
{
    fprintf(stderr, "loadParams.\n");
    cv::FileStorage fs(filename, cv::FileStorage::READ);
    if (!fs.isOpened()) {
        fprintf(stderr, "%s:%d:loadParams falied. 'camera.yml' does not exist\n", __FILE__, __LINE__);
        return false;
    }

    int n_camera = (int)fs["n_camera"];
    vcameraMatrix.resize(n_camera);
    vdistCoeffs.resize(n_camera);
    for (int i = 0; i < n_camera; i++) {
        char buf1[100];
        sprintf(buf1, "cam_%d_matrix", i);
        char buf2[100];
        sprintf(buf2, "cam_%d_distcoeffs", i);
        fs[buf1] >> vcameraMatrix[i];
        fs[buf2] >> vdistCoeffs[i];
    }
    fs.release();

    return true;
}

main.cpp

#include 
#include 

int main(int argc, char* argv[])
{
    std::vector vcameraMatrix;
    std::vector vdistCoeffs;

    //-- Zuo丶    Load Camera YAML
    loadParams("myCamera.yml", vcameraMatrix, vdistCoeffs);
}

你可能感兴趣的:(CV)