【问题标题】:How to write a python code to read data from ".bag" file and write data in bag file runtime如何编写python代码从“.bag”文件中读取数据并在bag文件运行时写入数据
【发布时间】:2017-10-24 19:28:03
【问题描述】:

我已经完成以下代码从 .bag 文件中读取数据

import os
f = open("/Volumes/aj/VLP16_Points_2017-10-24-11-21-21.bag", 'r')
print (f.read())
f.close()

我收到以下错误

Traceback (most recent call last):
  File "/Users/ajinkyabobade/PycharmProjects/storingfiles/storingimage.py", line 11, in <module>
    print (f.read())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 33: invalid start byte

如何消除此错误?另外我如何存储数据运行时间(正在生成包文件?)

【问题讨论】:

    标签: python python-3.x bag


    【解决方案1】:

    在 Python 3 中,open() 使用您的环境来选择合适的编码。如果你确定,用 utf-8 编码的文件你可以忽略无效的字节序列

    with open('/path/to/file', 'r', error='ignore') as f:
        print(f.read())
    

    或者您可以选择正确的编码(如果您的文件不是 utf-8 编码的)

    with open('/path/to/file', 'r', encoding='needed_encoding') as f:
        print(f.read())
    

    另外,open builtin 上的文档可以是 useful

    【讨论】:

    • 谢谢,请问我的包文件是什么类型的编码?
    • @Ajinkya Bobade 如果你使用 Linux 试试file --mime filename
    • 我使用的是 MacOS
    • 我发现 text/plain;字符集=us-ascii。我将代码修改为: open("/Volumes/aj/VLP16_Points_2017-10-24-11-21-21.bag", 'r', encoding='us-ascii') as f: 。我不确定为什么错误仍然存​​在我得到的错误是(UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 33: ordinal not in range(128))
    • @Ajinkya Bobade 看起来您的文件已损坏。无论如何,您都可以使用ignore 参数来阅读它,或者查看它是如何创建的并尝试在那里找到问题。
    【解决方案2】:

    来自https://wiki.ros.org/rosbag/Code%20API

    import rosbag
    bag = rosbag.Bag('test.bag')
    for topic, msg, t in bag.read_messages(topics=['chatter', 'numbers']):
       print(msg)
    bag.close()
    

    【讨论】:

      【解决方案3】:

      您可以使用bagpy 包在 Python 中读取 .bag 文件。可以使用pip安装

      pip install bagpy
      

      简要文档位于https://jmscslgroup.github.io/bagpy/

      以下是示例代码-sn-ps:

      import bagpy
      from bagpy import bagreader
      
      b = bagreader('09-23-59.bag')
      
      # get the list of topics
      print(b.topic_table)
      
      # get all the messages of type velocity
      velmsgs   = b.vel_data()
      veldf = pd.read_csv(velmsgs[0])
      plt.plot(veldf['Time'], veldf['linear.x'])
      
      # quickly plot velocities
      b.plot_vel(save_fig=True)
      
      # you can animate a timeseries data
      bagpy.animate_timeseries(veldf['Time'], veldf['linear.x'], title='Velocity Timeseries Plot')
      
      

      但是,该软件包似乎仍在开发中。

      【讨论】:

        猜你喜欢
        • 2011-12-16
        • 1970-01-01
        • 2019-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        • 2019-07-04
        • 1970-01-01
        相关资源
        最近更新 更多