python将ros下bag文件的所有topic解析为csv格式

背景:最近在制作kimera的数据集,尤其是运行semantic模块所需要的bag文件中有很多topic,但是很多不知道topic中装的是什么数据,及其格式,所以我就想着怎么可以将bag中的topic都解析数来,这样就能知道bag中都有啥了.有网友提供了下面的代码,我稍作了些修改,可以在python3下可以顺利运行.如果你的文件夹下有多个bag文件,这个代码可以挨个处理这些bag文件,先为每个bag文件创建一个相应的文件夹,然后把bag文件拷贝进去,然后将bag中的topic都解析为csv格式

 

#!/usr/bin/python
'''
This script saves each topic in a bagfile as a csv.Accepts a filename as an optional argument. Operates on all bagfiles in current directory if no argument providedWritten by Nick Speal in May 2013 at McGill University's Aerospace Mechatronics Laboratory
www.speal.caSupervised by Professor Inna Sharf, Professor Meyer Nahon'''import rosbag, sys, csv
import time
import string
import os #for file management make directory
import shutil #for file management, copy file#verify correct input arguments: 1 or 2
if (len(sys.argv) > 2):print("invalid number of arguments:   " + str(len(sys.argv)))print("should be 2: 'bag2csv.py' and 'bagName'")print("or just 1  : 'bag2csv.py'")sys.exit(1)
elif (len(sys.argv) == 2):listOfBagFiles = [sys.argv[1]]numberOfFiles = "1"print("reading only 1 bagfile: " + str(listOfBagFiles[0]))
elif (len(sys.argv) == 1):listOfBagFiles = [f for f in os.listdir(".") if f[-4:] == ".bag"]	#get list of only bag files in current dir.numberOfFiles = str(len(listOfBagFiles))print("reading all " + numberOfFiles + " bagfiles in current directory: \n")for f in listOfBagFiles:print(f)print("\n press ctrl+c in the next 10 seconds to cancel \n")time.sleep(10)
else:print("bad argument(s): " + str(sys.argv))	#shouldnt really come upsys.exit(1)count = 0
for bagFile in listOfBagFiles:count += 1print("reading file " + str(count) + " of  " + numberOfFiles + ": " + bagFile)#access bagbag = rosbag.Bag(bagFile)bagContents = bag.read_messages()bagName = bag.filename#/home/yunlei/COOL/kalibr-cde/test/2020-06-13-11-57-29.bag#create a new directory string.rstrip(bagName, ".bag")folder = bagName.split(".bag")[0]try:	#else already existsos.makedirs(folder)except:passshutil.copyfile(bagName, folder + '/' + bagName.split('/')[-1])#get list of topics from the baglistOfTopics = []for topic, msg, t in bagContents:if topic not in listOfTopics:listOfTopics.append(topic)for topicName in listOfTopics:#Create a new CSV file for each topic folder + '/' + string.replace(topicName, '/', '_slash_') + '.csv'filename = folder + '/' + topicName.split('/')[-1] + '.csv'with open(filename, 'w+') as csvfile:filewriter = csv.writer(csvfile, delimiter = ',')firstIteration = True	#allows header rowfor subtopic, msg, t in bag.read_messages(topicName):	# for each instant in time that has data for topicName#parse data from this instant, which is of the form of multiple lines of "Name: value\n"#	- put it in the form of a list of 2-element listsmsgString = str(msg)msgList = msgString.split('\n')instantaneousListOfData = []for nameValuePair in msgList:splitPair = nameValuePair.split(':')for i in range(len(splitPair)):	#should be 0 to 1splitPair[i] = splitPair[i].strip()instantaneousListOfData.append(splitPair)#write the first row from the first element of each pairif firstIteration:	# headerheaders = ["rosbagTimestamp"]	#first column headerfor pair in instantaneousListOfData:headers.append(pair[0])filewriter.writerow(headers)firstIteration = False# write the value from each pair to the filevalues = [str(t)]	#first column will have rosbag timestampfor pair in instantaneousListOfData:if len(pair) > 1:values.append(pair[1])filewriter.writerow(values)bag.close()
print("Done reading all " + numberOfFiles + " bag files.")

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/252415.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

