#!/usr/bin/env python
importrosbagimportrospyfromstd_msgs.msgimportHeader# Time offset (30ms)
time_offset=0.10# 30ms = 0.03s
defadjust_timestamp_in_rosbag(input_bag_file,output_bag_file,topic_name):# Open the original bag file and the new bag file
withrosbag.Bag(input_bag_file,'r')asin_bag,rosbag.Bag(output_bag_file,'w')asout_bag:fortopic,msg,tinin_bag.read_messages():# If it's the specified topic, modify the timestamp
iftopic==topic_name:new_time=msg.header.stamp+rospy.Duration(time_offset)# Update the timestamp in the message (if the message contains a Header)
ifhasattr(msg,'header')andhasattr(msg,'header'):msg.header.stamp=new_timeelse:rospy.logwarn(f"Message {topic} does not have a Header, skipping timestamp adjustment")# Write the modified message to the new bag file
out_bag.write(topic,msg,t)rospy.loginfo(f"Timestamps have been offset by {time_offset} seconds. Output file: {output_bag_file}")if__name__=='__main__':# Specify the input and output bag file paths, and the topic name to adjust
input_bag_file='../rosbags/MH_05_difficult.bag'# Input ROS bag file
output_bag_file='../rosbags/'+'MH_05_difficult_offset'+str(int(time_offset*1000))+"ms.bag"# Output ROS bag file
topic_name='/imu0'# The topic name to adjust timestamps for
# Call the function to adjust the timestamps
adjust_timestamp_in_rosbag(input_bag_file,output_bag_file,topic_name)
#!/usr/bin/env python
importrosbagimportmatplotlib.pyplotaspltfromcollectionsimportdefaultdictfromstd_msgs.msgimportHeaderdefvisualize_rosbag_timestamps(bag_file):"""
Visualize timestamps of all topics in a ROS bag file using msg.header.stamp.
"""# Dictionary to store timestamps for each topic
topic_timestamps=defaultdict(list)# Read the bag file
withrosbag.Bag(bag_file,'r')asbag:fortopic,msg,tinbag.read_messages():# Check if the message has a header with stamp field
ifhasattr(msg,'header')andhasattr(msg.header,'stamp'):# Convert the header.stamp (ros::Time) to seconds
timestamp=msg.header.stamp.to_sec()# Store the timestamp for the topic
topic_timestamps[topic].append(timestamp)else:# If no header.stamp, use the default timestamp (from rosbag)
topic_timestamps[topic].append(t.to_sec())# Plot timestamps for each topic
plt.figure(figsize=(10,6))fortopic,timestampsintopic_timestamps.items():plt.plot(timestamps,[topic]*len(timestamps),'o',label=topic)# Configure the plot
plt.title("Timestamps of Messages in ROS Bag (Using header.stamp)")plt.xlabel("Time (seconds)")plt.ylabel("Topics")plt.yticks(range(len(topic_timestamps)),topic_timestamps.keys())plt.legend(loc='upper right',fontsize='small')plt.grid(True)plt.tight_layout()# Show the plot
plt.show()if__name__=='__main__':# Specify the ROS bag file to analyze
bag_file='../rosbags/MH_05_difficult_offset3ms.bag'# Replace with your ROS bag file path
# Visualize timestamps
visualize_rosbag_timestamps(bag_file)