改进该脚本,在txt文件每次输出的开头增加一个数据,该数据是对应话题第一次消息发布时的时间戳
时间: 2024-12-23 09:23:07 浏览: 4
KITTI数据集通过evo转换成tum数据,对应的结果,以及xx.txt的poses文件和times.txt的时间戳文件
为了改进脚本,在每个txt文件开始添加对应主题第一次消息发布的数据,你需要在初始化文件写入之前,存储并检查每个主题第一次接收到的数据的时间戳。以下是更新后的代码:
```python
import rospy
from nav_msgs.msg import Odometry
from rospy.rostime import Time
from datetime import datetime
# 存储首次接收到的数据时间戳
first_timestamps = {
'/Odometry_left': None,
'/Odometry': None,
}
def get_first_timestamp(topic_name):
if topic_name not in first_timestamps or first_timestamps[topic_name] is None:
return "First message time unavailable for " + topic_name
else:
return str(first_timestamps[topic_name])
def robot0_callback(data):
global first_timestamps
if first_timestamps.get('/Odometry_left', None) is None:
first_timestamps['/Odometry_left'] = data.header.stamp.to_sec()
pose = data.pose.pose
timestamp = data.header.stamp.to_sec()
x = pose.position.x
y = pose.position.y
z = pose.position.z
px = pose.orientation.x
py = pose.orientation.y
pz = pose.orientation.z
pw = pose.orientation.w
with open('1.txt', 'a', newline='') as f:
# 在每一行开始写入数据前先写入首次时间戳
f.write(get_first_timestamp('/Odometry_left'))
f.write(" " * (len(str(timestamp)) + 1)) # 确保时间对齐
line = f"{timestamp} {x} {y} {z} {px} {py} {pz} {pw}\n"
f.write(line)
def robot1_callback(data):
global first_timestamps
if first_timestamps.get('/Odometry', None) is None:
first_timestamps['/Odometry'] = data.header.stamp.to_sec()
pose = data.pose.pose
timestamp = data.header.stamp.to_sec()
x = pose.position.x
y = pose.position.y
z = pose.position.z
px = pose.orientation.x
py = pose.orientation.y
pz = pose.orientation.z
pw = pose.orientation.w
with open('2.txt', 'a', newline='') as f:
f.write(get_first_timestamp('/Odometry'))
f.write(" " * (len(str(timestamp)) + 1))
line = f"{timestamp} {x} {y} {z} {px} {py} {pz} {pw}\n"
f.write(line)
# ...其他代码保持不变...
```
现在,当你运行此版本的脚本,每个txt文件都会首先包含各自主题首次接收到的消息时间戳,随后才是后续接收到的数据。
阅读全文