十九. Python基础(19)--异常

十九. Python基础(19)--异常 1 ● 捕获异常 if VS异常处理: if是预防异常出现, 异常处理是处理异常出现 异常处理一般格式: try: <...............> #可能得到异常的语句 except <.......>: #捕获是哪种异常 <...............> #出现异常的处理方…

洛谷1052——过河(DP+状态压缩)

题目描述 在河上有一座独木桥&#xff0c;一只青蛙想沿着独木桥从河的一侧跳到另一侧。在桥上有一些石子&#xff0c;青蛙很讨厌踩在这些石子上。由于桥的长度和青蛙一次跳过的距离都是正整数&#xff0c;我们可以把独木桥上青蛙可能到达的点看成数轴上的一串整点&#xff1a;0…

Tensorflow学习教程------tfrecords数据格式生成与读取

首先是生成tfrecords格式的数据&#xff0c;具体代码如下&#xff1a; #coding:utf-8import os import tensorflow as tf from PIL import Imagecwd os.getcwd() 此处我加载的数据目录如下&#xff1a; bt -- 14018.jpg14019.jpg14020.jpgnbt -- 1_ddd.jpg1_dsdfs.jpg1_dfd.…

ROS获取KinectV2相机的彩色图和深度图并制作bundlefusion需要的数据集

背景&#xff1a; 最近在研究BundleFusion&#xff0c;跑通官方数据集后&#xff0c;就想着制作自己的数据集来运行bundlefusion&#xff0e;KinectV2相机可直接获取的图像的分辨率分为三个HD 1920x1080, QHD: 960X540&#xff0c;SD: 512x424.我选择是中间的分辨率qhd. 录制…

Linux下配置tomcat+apr+native应对高并发

摘要&#xff1a;在慢速网络上Tomcat线程数开到300以上的水平&#xff0c;不配APR&#xff0c;基本上300个线程狠快就会用满&#xff0c;以后的请求就只好等待。但是配上APR之后&#xff0c;Tomcat将以JNI的形式调用Apache HTTP服务器的核心动态链接库来处理文件读取或网络传输…

Firefox 66 将阻止自动播放音频和视频

百度智能云 云生态狂欢季 热门云产品1折起>>> 当我们点击一个链接&#xff0c;或者打开新的浏览器选项卡时&#xff0c;浏览器就开始自动播放视频和声音&#xff0c;这是一件十分烦人的事。Chrome 浏览器早已对这些行为下手了&#xff0c;现在 Firefox 也明确表示要…

Windows 10 关闭Hyper-V

以管理员身份运行命令提示符 关闭 bcdedit /set hypervisorlaunchtype off 启用 bcdedit / set hypervisorlaunchtype auto 禁用DG 转载于:https://www.cnblogs.com/Robbery/p/8397767.html

ROS下获取kinectv2相机的仿照TUM数据集格式的彩色图和深度图

准备工作&#xff1a; &#xff11;&#xff0e; ubuntu16.04上安装iai-kinect2, 2. 运行roslaunch kinect2_bridge kinect2_bridge.launch, 3. 运行 rosrun save_rgbd_from_kinect2 save_rgbd_from_kinect2,开始保存图像&#xff0e; 这个保存kinectV2相机的代码如下&…

Java Web 九大内置对象(一)

在Jsp 中一共定义了九个内置对象&#xff0c;分别为&#xff1a; *request HttpServletRequest; *response HttpServletResponse; *session HttpSession; page This(本jsp页面)&#xff1b; *application ServletCon…

Missing URI template variable 'XXXX' for method parameter of type String

