Rosbag to Ros2 bag conversion - ashBabu/Utilities GitHub Wiki

Steps

  • pip install rosbags
  • rosbags-convert --src /path/to/rosbag.bag --dst /path/to/ros2bag_folder # ros2bag_folder will be created automatically
import os
import subprocess
import sys

def convert_rosbags(folder_path):
    # Check if the provided folder path exists
    if not os.path.isdir(folder_path):
        print(f"Error: The folder path '{folder_path}' does not exist.")
        return

    # List all .bag files in the directory
    bag_files = [f for f in os.listdir(folder_path) if f.endswith('.bag')]
    
    if not bag_files:
        print(f"No ROS1 bag files found in the folder '{folder_path}'.")
        return

    # Process each .bag file
    for bag_file in bag_files:
        input_path = os.path.join(folder_path, bag_file)
        output_path = os.path.join(folder_path, os.path.splitext(bag_file)[0] + '_ros2')
        
        # Convert the ROS1 bag to ROS2 bag using rosbags-convert
        command = ['rosbags-convert', input_path, '--dst', output_path]
        
        try:
            subprocess.run(command, check=True)
            print(f"Converted '{bag_file}' to ROS2 format successfully.")
        except subprocess.CalledProcessError as e:
            print(f"Error converting '{bag_file}': {e}")

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python convert_rosbags.py <folder_path>")
    else:
        folder_path = sys.argv[1]
        convert_rosbags(folder_path)