数据在XML / YAML文件的保存/载入

 //保存数据
#include <cv.h> 
  
using namespace std; 
  
int
main (int argc, char **argv) 
{ 
  char filename[] = "save_cv.xml";  // file name 
  
  // (1)create sample data 
  int a = 10; 
  float b = 0.1; 
  
  cv::Mat mat[3]; 
  for(int i=0; i<3; i++){ 
    mat[i].create(3,3,CV_32FC1); 
    mat[i].setTo(cv::Scalar(i)); 
  } 
  
  // (2)open file storage 
  cv::FileStorage   cvfs(filename,CV_STORAGE_WRITE); 
  
  // (3)write data to file 
  cv::write(cvfs,"a",a); 
  cv::write(cvfs,"b",b); 
  cv::WriteStructContext ws(cvfs, "mat_array", CV_NODE_SEQ);    // create node 
  for(int i=0; i<3; i++){ 
    cv::write(cvfs,"",mat[i]); 
  } 
  
  return 0; 
}

 

保存在save_cv.xml的内容为

  <?xml version="1.0" ?> 
- <opencv_storage>
  <a>10</a> 
  <b>1.0000000149011612e-001</b> 
- <mat_array>
- <_ type_id="opencv-matrix">
  <rows>3</rows> 
  <cols>3</cols> 
  <dt>f</dt> 
  <data>0. 0. 0. 0. 0. 0. 0. 0. 0.</data> 
  </_>
- <_ type_id="opencv-matrix">
  <rows>3</rows> 
  <cols>3</cols> 
  <dt>f</dt> 
  <data>1. 1. 1. 1. 1. 1. 1. 1. 1.</data> 
  </_>
- <_ type_id="opencv-matrix">
  <rows>3</rows> 
  <cols>3</cols> 
  <dt>f</dt> 
  <data>2. 2. 2. 2. 2. 2. 2. 2. 2.</data> 
  </_>
  </mat_array>
  </opencv_storage>


 


//读取数据

#include "stdafx.h"
#include <iostream>
#include <opencv2/core/core.hpp>

using namespace cv;
using namespace std; 
  
  
int main (int argc, char **argv) 
{ 
  char filename[] = "save_cv.xml";  // file name 
  int i,j,k; 
  
  // (1)memory space for loading data 
  int a; 
  float b; 
  cv::Mat mat[3]; 
  
  // (2)open file storage 
  cv::FileStorage cvfs(filename,CV_STORAGE_READ); 
  
  // (3)read data from file storage 
  cv::FileNode node(cvfs.fs, NULL); // Get Top Node 
  a = node["a"]; 
  b = node["b"]; 
  cv::FileNode fn = node[string("mat_array")]; 
      
  for(i=0;i<fn.size();i++){ 
    cv::read(fn[i], mat[i]); 
  } 
  
  // (4)print loaded data 
  cout << "a:" << a << endl; 
  cout << "b:" << b << endl; 
  
  for(i=0; i<3; i++){ 
    cout << "mat" << i << ":" << endl; 
    for(j=0;j<mat[i].rows;j++){ 
      for(k=0;k<mat[i].cols;k++){ 
    cout << mat[i].at<float>(j,k) << ","; 
      } 
      cout << endl; 
    } 
  } 
  
  return 0; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值