从 ros 的 bag 包里提取特定的数据

目录

  • 1、从 ros 的 bag 包里提取带时间戳的图片数据
  • 2、从 ros 的 bag 包里提取不带时间戳的图片数据
  • 3、从 ros 的 bag 包里提取带时间戳的 PointCloud 格式的点云数据,把提取出来的点云保存为 txt 格式
  • 4、如何将两个rosbag包合并或者提取rosbag包中某些或某一个话题到一个rosbag里


1、从 ros 的 bag 包里提取带时间戳的图片数据

全部代码如下(python):
只要第10行、第14行、第16行根据自己的文件名进行更改就行了。

#coding:utf-8
import roslib;  
import rosbag
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from cv_bridge import CvBridgeError

path='/home/zy/shu_ju/2021-03-03-15-57-52/image2/' #要存放图片的位置
class ImageCreator():
    def __init__(self):
        self.bridge = CvBridge()
        with rosbag.Bag('2021-03-03-15-57-52.bag', 'r') as bag:   #要读取的bag文件;
            for topic,msg,t in bag.read_messages():
                if topic == "/hik03/forwardright/image_raw":  #图像的topic;
                        try:
                            cv_image = self.bridge.imgmsg_to_cv2(msg,"bgr8")
                        except CvBridgeError as e:
                            print(e)
                        timestr = "%.6f" %  msg.header.stamp.to_sec()
                        #%.6f表示小数点后带有6位,可根据精确度需要修改;
                        image_name = timestr+ ".png" #图像命名:时间戳.jpg
                        cv2.imwrite(path+image_name, cv_image)  #保存;


if __name__ == '__main__':
    try:
        image_creator = ImageCreator()
    except rospy.ROSInterruptException:
        pass

2、从 ros 的 bag 包里提取不带时间戳的图片数据

全部代码如下(后缀为 “.launch” 的文件):
只要第2行、第4行根据自己的文件名和文件路径进行更改就行了。

<launch>
  <node pkg="rosbag" type="play" name="rosbag" args="-d 2 $(find /home/zy/shu_ju)/2021-03-03-15-57-52.bag"/>
  <node name="extract" pkg="image_view" type="extract_images" respawn="false" output="screen" cwd="ROS_HOME">
<remap from="image" to="/hik03/forwardright/image_raw"/>
  </node>
</launch>

3、从 ros 的 bag 包里提取带时间戳的 PointCloud 格式的点云数据,把提取出来的点云保存为 txt 格式

全部代码如下(python):
只要第9行、第11行、第12行根据自己的文件名和文件路径进行更改就行了。

#!/usr/bin/env python
#coding:utf-8
import sys
import argparse
from fnmatch import fnmatchcase
from rosbag import Bag
import rosbag

bag_file = '2021-03-03-15-57-52.bag'
bag = rosbag.Bag(bag_file, "r")
bag_data = bag.read_messages('/ruby128result')
save_path = "/home/zy/pcd_result/"

j = 0
for topic, msg, t in bag_data:
    timestr = "%.6f" %  msg.header.stamp.to_sec()
    #print(timestr)
    #%.6f表示小数点后带有6位,可根据精确度需要修改;
    
    cloud_name = save_path + timestr+ ".txt" #点云命名:时间戳.txt
    with open(cloud_name,"w") as f:
		#其中i为索引值,如下直接通过索引取得接收到的数据对象
        for i in range(len(msg.points)):
            msg.points[i].x;
            msg.points[i].y;
            msg.points[i].z;
            f.writelines([str(msg.points[i].x), ' ', str(msg.points[i].y), ' ', str(msg.points[i].z), '\n'])  # 自带文件关闭功能,不需要再写f.close()
    if j % 10 == 0:
    	print('di ', j, ' zhen')
    j += 1
    #o3d.io.write_point_cloud(pcd_name, pcd)
    #o3d.io.write_point_cloud("../../TestData/sync.ply", pcd)

4、如何将两个rosbag包合并或者提取rosbag包中某些或某一个话题到一个rosbag里

代码叫做merge_bag.py
运行的时候,命令行输入:

python merge_bag.py -v 1028msf.bag msf.bag vinReNoOutlier.bag 

就是把 msf.bag 和 vinReNoOutlier.bag 完全合并在一起了,合并的新bag包叫 1028msf.bag,时间戳打的都是原来两个bag里原始的时间戳,而不是像一边rosbag play一边rosbag record一样录的是现在这个时间戳。

命令行输入:

python merge_bag.py -v –topics ‘/aft_mapped_to_init /gnss/data /imu/data vinReNoOutlier’ msf.bag 2019-10-28-14-40-45.bag vinReNoOutlier.bag

就是把2019-10-28-14-40-45.bag里的/aft_mapped_to_init、/gnss/data、/imu/data和vinReNoOutlier.bag里的vinReNoOutlier合并在了一起,注意一定不能在vinReNoOutlier前加/,因为本身vinReNoOutlier.bag里的话题名就是vinReNoOutlier,没有/

全部代码如下(python):

#!/usr/bin/env python
import sys
import argparse
from fnmatch import fnmatchcase
from rosbag import Bag
def main():
    parser = argparse.ArgumentParser(description='Merge one or more bag files with the possibilities of filtering topics.')
    parser.add_argument('outputbag',
                        help='output bag file with topics merged')
    parser.add_argument('inputbag', nargs='+',
                        help='input bag files')
    parser.add_argument('-v', '--verbose', action="store_true", default=False,
                        help='verbose output')
    parser.add_argument('-t', '--topics', default="*",
                        help='string interpreted as a list of topics (wildcards \'*\' and \'?\' allowed) to include in the merged bag file')
    args = parser.parse_args()
    topics = args.topics.split(' ')
    total_included_count = 0
    total_skipped_count = 0
    if (args.verbose):
        print("Writing bag file: " + args.outputbag)
        print("Matching topics against patters: '%s'" % ' '.join(topics))
        
    with Bag(args.outputbag, 'w') as o: 
        for ifile in args.inputbag:
            matchedtopics = []             
            included_count = 0
            skipped_count = 0
            if (args.verbose):
                print("> Reading bag file: " + ifile)
            with Bag(ifile, 'r') as ib:
                for topic, msg, t in ib:
                    if any(fnmatchcase(topic, pattern) for pattern in topics):
                        if not topic in matchedtopics:
                            matchedtopics.append(topic)
                            if (args.verbose):
                                print("Including matched topic '%s'" % topic)
                        o.write(topic, msg, t)
                        included_count += 1
                        if included_count % 10 == 0:
                            print("Included messages:", included_count)
                    else:
                        skipped_count += 1
            total_included_count += included_count
            total_skipped_count += skipped_count
            if (args.verbose):
                print("< Included %d messages and skipped %d" % (included_count, skipped_count))
    if (args.verbose):
        print("Total: Included %d messages and skipped %d" % (total_included_count, total_skipped_count))
if __name__ == "__main__":
    main()

你可能感兴趣的:(自动驾驶,人工智能,机器学习)