gpt4 book ai didi

c++ - 如何使用文件存储从 xml 文件中读取 vector>

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:43 24 4
gpt4 key购买 nike

我想知道是否可以使用 cv::FileStorage 类从 xml 文件加载 Point2f 的 vector vector 。

这是我尝试保存的内容:

filestorage  << "ObjPoints" << "{";
for (int i = 0; i < objPoints.size(); ++i)
{
Mat outMat(objPoints[i]);
filestorage << "ObjPoints_" + IntToString(i) << outMat;
}
filestorage << "}";

这是为了加载:

FileNode k = n["ObjPoints"];
int i = 0;
for (FileNodeIterator it = k.begin(); it!=k.end(); ++it)
{
Mat inMat;
k["ObjPoints_" + IntToString(i)] >> inMat;
vector<Point3f> tmp = Mat_<Point3f>(inMat);
++i;
objPoints.push_back(tmp);
}

其中 objPoints 是一个 vector < vector< Point3f >> 并且 IntToString 定义如下:

string IntToString(int number)
{
stringstream ss;
ss << number;
return ss.str();
}

谁能指出我正确的方向?谢谢。

最佳答案

您可以使用 FileNode 迭代每个 vector 和每个点。展示比解释更容易:

#include <opencv2\opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;

int main(){

{
// Write

vector<vector<Point3f>> v{
{ { 1, 0, 0 }, { 1, 0, 1 }, { 1, 0, 2 } },
{ { 2, 0, 0 } },
{ { 3, 0, 0 }, { 3, 0, 1 } },
};


FileStorage fs("test.xml", FileStorage::WRITE);
fs << "data" << "[";
for (int i = 0; i < v.size(); ++i)
{
// Write each vector
fs << "[:";
for (int j = 0; j < v[i].size(); ++j)
{
// Write each point
fs << "[:" << v[i][j].x << v[i][j].y << v[i][j].z << "]"; // Or use: fs << v[i][j];
}
fs << "]"; // close vector
}
fs << "]"; // close data
}


// Read

vector<vector<Point3f>> v;

FileStorage fs("test.xml", FileStorage::READ);

FileNode data = fs["data"];
for (FileNodeIterator itData = data.begin(); itData != data.end(); ++itData)
{
// Read each vector
vector<Point3f> vv;

FileNode pts = *itData;
for (FileNodeIterator itPts = pts.begin(); itPts != pts.end(); ++itPts)
{
// Read each point
FileNode pt = *itPts;

Point3f point;
FileNodeIterator itPt = pt.begin();
point.x = *itPt; ++itPt;
point.y = *itPt; ++itPt;
point.z = *itPt;

vv.push_back(point);
}
v.push_back(vv);
}

return 0;
}

您的 XML 将如下所示:

<?xml version="1.0"?>
<opencv_storage>
<data>
<_><_>
1. 0. 0.</_>
<_>
1. 0. 1.</_>
<_>
1. 0. 2.</_></_>
<_><_>
2. 0. 0.</_></_>
<_><_>
3. 0. 0.</_>
<_>
3. 0. 1.</_></_></data>
</opencv_storage>

或者在 YAML 中,例如:

%YAML:1.0
data:
- [ [ 1., 0., 0. ], [ 1., 0., 1. ], [ 1., 0., 2. ] ]
- [ [ 2., 0., 0. ] ]
- [ [ 3., 0., 0. ], [ 3., 0., 1. ] ]

关于c++ - 如何使用文件存储从 xml 文件中读取 vector<vector<Point3f>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34382832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com