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.pswp.cn/news/252415.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/252415.shtml
英文地址,請注明出處:http://en.pswp.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數據集寫了…