因此,我有这段代码,它可以很好地从预定义的主题中读取消息并将其打印到屏幕上。这些书包带有一个rosbag_name.db3 (sqlite)数据库和metadata.yaml文件。
from rosbags.rosbag2 import Reader as ROS2Reader
import sqlite3
from rosbags.serde import deserialize_cdr
import matplotlib.pyplot as plt
import os
import collections
import argparse
parser = argparse.ArgumentParser(description='Extract images from rosbag.')
# input will be the folder containing the .db3 and metadata.yml file
parser.add_argument('--input','-i',type=str, help='rosbag input location')
# run with python filename.py -i rosbag_dir/
args = parser.parse_args()
rosbag_dir = args.input
topic = "/topic/name"
frame_counter = 0
with ROS2Reader(rosbag_dir) as ros2_reader:
ros2_conns = [x for x in ros2_reader.connections]
# This prints a list of all topic names for sanity
print([x.topic for x in ros2_conns])
ros2_messages = ros2_reader.messages(connections=ros2_conns)
for m, msg in enumerate(ros2_messages):
(connection, timestamp, rawdata) = msg
if (connection.topic == topic):
print(connection.topic) # shows topic
print(connection.msgtype) # shows message type
print(type(connection.msgtype)) # shows it's of type string
# TODO
# this is where things crash when it's a custom message type
data = deserialize_cdr(rawdata, connection.msgtype)
print(data)
问题是,我似乎无法理解如何在自定义消息类型中读取。deserialize_cdr为消息类型字段接受一个字符串,但我不清楚如何用路径替换它,或者如何传递自定义消息。
谢谢
发布于 2022-08-22 06:37:50
一种方法是将其声明并以字符串的形式注册到类型系统:
from rosbags.typesys import get_types_from_msg, register_types
MY_CUSTOM_MSG = """
std_msgs/Header header
string foo
"""
register_types(get_types_from_msg(
MY_CUSTOM_MSG, 'my_custom_msgs/msg/MyCustomMsg'))
from rosbags.typesys.types import my_custom_msgs__msg__MyCustomMsg as MyCustomMsg
接下来,使用:
msg_type = MyCustomMsg.__msgtype__
您可以获得可以传递给deserialize_cdr
的消息类型。另外,请参阅这里获取一个快速示例。
另一种方法是直接从消息定义加载它。实际上,您需要阅读该消息。
from pathlib import Path
custom_msg_path = Path('/path/to/my_custom_msgs/msg/MyCustomMsg.msg')
msg_def = custom_msg_path.read_text(encoding='utf-8')
然后按照与上面相同的步骤,从get_types_from_msg()
开始。这个方法的一个更详细的例子是这里。
https://stackoverflow.com/questions/73420147
复制相似问题