我正在尝试获取特定 ROS 消息的时间戳,将其记录在文件中,读取文件并恢复原始时间戳。至今未果。
这是我的代码
import os
import os.path
import rosbag
from sensor_msgs.msg import Image
import rospy
IMG_DIRNAME = '/the/root/to/bags/'
#we get only one published topic time and quit
def main():
rosbag_file = 'thebag.bag'
rosbag_file= os.path.join(IMG_DIRNAME,rosbag_file)
for topic, msg, t in rosbag.Bag(rosbag_file).read_messages():
if topic == '/the/topic/image':
print(".")
return t
if __name__ == '__main__':
try:
time_stamp= main() #I got the time stamp
print("original ",time_stamp)
print(time_stamp)
print(time_stamp.secs)
print(time_stamp.nsecs)
print("recorded ",time_stamp.to_sec())
print(time_stamp.to_sec())
print("just to show ",time_stamp.to_nsec())
ts=time_stamp.to_sec()
#Here we record it in a file
with open("afile.txt",'w') as f:
f.write('{0}\n'.format(ts))
with open("afile.txt",'r') as f:
new_ts=float(f.read())
time_new= rospy.Time.from_sec(new_ts)
print("recovered ", time_new)
print(time_new)
print(time_new.secs)
print(time_new.nsecs)
print("==================================")
print("other record",time_stamp.to_nsec())
print(time_stamp.to_nsec())
tns=time_stamp.to_nsec()
#Here we record it in a file
with open("afile2.txt",'w') as f:
f.write('{0}\n'.format(tns))
with open("afile2.txt",'r') as f:
ff=f.read().strip("\n")
print("read as")
print(ff)
new_tns=float(ff)
print(new_tns)
time_new_ns= rospy.Time(new_tns)
print("recovered",time_new_ns)
print(time_new_ns)
print(time_new_ns.secs)
print(time_new_ns.nsecs)
结果我得到了
.
('original ', rospy.Time[1625151029987577614])
1625151029987577614
1625151029
987577614
('recorded ', 1625151029.9875777)
1625151029.99
('just to show ', 1625151029987577614)
('recovered ', rospy.Time[1625151029990000009])
1625151029990000009
1625151029
990000009
==================================
('other record', 1625151029987577614)
1625151029987577614
read as
1625151029987577614
1.62515102999e+18
('recovered', rospy.Time[1625151029987577600000000000])
1625151029987577600000000000
1625151029987577600
0
所以你可以看到,首先我得到了时间戳(原始)并记录了转换为秒(1625151029.99)。我将它记录到一个文件中(其中记录了该数字),恢复的时间戳与原始时间戳不同(ns 部分从 987577614 变为 990000009)。我想这是由于进行了to_sec
转换
为了纠正这一点,我做了第二部分(在===之后)。我记录了我读取的 nsecs 数(1625151029987577614),首先正确地作为一个字符串,然后作为一个浮点数(以科学计数法显示)但在最后一部分(“恢复”)我不知道如何正确转换这个数字到 ROS 时间。我得到的价值是完全错误的
如何在此处获取原始时间戳?
编辑:我试过
print("recalculated")
tt=rospy.Time( int(new_tns //1000000000), int(new_tns%1000000000))
print("recovered",tt)
print(tt)
print(tt.secs)
print(tt.nsecs)
但是虽然更接近原作了,但还是不明白
recalculated
('recovered', rospy.Time[1625151029987577600])
1625151029987577600
1625151029
987577600
另外,不能是一个更简单和正确的方法吗?