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_map[topic_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)

相关推荐
前端付豪7 分钟前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
这里有鱼汤12 分钟前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
北方有星辰zz15 分钟前
数据结构:栈
java·开发语言·数据结构
源码站~23 分钟前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐
MessiGo28 分钟前
Python 爬虫实战 | 国家医保
python
我是唐青枫37 分钟前
C#.NET NLog 详解
开发语言·c#·.net
chanalbert44 分钟前
Spring 6 源码深度掘金:66+核心原理与高频面试攻坚指南
python·spring·面试
Mr_Xuhhh1 小时前
网络基础(1)
c语言·开发语言·网络·c++·qt·算法
旺旺大力包1 小时前
【JS笔记】JS 和 noodjs 的常见操作(十)
开发语言·javascript·node.js·ecmascript
都叫我大帅哥1 小时前
向量数据库Milvus:非结构化数据的救星,AI开发者的瑞士军刀
java·python