OpenCV文件存储如何读取结构向量

OpenCV FileStorage how to read vector of structures?

本文关键字:读取 结构 向量 文件 存储 何读取 OpenCV      更新时间:2023-10-16

我用一些数据写向量:

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 << "]";

但是我不能读回去。

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;
    //...
}

正确的方法是什么?

正确的方法是使用FileNodeFileNodeIterator

    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;
    }