mrgloom
mrgloom

Reputation: 21642

OpenCV FileStorage how to read vector of structures?

I write vector with some data like this:

string filename= itemName+".yml";

FileStorage fs(filename, FileStorage::WRITE);
fs << "number_of_objects" << (int)vec.size();
fs << "objects" << "[";
for( int i=0; i < (int)vec.size(); ++i )
{
    fs << "{";
    fs << "x" << rc.x/imageScale;
    fs << "y" << rc.y/imageScale;
    fs << "w" << rc.width/imageScale;
    fs << "h" << rc.height/imageScale;
    fs << "}";
}
fs << "]";

But I can't read them back.

FileStorage fs(filename, FileStorage::READ);

if(!fs.isOpened())
    return false;

int nObjects= 0;
fs["number_of_objects"] >> nObjects;
imageMarkupData.resize(nObjects);
for( int i=0; i < nObjects; ++i )
{
    int x,y,w,h;
    fs["x"] >> x;
    fs["y"] >> y;
    fs["w"] >> w;
    fs["h"] >> h;

    //...
}

What is the proper way?

Upvotes: 1

Views: 3004

Answers (1)

mrgloom
mrgloom

Reputation: 21642

Proper way was to use FileNode and FileNodeIterator.

    FileStorage fs(filename, FileStorage::READ);

    if(!fs.isOpened())
        return false;

    int nObjects= 0;
    fs["number_of_objects"] >> nObjects;
    vec.resize(nObjects);

    FileNode fn = fs["objects"];
    int id=0;
    for (FileNodeIterator it = fn.begin(); it != fn.end(); it++,id++)
    {
        FileNode item = *it;

        int x,y,w,h;
        item["x"] >> x;
        item["y"] >> y;
        item["w"] >> w;
        item["h"] >> h;
    }

Upvotes: 1

Related Questions