Ask Your Question
0

A question of reading yaml file

asked 2017-07-26 10:53:15 -0600

updated 2017-07-26 11:01:28 -0600

LBerger gravatar image

When I write my yaml file, it's created like this:

%YAML:1.0
name: object1
Date of storage: "Wed Jul 26 16:45:46 2017\n"
object1: !!opencv-matrix
   rows: 540
   cols: 960
   dt: "3u"
   data: // blabla, a matrix here
...
---
name: object2
Date of storage: "Wed Jul 26 16:45:46 2017\n"
object1: !!opencv-matrix
   rows: 540
   cols: 960
   dt: "3u"
   data: // blabla, a matrix here
...

The problem is how can I get all the Mats of the objects, here when I use operator like fs["name"], I can only get the first object's data. Anyone Help? Thanks!

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
1

answered 2017-07-27 00:35:17 -0600

berak gravatar image

cv::FileStorage is a "key-value" store, to save different objects, you need unique keys, "name" isn't unique.

so, you either do, what @sturkmen proposes, give any item a unique name, or wrap it into "objects", like this:

Mat m1(10,10,CV_8UC3); m1=17;
Mat m2(6,8,CV_32F); m2=3;

FileStorage fs("my.yml", FileStorage::WRITE);

fs << "object1" << "{"; // an object with a unique name.
fs << "Date of storage" << "Wed Jul 26 16:45:46 2017\n";
fs << "Mat" << m1; // the "internal" keys can be as generic as you want
fs << "}";

fs << "object2" << "{";
fs << "Date of storage" << "Wed Jul 26 16:48:16 2017\n";
fs << "Mat" << m2;
fs << "}";

fs.release();

fs.open("my.yml", FileStorage::READ);
FileNode fn = fs["object2"];  // retrieve the object node
Mat M2;  String date;
fn["Mat"] >> M2;      // and its data
fn["Date of storage"] >> date;
cerr << date << endl;
cerr << M2 << endl;
edit flag offensive delete link more

Comments

Thanks, it helps me a lot

xiaohuang1992 gravatar imagexiaohuang1992 ( 2017-07-28 05:35:53 -0600 )edit
0

answered 2017-07-26 12:01:29 -0600

check the code below

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;


bool saveMats(const Mat m1, const Mat m2, String file_path)
{
    FileStorage fs(file_path, FileStorage::WRITE);

    fs << "name" << "object1";
    fs << "object1" << m1;
    fs << "object2" << m2;

    return true;
}


int main()
{

    Mat m1(5, 5, CV_8UC1, Scalar(127));
    Mat m2(6, 6, CV_8UC1, Scalar(128));
    saveMats(m1, m2, "test.yml");

    FileStorage fs("test.yml", FileStorage::READ);
    FileNode fn = fs.root();

    Mat r1,r2;
    cv::read(fn["object1"], r1);
    cv::read(fn["object2"], r2);
    cout << r1 << endl;
    cout << r2;
    imshow("just for waiting", r1);
    waitKey();

    return 0;
}
edit flag offensive delete link more

Comments

Thanks for your code~

xiaohuang1992 gravatar imagexiaohuang1992 ( 2017-07-28 05:36:06 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-07-26 10:53:15 -0600

Seen: 375 times

Last updated: Jul 27 '17