Bag File Reading and Writting Example

Share:
## Synopsis - rosbag file reaing and writting ## C++ Example ### write bag file example ```cpp #include <ros/ros.h> #include <rosbag/bag.h> #include <std_msgs/Int32.h> #include <std_msgs/String.h> int main(int argc, char** argv) { ros::init(argc, argv, "bag_writer"); ros::NodeHandle nh; rosbag::Bag bag; bag.open("test.bag", rosbag::bagmode::Write); std_msgs::String str; str.data = std::string("foo"); std_msgs::Int32 i; i.data = 42; bag.write("chatter", ros::Time::now(), str); bag.write("numbers", ros::Time::now(), i); bag.close(); ros::spinOnce(); return 0; } ``` ### read bag file example ```cpp #include #include #include #include #include #include #define foreach BOOST_FOREACH int main(int argc, char** argv) { ros::init(argc, argv, "bag_reader"); ros::NodeHandle nh; rosbag::Bag bag; bag.open("test.bag", rosbag::bagmode::Read); std::vector topics; topics.push_back(std::string("chatter")); topics.push_back(std::string("numbers")); rosbag::View view(bag, rosbag::TopicQuery(topics)); foreach (rosbag::MessageInstance const m, view) { std_msgs::String::ConstPtr s = m.instantiate(); if (s != NULL) std::cout << s->data << std::endl; std_msgs::Int32::ConstPtr i = m.instantiate(); if (i != NULL) std::cout << i->data << std::endl; } bag.close(); ros::spinOnce(); return 0; } ``` # Python Example ## Write bag file ```python #!/usr/bin/python # http://wiki.ros.org/rosbag/Code%20API import rosbag from std_msgs.msg import Int32, String bag = rosbag.Bag('test.bag', 'w') try: s = String() s.data = 'foo' i = Int32() i.data = 42 bag.write('chatter', s) bag.write('numbers', i) finally: bag.close() ``` ## Read bag file ```python #!/usr/bin/python # http://wiki.ros.org/rosbag/Code%20API import rosbag bag = rosbag.Bag('test.bag') for topic, msg, t in bag.read_messages(topics=['chatter', 'numbers']): print(topic) print(msg) bag.close() ``` ## References - [rosbag/Code API]\( API?action=fullsearch&context=180&value=linkto%3A"rosbag%2FCode+API") ![yubao_blog_cover](https://raw.githubusercontent.com/yubaoliu/assets/image/yubao_blog_cover.png)

No comments