How to write a python code to read data from “.bag” file and write data in bag file runtime

☆樱花仙子☆ 提交于 2021-02-05 09:40:45

问题


I have done following code to read data from .bag file

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

I am getting the following error

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

How do I remove this error? Also how do I store data run time(as the bag file is being generated?)


回答1:


In Python 3 open() uses your environment to choose an appropriate encoding. If you sure, that file encoded with utf-8 you could ignore invalid byte sequence with

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

Or you could chose right encoding (if your file is non utf-8 encoded) with

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

Also, docs on open builtin could be useful.




回答2:


From 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:


You can use the bagpy package to read the .bag file in Python. It can be installed using pip

pip install bagpy

Brief documentation is at https://jmscslgroup.github.io/bagpy/

Following are example code-snippets:

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')

However, it looks like the package is still under development.



来源:https://stackoverflow.com/questions/46918566/how-to-write-a-python-code-to-read-data-from-bag-file-and-write-data-in-bag-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!