原因&#xff1a;就是spring的controller上的RequestMapping的实参和方法里面的形参名字不一致 方法&#xff1a;改成一样就可。 ps.还能用绑定的方法&#xff0c;不建议&#xff0c;因为太麻烦了 RequestMapping(value "/findUser/{id}",method RequestMethod.GET…

css:text-overflow属性

参考文档:www.w3school.com.cn/cssref/pr_t… text-overflow:ellipsis;( 显示省略符号来代表被修剪的文本。)

Failed to load nodelet ‘/kinect2_bridge` of type `kinect2_bridge/kinect2_bridge_nodelet` to manager

之前在我的电脑上配置了libfreenect2和iai_kinect2&#xff0c;现在需要在工控机上重新安装这两个库&#xff0c;讲kinectV2相机安置在婴儿车上&#xff0c;然后使用我的ros下获取kinectV2相机的彩色图和灰度图的脚本&#xff0c;获取深度图和彩色图。 我成功的安装了libfreen…

object转字符串

1、obj.tostring() obj为空时&#xff0c;抛异常。 2、convert.tostring(obj) obj为空时&#xff0c;返回null&#xff1b; 3、(string)obj obj为空时&#xff0c;返回null&#xff1b;obj不是string类型时&#xff0c;抛异常。 4、obj as string obj为空时&#xff0c;返回nul…

微信开发中,H5的video标签使用

<video></video>是HTML5新加入的标签&#xff0c;最近流行的h5开发多以video技术集成一个H5页面&#xff0c;效果也是很6的。现在总结一下用到的技术&#xff0c;主要的使用环境是微信&#xff0c;部分属性一些手机的默认浏览器不支持&#xff0c;这些还需要读者亲…

bundlefusion论文阅读笔记

4. 全局位姿对齐(glob pose alignment) 输入系统的是使用消费级的传感器获取的RGBD数据流&#xff0c;并且保证这些数据中的彩色图像和深度图像是时间和空间上都对齐的。图像分辨率是640x480,频率是30hz。我们的目的就是要找到frames之间的3D对应&#xff0c;然后根据这些对应…

IOC和DI的区别详解

IOC 是英文inversion of control的缩写&#xff0c;意思是控制反转DI 是英文Dependency Injection的缩写&#xff0c;意思是依赖注入 下面用一个简单的例子来描述一下IOC和DI的关系 先看下总结&#xff1a; 依赖注入(DI)和控制反转(IOC)是从不同的角度的描述的同一件事情&#…

TOMCAT启动到一半停止如何解决

当你的项目过大的时候&#xff0c;往往会导致你的TOMCAT启动时间过长&#xff0c;启动失败&#xff0c;遇到该情况可以试一下下面两招&#xff1a; TOmcat启动到一半的时候停止了&#xff0c;以下原因&#xff1a; 1、 tomcat启动时间超过了设置时间&#xff1a; 解决办法&…

视觉slam十四讲ch6曲线拟合 代码注释(笔记版)

1 #include <opencv2/core/core.hpp>2 #include <ceres/ceres.h>3 #include <chrono>4 5 using namespace std;6 7 // 代价函数的计算模型8 struct CURVE_FITTING_COST9 {10 CURVE_FITTING_COST ( double x, double y ) : _x ( x ), _y ( y ) {}11 /…

Dojo 如何测试 widget

测试 dojo/framework/src/testing/README.mdcommit 84e254725f41d60f624ab5ad38fe82e15b6348a2 用于测试和断言 Dojo 部件期望的虚拟 DOM 和行为的简单 API。 测试 Features harness APICustom Comparatorsselectors harness.expect harness.expectPartial harness.triggerharn…

python中将四元数转换为旋转矩阵

在制作bundlefusion时,想测试TUM数据集,并且将groundtruth写入到数据集中,TUM中给定的groundtruth中的旋转是使用四元数表示的,而bundlefusion中需要SE3的形式,所以我需要首先将四元数转换为旋转矩阵,然后再将其与平移向量合并在一起,因为我之前关于生成bundlefusion数据集写了…