如何在 OpenCV 中以编程方式在 YAML 中编写注释?

How to write comments in the YAML programmatically in OpenCV?

我通常在 YAML 中添加注释,以便 reader 可以快速理解 YAML 参数。

%CommentC: "~~~~~~~~~~~~~~~~~~~Filtering Setting~~~~~~~~~~~~~~~~~~~"
WindowSize: 3
Sigma: 3
LowerThreshold: 25
HigherThreshold: 35 

但是如何使用 FileStorage 在 OpenCV 中以编程方式编写评论?

您可以使用函数:

/* writes a comment */
CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, int eol_comment );

这是工作示例:

#include <opencv2\opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    {
        FileStorage fs("test.yml", FileStorage::WRITE);

        cvWriteComment(*fs, "a double value", 0);
        fs << "dbl" << 2.0;

        cvWriteComment(*fs, "a\nvery\nimportant\nstring", 0);
        fs << "str" << "Multiline comments work, too!";
    }

    {
        double d;
        string s;
        FileStorage fs("test.yml", FileStorage::READ);
        fs["dbl"] >> d;
        fs["str"] >> s;
    }

    return 0;
}

test.yml 文件:

%YAML:1.0
# a double value
dbl: 2.
# a
# very
# important
# string
str: "Multiline comments work, too!"

我们在新版本的OpenCV(3.2或更高版本)中使用FileStorage编写注释的方式与以前的版本有点不同。这是函数:

void cv::FileStorage::writeComment(const String &   comment, bool  append = false)  

一个例子:

#include <opencv2/core.hpp>
#include <iostream>
#include <string>

using namespace cv;
using namespace std;

int main()
{
    {
        FileStorage fs("test.yml", FileStorage::WRITE);

        fs.writeComment("a double value", 0);
        fs << "dbl" << 2.0;

        fs.writeComment("a\nvery\nimportant\nstring", 0);
        fs << "str" << "Multiline comments work, too!";
    }

    {
        double d;
        string s;
        FileStorage fs("test.yml", FileStorage::READ);
        fs["dbl"] >> d;
        fs["str"] >> s;
    }

    return 0;
}

结果(test.yml):

%YAML:1.0
---
# a double value
dbl: 2.
# a
# very
# important
# string
str: "Multiline comments work, too!"