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)

相关推荐
IT小郭.14 分钟前
使用 Docker Desktop 安装 Neo4j 知识图谱
windows·python·sql·docker·知识图谱·database·neo4j
后青春期的诗go14 分钟前
基于Rust语言的Rocket框架和Sqlx库开发WebAPI项目记录(一)
开发语言·后端·rust
qh0526wy1 小时前
金融接口基方法Python
windows·python·金融
景天科技苑1 小时前
【Rust闭包】rust语言闭包函数原理用法汇总与应用实战
开发语言·后端·rust·闭包·闭包函数·rust闭包·rust闭包用法
史迪仔01121 小时前
Python生成器:高效处理大数据的秘密武器
前端·数据库·python
uyeonashi2 小时前
【Boost搜索引擎】构建Boost站内搜索引擎实践
开发语言·c++·搜索引擎
再睡一夏就好2 小时前
从硬件角度理解“Linux下一切皆文件“,详解用户级缓冲区
linux·服务器·c语言·开发语言·学习笔记
TIF星空3 小时前
【使用 C# 获取 USB 设备信息及进行通信】
开发语言·经验分享·笔记·学习·microsoft·c#
Smile丶凉轩5 小时前
Qt 界面优化(绘图)
开发语言·数据库·c++·qt
reasonsummer6 小时前
【办公类-100-01】20250515手机导出教学照片,自动上传csdn+最大化、最小化Vs界面
开发语言·python