在ROS中处理yaml文件

版权声明: https://blog.csdn.net/u014610460/article/details/79508869
在ROS系统中,参数读写一般通过xml或者yaml格式的文件,其中yaml用得比较多。这是一种可读性高,轻量级的标记语言,简单好用。
对于yaml文件,ros中用的较早版本的 yaml-cpp库,最新的可在github上下载,并按照readme中所述的方法编译安装。

特别留意的是,如果需要生成共享库,cmake的时候后面一定要加上 -DBUILD_SHARED_LIBS=ON 这句话。


有了yaml库,在CMakeLists.txt中加入,

link_directories(/usr/local/lib)
include_directories(/usr/local/include/yaml-cpp)
最后别忘了在链接库target_link_libraries时,加上yaml-cpp。
关于库的使用,github上有一些简单的 tutorial教程

以下是简单的yaml文件读写操作示例。

#include <ros/ros.h>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <fstream>

int main(int argc, char **argv)
{
    std::string fin = "/home/user/param/param.yaml";       //yaml文件所在的路径
    YAML::Node yamlConfig = YAML::LoadFile(fin);
    int int_param = yamlConfig["int_param"].as<int>();
    std::cout << "  node size: " << yamlConfig.size() << std::endl;
    std::cout << yamlConfig["bool_param"].as<bool>() << "\n";
    yamlConfig["bool_param"] = !yamlConfig["bool_param"].as<bool>();
    yamlConfig["str_param"] = "test";
    std::ofstream file;
    file.open(fin);
    file.flush();
    file << yamlConfig;
    file.close();

    return 0;
}

其中,yaml文件里的内容为:

bool_param: true
int_param: 2
double_param: 0.5
str_param: "123"

也可采用Emit来生成yaml文件,代码如下:

#include <ros/ros.h>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <fstream>

int main(int argc, char **argv)
{
    std::ofstream fout("/home/user/param/param.yaml");
    YAML::Emitter out(fout);
    out << YAML::BeginMap;
    out << YAML::Key << "int_param";
    out << YAML::Value << 1;
    out << YAML::Key << "double_param";
    out << YAML::Value << 0.5;
    out << YAML::Key << "bool_param";
    out << YAML::Value << false;
    out << YAML::Comment("bool parameter");
    out << YAML::Key << "str_param";
    out << YAML::Value << "test";
    out << YAML::EndMap;
    
    return 0;
}


其综合运用的案例可参见博文:ros-opencv-qt-yaml综合运用之滤波

Enjoy!

猜你喜欢

转载自blog.csdn.net/u014610460/article/details/79508869
今日推荐