Python Tools for Processing ROS2 Bag Data
ROS2 provides several powerful tools for working with recorded bag data in Python. These tools range from command-line utilities to programmatic APIs that allow developers to read, analyze, transform, and reuse data captured in rosbag2 files. This overview covers the core tools available, how to use them, and their limitations.
rosbag2_py Python API
The rosbag2_py package provides a Python API for directly interacting with bag files programmatically, offering more flexibility than command-line tools.
Usage
Reading from a bag file:
import rclpy
from rclpy.serialization import deserialize_message
from rosidl_runtime_py.utilities import get_message
import rosbag2_py
def read_messages(input_bag):
reader = rosbag2_py.SequentialReader()
reader.open(
rosbag2_py.StorageOptions(uri=input_bag, storage_id="mcap"),
rosbag2_py.ConverterOptions(
input_serialization_format="cdr", output_serialization_format="cdr"
)
)
topic_types = reader.get_all_topics_and_types()
def typename(topic_name):
for topic_type in topic_types:
if topic_type.name == topic_name:
return topic_type.type
raise ValueError(f"topic {topic_name} not in bag")
while reader.has_next():
topic, data, timestamp = reader.read_next()
msg_type = get_message(typename(topic))
msg = deserialize_message(data, msg_type)
yield topic, msg, timestamp
Writing to a bag file:
from rclpy.serialization import serialize_message
from std_msgs.msg import String
import rosbag2_py
writer = rosbag2_py.SequentialWriter()
writer.open(
rosbag2_py.StorageOptions(uri="output.mcap", storage_id="mcap"),
rosbag2_py.ConverterOptions(
input_serialization_format="cdr", output_serialization_format="cdr"
)
)
writer.create_topic(
rosbag2_py.TopicMetadata(
name="/topic", type="std_msgs/msg/String", serialization_format="cdr"
)
)
msg = String()
msg.data = "Hello, World!"
writer.write("/topic", serialize_message(msg), timestamp)
Key Features
- SequentialReader: Reads messages from a bag file in chronological order[3][5].
- SequentialWriter: Writes messages to a bag file[2][6].
- Storage Options: Control the storage format (mcap, sqlite3) and location[5].
- Converter Options: Control serialization formats[5].
- Direct access to message data: Enables custom processing without playback[3].
Limitations
- Requires understanding of ROS2 message serialization/deserialization.
- More complex setup compared to CLI tools.
- Limited documentation compared to command-line utilities.
- Requires explicit handling of message types and serialization formats[3][6].
ros2 bag Command Line Tool
While primarily a command-line tool, ros2 bag can be integrated with Python through subprocess calls or launch files.
Usage
Playing back a bag:
import subprocess
def play_bag(bag_path, topics=None):
cmd = ["ros2", "bag", "play", bag_path]
if topics:
cmd.extend(["--topics"] + topics)
subprocess.run(cmd)
Using in a Launch File:
import launch
def generate_launch_description():
return launch.LaunchDescription([
launch.actions.ExecuteProcess(
cmd=["ros2", "bag", "play", "my_bag"],
output="screen"
)
])
Key Commands
- play: Replays recorded data[1][8].
- info: Displays metadata about a bag[1].
- convert: Converts between storage formats, merges or splits bags[1].
Limitations
- Limited programmatic control compared to direct API.
- Cannot process data without publishing to topics in playback mode.
- No direct Python integration without subprocess or launch files[9].
- Less flexible for custom processing workflows.
ros2bag_tools Package
The ros2bag_tools package extends the ros2bag CLI with additional functionality for processing bag data.
Usage
from rosbag2_tools.bag_view import BagView
from rosbag2_tools.data_frame import read_data_frames
# Read bag data as pandas dataframes
bag_view = BagView('path/to/bag')
dfs = read_data_frames(bag_view, {'/topic': ['field1', 'field2']})
Key Features
- Verb Extensions: Adds commands like add, cut, drop, export, extract, plot, etc.[4].
- Data Frame Integration: Convert bag data to pandas DataFrames[4].
- Command Chaining: Process bags with multiple filters in sequence[4].
- Visualization: Plot message data directly[4].
Limitations
- May require additional dependencies like matplotlib for visualization.
- Some verbs may not work with all storage formats.
- Command chaining creates intermediate files unless using the process verb[4].
Integration Examples
Custom Bag Processing Node
import rclpy
from rclpy.node import Node
from rclpy.serialization import deserialize_message
import rosbag2_py
class BagProcessor(Node):
def __init__(self):
super().__init__('bag_processor')
# Open bag file
self.reader = rosbag2_py.SequentialReader()
storage_options = rosbag2_py.StorageOptions(
uri='my_bag',
storage_id='mcap')
converter_options = rosbag2_py.ConverterOptions('', '')
self.reader.open(storage_options, converter_options)
# Process data at a regular interval
self.timer = self.create_timer(0.1, self.process_next)
def process_next(self):
if self.reader.has_next():
topic, data, timestamp = self.reader.read_next()
# Process data here
self.get_logger().info(f'Processed message from {topic}')
Generating Synthetic Data
from rclpy.clock import Clock
from rclpy.serialization import serialize_message
from example_interfaces.msg import Int32
import rosbag2_py
def generate_synthetic_data():
writer = rosbag2_py.SequentialWriter()
storage_options = rosbag2_py.StorageOptions(
uri='synthetic_bag',
storage_id='mcap')
converter_options = rosbag2_py.ConverterOptions('', '')
writer.open(storage_options, converter_options)
topic_info = rosbag2_py.TopicMetadata(
name='synthetic',
type='example_interfaces/msg/Int32',
serialization_format='cdr')
writer.create_topic(topic_info)
time_stamp = Clock().now()
# Generate 100 samples with increasing timestamps
for i in range(100):
msg = Int32()
msg.data = i
writer.write('synthetic', serialize_message(msg), time_stamp.nanoseconds)
time_stamp = time_stamp + Duration(seconds=0.1)
Storage Format Considerations
ROS2 bags support multiple storage formats with different characteristics:
- sqlite3: Traditional format with good compatibility[1].
- mcap: Newer format with better performance and compression options[1][5].
Each format has its own advantages:
# Using sqlite3
storage_options = rosbag2_py.StorageOptions(uri='my_bag', storage_id='sqlite3')
# Using mcap
storage_options = rosbag2_py.StorageOptions(uri='my_bag', storage_id='mcap')
Limitations of ROS2 Bag Processing in Python
- Performance Overhead: Python processing can be slower than C++ for large bags.
- Memory Management: Large bags may cause memory issues without careful streaming.
- Storage Format Compatibility: Not all tools support all storage formats equally.
- Serialization Format Constraints: Must match the serialization format when reading bags.
- Topic Discovery: When recording, auto-discovery of topics can be disabled with
--no-discovery[1].
- Time Handling: Simulation time handling requires special consideration[1].
- Storage Location: By default, bags are saved in the current directory unless specified otherwise[9][10].
Summary
ROS2 provides a rich ecosystem of Python tools for processing recorded bag data, from the low-level rosbag2_py API to high-level extensions like ros2bag_tools. Each approach offers different trade-offs between ease of use, flexibility, and performance. By understanding these tools and their limitations, developers can choose the right approach for their specific bag processing needs.