ros2 hunmle bag 数据包转为图片数据 python版

import os

import cv2

import rosbag2_py

from cv_bridge import CvBridge

from rclpy.serialization import deserialize_message

from rosidl_runtime_py.utilities import get_message

def save_image(image_data, image_count, output_dir):

"""将图像数据保存为文件"""

filename = os.path.join(output_dir, f"image_{image_count:05d}.jpg")

cv2.imwrite(filename, image_data)

print(f"保存图片:{filename}")

def parse_ros2_bag(bag_path, topic_name, output_dir):

"""解析ROS 2 bag文件中的图像数据"""

if not os.path.exists(output_dir):

os.makedirs(output_dir)

创建rosbag2读取器

reader = rosbag2_py.SequentialReader()

storage_options = rosbag2_py.StorageOptions(uri=bag_path, storage_id='sqlite3')

converter_options = rosbag2_py.ConverterOptions('', '')

reader.open(storage_options, converter_options)

获取话题列表

topic_types = reader.get_all_topics_and_types()

type_map = {topic.name: topic.type for topic in topic_types}

print(f"Bag文件中的话题:{list(type_map.keys())}")

检查话题是否存在

if topic_name not in type_map:

print(f"错误:话题 {topic_name} 不存在于 bag 文件中")

return

获取消息类型

msg_type = type_maptopic_name

msg_class = get_message(msg_type)

初始化CvBridge

bridge = CvBridge()

image_count = 0

while reader.has_next():

(topic, data, timestamp) = reader.read_next()

if topic == topic_name:

try:

反序列化字节流为Image消息

image_msg = deserialize_message(data, msg_class)

使用cv_bridge转换消息为OpenCV格式图像

image = bridge.imgmsg_to_cv2(image_msg, "bgr8")

save_image(image, image_count, output_dir)

image_count += 1

except Exception as e:

print(f"跳过无法解析的消息:{e}")

print(f"图片提取完成,共提取 {image_count} 张图片。")

if name == "main":

bag_path = "/home/yao/workspace/data/yao_bag/" # ROS 2 bag 文件路径

topic_name = "/pic_hsp004" # 图像话题名称

output_dir = "output_images" # 保存图片的文件夹

parse_ros2_bag(bag_path, topic_name, output_dir)

相关推荐
键盘上的猫头鹰9 分钟前
【Linux 基础教程(四)】文件内容查看、打包压缩与搜索、重定向管道及环境变量
linux·服务器·python
独挽离人12 分钟前
【无标题】
python
兰令水27 分钟前
leecodecode【回溯子集】【2026.6.4打卡-java版本】
java·开发语言·深度优先
fox_lht29 分钟前
14.3.重构
开发语言·后端·rust
牛油果子哥q1 小时前
【C++ const 】全场景深度精讲:修饰规则、底层常量折叠、指针 / 引用 / 成员函数实战、易错坑点与工程代码实现
开发语言·c++
天天进步20151 小时前
Python全栈项目--社区问答平台
开发语言·python·django
skywalk81631 小时前
Tree-sitter是一个解析器生成器工具和一个增量解析库。它可以为源文件构建具体的语法树,并在编辑源文件时有效地更新语法树
开发语言·编程
噜噜噜阿鲁~1 小时前
python学习笔记 | 12.0、错误、调试和测试
笔记·python·学习
AI视觉网奇1 小时前
Bambu Studio 发现 xx个开放边
开发语言·人工智能·python
qq_458148201 小时前
科大讯飞实时语音识别(rtasr)真实项目踩坑经验总结与手把手教学真实可运行Demo
java·开发语言·websocket·语音识别