[7] opencv: C++_cv::FileStorage读写xml配置文件

该代码示例展示了如何使用OpenCV库将图像的宽度、高度以及3x3单位矩阵等数据写入XML文件,并从XML文件中读取这些数据。通过定义XML_TEST宏,程序可以分别执行写入和读取操作。在写入部分,文件存储对象`fs`用于写入width、height、数据矩阵和单位矩阵;在读取部分,同样使用`fs`读取并打印这些数据。
摘要由CSDN通过智能技术生成

小案例:

把数据写入xml文件中,如图像宽高、相机标定参数等等。

如,把width=320,height=380,即1行5列、值为3的Mat,3*3的单位矩阵写入xml,形式如图:在这里插入图片描述

代码:
#include <iostream>
#include "opencv2/opencv.hpp"

using namespace std;

#define XML_TEST

int main() {
#ifdef XML_TEST //写xml
    int width = 320;
    int height = 280;

    cv::Mat r_data = cv::Mat::ones(1, 5, CV_32F) * 3;//set initial value: 3
    cv::Mat r_eye = cv::Mat::eye(3, 3, CV_64F);

    cv::FileStorage fs("./test.xml", cv::FileStorage::WRITE);
    if(fs.isOpened())
    {
        //write data to xml file
        fs << "width" << width << "height" << height <<"m_data" << r_data << "m_eye" << r_eye;
        fs.release();//release after used
    }
#else //从xml读数据
    int width;
    int height;
    cv::Mat r_data, r_eye;
    int i = 0, j = 0;

    cv::FileStorage fs("./test.xml", cv::FileStorage::READ);
    if(fs.isOpened()) {
        //read params from xml
        fs["width"] >> width;
        fs["height"] >> height;
        fs["m_data"] >> r_data;
        fs["m_eye"] >> r_eye;
        
        fs.release();

        cout << "r_data: " << r_data << endl;
        cout << "r_eye: " << endl << r_eye << endl;

        cout << "[";
        for (i = 0; i < r_eye.size().height; i++) {
            for (j = 0; j < r_eye.size().width; j++) {
                cout << r_eye.at<double>(i, j);//read every element value
                if(j != r_eye.size().width - 1){
                    cout << ", ";
                }
                else if(i != r_eye.size().height - 1){
                    cout << ";" << endl;
                } else{
                    cout << "]" << endl;
                }
            }
        }

    }
#endif

    return 0;
}

读取结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值