我得到了一系列OpenCv生成的YAML文件,并希望用yaml-cpp解析它们。
我在简单的事情上做得还不错,但是矩阵表示是很困难的。
# Center of table
tableCenter: !!opencv-matrix
rows: 1
cols: 2
dt: f
data: [ 240, 240]这应该映射到向量中。
240
240使用float类型。我的代码看起来是:
#include "yaml.h"
#include <fstream>
#include <string>
struct Matrix {
int x;
};
void operator >> (const YAML::Node& node, Matrix& matrix) {
unsigned rows;
node["rows"] >> rows;
}
int main()
{
std::ifstream fin("monsters.yaml");
YAML::Parser parser(fin);
YAML::Node doc;
Matrix m;
doc["tableCenter"] >> m;
return 0;
}但我得到
terminate called after throwing an instance of 'YAML::BadDereference'
what(): yaml-cpp: error at line 0, column 0: bad dereference
Abort trap我搜索了yaml-cpp的一些文档,但除了一个关于解析和发射的简短介绍性示例之外,似乎没有任何文档。不幸的是,在这种特殊情况下,这两种情况都没有帮助。
据我所知,!!表示这是用户定义的类型,但我不知道yaml-cpp如何解析它。
发布于 2010-04-20 16:55:15
您必须告诉yaml-cpp如何解析这种类型。由于C++不是动态类型的,所以它无法检测您想要的数据类型并从头创建它--您必须直接告诉它。标记节点实际上只适用于自己,而不是解析器(它只为您忠实地存储它)。
我不太确定OpenCV矩阵是如何存储的,但是如果是这样的话:
class Matrix {
public:
Matrix(unsigned r, unsigned c, const std::vector<float>& d): rows(r), cols(c), data(d) { /* init */ }
Matrix(const Matrix&) { /* copy */ }
~Matrix() { /* delete */ }
Matrix& operator = (const Matrix&) { /* assign */ }
private:
unsigned rows, cols;
std::vector<float> data;
};然后你就可以写这样的东西
void operator >> (const YAML::Node& node, Matrix& matrix) {
unsigned rows, cols;
std::vector<float> data;
node["rows"] >> rows;
node["cols"] >> cols;
node["data"] >> data;
matrix = Matrix(rows, cols, data);
}编辑--在此之前,您似乎还好;但是,您忽略了解析器将信息加载到YAML::Node中的步骤。相反,把它说成:
std::ifstream fin("monsters.yaml");
YAML::Parser parser(fin);
YAML::Node doc;
parser.GetNextDocument(doc); // <-- this line was missing!
Matrix m;
doc["tableCenter"] >> m;注意:我猜dt: f的意思是“数据类型是浮动的”。如果是这样的话,这将取决于Matrix类如何处理这个问题。如果每个数据类型(或模板类)有不同的类,则必须先读取该字段,然后选择要实例化的类型。(如果你知道它总是浮动的,那当然会让你的生活更轻松。)
https://stackoverflow.com/questions/2675092
复制相似问题