OpenCV FileStorage读写.yml文件出现解析错误问题求助
Fixing OpenCV FileStorage YAML Parsing Error with Nested Data Structures
First, let's break down why you're hitting that parsing error:
Your error Missing , between the elements happens because the YAML file generated by your write code has invalid formatting. Looking at your YAML snippet, you can see:
- The final
scorevalue is truncated (score:-1.095020413instead of a complete number + closing}) - Manual concatenation of
[,{:, and sequence closers leads to missing separators or unclosed mappings/sequences in nested layers - OpenCV's YAML parser is strict about syntax, so even small formatting breaks will cause it to fail immediately (which is why your "Here" debug prints never run—
FileStoragethrows an error during initialization when it hits bad YAML).
Solution: Use OpenCV's Built-in Sequence/Map APIs
Instead of manually writing YAML syntax characters like [ or {:, use OpenCV's beginWriteSeq()/endWriteSeq() and beginWriteMap()/endWriteMap() methods. These handle all formatting details (commas, brackets, closures) automatically, eliminating human error.
Fixed Write Code
if (saveLoad == MODEL::SAVE) { cv::FileStorage fs(detections_filename, cv::FileStorage::WRITE); // Start outer sequence for detections_structure cv::FileNode class_seq = fs.beginWriteSeq("detections_structure"); for (auto &class_entry : dpm_detections) { // Create map for each class entry cv::FileNode class_map = fs.beginWriteMap(); class_map["class_id"] = class_entry.first; // Start sequence for image paths under this class cv::FileNode img_seq = fs.beginWriteSeq("second"); for (auto &img_entry : class_entry.second) { // Create map for image path entry cv::FileNode img_map = fs.beginWriteMap(); img_map["img_path"] = img_entry.first; // Start sequence for detections under this image cv::FileNode det_seq = fs.beginWriteSeq("second"); for (auto &detection : img_entry.second) { // Create map for individual detection cv::FileNode det_map = fs.beginWriteMap(); det_map["classID"] = detection.classID; det_map["rect"] = detection.rect; det_map["score"] = detection.score; fs.endWriteMap(det_map); } fs.endWriteSeq(det_seq); fs.endWriteMap(img_map); } fs.endWriteSeq(img_seq); fs.endWriteMap(class_map); } fs.endWriteSeq(class_seq); fs.release(); }
Verification Steps
- Run the fixed write code to generate a new YAML file.
- Open the YAML file to confirm:
- All mappings
{...}have closing} - Nested sequences are properly formatted with valid separators
- No truncated values (like the incomplete
scorein your original snippet)
- All mappings
- Test your existing read code again—it should now print your "Here" debug messages and successfully parse the file.
内容的提问来源于stack exchange,提问作者David W. Romero
相关产品推荐
相关产品推荐

