Reading ROS Messages from a Bagfile in Python

Image for post
Image for post
Image by the author from a ROS simulation.

Install bagpy package:

!pip install bagpy

Get the sample bag files

!wget https://data.ouster.io/sample-data-1.13/OS1-64/OS1-64_city1.bag

Read the bag file

import bagpy
from bagpy import bagreader
import pandas as pd
import seaborn as sea
import matplotlib.pyplot as plt
import numpy as np
b = bagreader('OS1-64_city1.bag')

Check available topics

b.topic_table
csvfiles = []
for t in b.topics:
data = b.message_by_topic(t)
csvfiles.append(data)
data = b.message_by_topic('/os1_cloud_node/imu')
print("File saved: {}".format(data))
df_imu = pd.read_csv(data)
df_imu
fig, ax = bagpy.create_fig(10)
ax[0].scatter(x = 'Time', y = 'orientation.x', data = df_imu, s= 1, label = 'orientation.x')
ax[1].scatter(x = 'Time', y = 'orientation.y', data = df_imu, s= 1, label ='orientation.y')
ax[2].scatter(x = 'Time', y = 'orientation.z', data = df_imu, s= 1, label = 'orientation.z')
ax[3].scatter(x = 'Time', y = 'orientation.w', data = df_imu, s= 1, label ='orientation.w')
ax[4].scatter(x = 'Time', y = 'angular_velocity.x', data = df_imu, s= 1, label = 'angular_velocity.x')
ax[5].scatter(x = 'Time', y = 'angular_velocity.y', data = df_imu, s= 1, label = 'angular_velocity.y')
ax[6].scatter(x = 'Time', y = 'angular_velocity.z', data = df_imu, s= 1, label = 'angular_velocity.z')
ax[7].scatter(x = 'Time', y = 'linear_acceleration.x', data = df_imu, s= 1, label = 'linear_acceleration.x')
ax[8].scatter(x = 'Time', y = 'linear_acceleration.y', data = df_imu, s= 1, label = 'linear_acceleration.y')
ax[9].scatter(x = 'Time', y = 'linear_acceleration.z', data = df_imu, s= 1, label = 'linear_acceleration.z')
for axis in ax:
axis.legend()
axis.set_xlabel('Time')

plt.show()

Written by

Pursuing Ph.D, Electrical Engg | Lecturer in Engineering | Intelligent Transportation & Quantum Science Researcher | https://www.buymeacoffee.com/rahulbhadani

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store