ROS 程序运行参数设置方法
背景: 很多程序都需要输入运行参数, 这里有几种方法
1.使用argv
适用于单一参数或参数数量较少,参数类型简单的情况。
int main(int argc, char **argv)
{
std::string str;
if(argc == 2)
{
str = argv[1];
}
}
2.使用Launch文件
该方法适用于载入多个文件,可以搭配yaml文件进行,也可以单独在launch文件中输入变量
读入yaml文件的方法:
<rosparam command="load" file="$(find apriltags2_ros)/config/settings.yaml" ns="$(arg node_namespace)" />
随后在源文件中
double init_x;
std::string name_init_x = "apriltags2_ros_continuous_node/Position_x";
ros::param::get(name_init_x, init_x);//return type is bool
读入yaml文件中的矩阵
使用XmlRpc::XmlRpcValue
launch文件:
<launch>
<node pkg="warpImage" type="warp" name="warp" clear_params="true" output="screen">
<rosparam file="/home/junbo/dev/ROS_Tutorials/src/warpImage/config/config.yaml"/>
</node>
</launch>
yaml文件:
Intrinsic: [640.1291987855028, 0.0, 310.6979515634958, 0.0, 639.8707433015408, 238.0339433865112, 0.0, 0.0, 1.0]
Rotation: [0.977, 0.081, 0.116, -0.023, 0.856, -0.494, -0.153, 0.495, 0.843]
源文件:
XmlRpc::XmlRpcValue paramList;
std::vector<double> Intrinsic;
std::vector<double> Rotation;
Matrix3d K, Kinv, R;
if(!ros::param::get("warp/Intrinsic", paramList))
{
ROS_ERROR("Failed to get parameter from server!");
return -1;
}
else
{
for(size_t i = 0; i < paramList.size(); ++i)
{
XmlRpc::XmlRpcValue temp = paramList[i];
if(temp.getType() == XmlRpc::XmlRpcValue::TypeDouble)
Intrinsic.push_back(double(temp));
}
}
cv::Matx33d matRotation(
Rotation[0], Rotation[1], Rotation[2],
Rotation[3], Rotation[4], Rotation[5],
Rotation[6], Rotation[7], Rotation[8]);
3.使用OpenCV的Filestorage对象
该方式适用于比较特殊的参数类型,比如说用于表示位姿变换的向量和矩阵;该方法的另外优点是: 可以用来写入参数
写入:
cv::Mat mat = (cv::Mat_<double>(1,4) << odo.pose.pose.orientation.w, odo.pose.pose.orientation.x, odo.pose.pose.orientation.y, odo.pose.pose.orientation.z);
cv::Mat vec = (cv::Mat_<double>(1,3) << odo.pose.pose.position.x, odo.pose.pose.position.y, odo.pose.pose.position.z);
FileStorage fs("/home/junbo/dev/ROS_Tutorials/src/odometry/test.yaml", FileStorage::APPEND);
if(type == 0)
{
fs << "QuatCam0Init" << mat;
fs << "TranVecCam0Init" << vec;
fs.release();
cout << "WRITTEN!" << endl;
}
读取:
FileStorage fs("/home/junbo/dev/ROS_Tutorials/src/odometry/test.yaml", FileStorage::READ);
if(!fs.isOpened())
{
std::cout << "No file!" << std::endl;
//return -1;
}
cv::Mat Q0I, Q0C, Q1C;
cv::Mat T0I, T0C, T1C;
fs["QuatCam0Init"] >> Q0I;
fs["QuatCam0Covision"] >> Q0C;
fs["QuatCam1Covision"] >> Q1C;
fs["TranVecCam0Init"] >> T0I;
fs["TranVecCam0Covision"] >> T0C;
fs["TranVecCam1Covision"] >> T1C;
fs.release();
4.其他方法
比如使用yaml-cpp库,这是一种针对yaml的工具,可用于读写yaml文件,但是需要增加额外的依赖项。