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<cv::Mat>& vcameraMatrix, std::vector<cv::Mat>& 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 <opencv2/opencv.hpp>
#include <vector>

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

    //-- Zuo丶    Load Camera YAML
    loadParams("myCamera.yml", vcameraMatrix, vdistCoeffs);
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值