Reputation: 117
Can I parse a YAML file in OpenCV (using FileStorage library) without knowing the names of the nodes?
For example, the next YAML file:
%YAML:1.0
descriptors1: !!opencv-matrix
rows: 82
cols: 64
dt: f
data: [ ... ]
descriptors2: !!opencv-matrix
rows: 161
cols: 64
dt: f
data: [ ... ]
and parse, node by node (OpenCV Matrix by OpenCV Matrix), without doing:
FileStorage fs;
...
Mat firstMatrix;
Mat secondMatrix;
fs["descriptors1"] >> firstMatrix;
fs["descriptors2"] >> secondMatrix;
Upvotes: 4
Views: 2740
Reputation: 161
To obtain all keys in any node, which have a name, you can do like this:
cv::FileStorage pfs(fileToRead, cv::FileStorage::READ);
cv::FileNode fn = pfs.root();
for (cv::FileNodeIterator fit = fn.begin(); fit != fn.end(); ++fit)
{
cv::FileNode item = *fit;
std::string somekey = item.name();
std::cout << somekey << std::endl;
}
You can also do this recursively by iterating on the file node item
Upvotes: 4
Reputation: 8617
I had a similar problem (here), but in my case the nodes were not in the top level. I don't think you can access to all the elements, but the first one with FileStorage::getFirstTopLevelNode
.
Based on @Aurelius' idea, another workaround may be to create a new YAML file in which you dump your original YAML but inside a node structure (adding a couple of lines and increasing the indentation). Then, you can read the new YAML file, retrieve the first node and get the rest of the data with a FileNodeIterator
. This should give you access to elements even without knowing the names.
Upvotes: 0
Reputation: 11359
If the matrices are all mapped to the top level (as in your example), there is not a way to access them without knowing the name of their corresponding nodes. FileStorage::operator[]
only takes string arguments specifying the name of the node.
A workaround could be to parse the YAML with another method to get the node names, and then access the FileStorage
afterward.
Upvotes: 1