告别手动截图!用Python脚本从ROS bag文件里精准提取带时间戳的图片(附完整代码)
告别手动截图用Python脚本从ROS bag文件里精准提取带时间戳的图片附完整代码在计算机视觉和机器人研究中从ROS bag文件中高效提取带时间戳的图像数据是构建数据集的关键步骤。传统方法依赖ROS自带工具但常面临提取不完整、时间戳缺失或操作繁琐等问题。本文将分享一个兼容ROS1的Python自动化解决方案支持压缩/非压缩图像消息处理并提供可直接复用的模块化代码。1. 为什么需要自定义提取工具ROS生态中的image_view工具虽然能提取图像但存在三个致命缺陷时间戳丢失提取的图片无法与原始传感器数据严格对齐数量不一致实际提取帧数常少于bag文件记录数格式受限无法灵活处理压缩图像(sensor_msgs/CompressedImage)通过Python脚本直接解析bag文件可以保留精确到微秒级的时间戳确保100%数据完整提取自动适应不同图像编码格式批量处理多个topic数据2. 环境准备与依赖检查2.1 基础环境配置确保系统已安装以下组件# 检查ROS版本需ROS1 Noetic或Melodic rosversion -d # 验证Python环境推荐Python3 python3 --version # 需≥3.6 pip3 list | grep rosbag\|cv-bridge2.2 关键Python库安装# requirements.txt内容 rosbag1.15.15 opencv-contrib-python4.2.0 cv-bridge1.15.0 numpy1.19.0使用pip快速安装pip3 install -r requirements.txt3. 核心代码实现解析3.1 消息类型自动识别处理两种常见图像消息类型from sensor_msgs.msg import Image, CompressedImage def detect_msg_type(bag_file, topic): with rosbag.Bag(bag_file, r) as bag: _, first_msg, _ next(bag.read_messages(topics[topic])) return CompressedImage if CompressedImage in str(type(first_msg)) else Image3.2 带时间戳的图像提取器完整类实现class BagImageExtractor: def __init__(self): self.bridge CvBridge() self.compressed_formats { jpeg: .jpg, png: .png, bmp: .bmp } def _save_image(self, cv_image, save_path, timestamp): timestamp_str {:.6f}.format(timestamp.to_sec()) ext .jpg if len(cv_image.shape) 3 else .png filename f{timestamp_str}{ext} cv2.imwrite(os.path.join(save_path, filename), cv_image) return filename def process_bag(self, bag_file, topics, output_dir): os.makedirs(output_dir, exist_okTrue) results {topic: {count:0, first_ts:None, last_ts:None} for topic in topics} with rosbag.Bag(bag_file, r) as bag: for topic, msg, t in bag.read_messages(topicstopics): try: if CompressedImage in str(type(msg)): np_arr np.frombuffer(msg.data, np.uint8) cv_image cv2.imdecode(np_arr, cv2.IMREAD_COLOR) else: cv_image self.bridge.imgmsg_to_cv2(msg, bgr8) filename self._save_image(cv_image, output_dir, msg.header.stamp) results[topic][count] 1 if not results[topic][first_ts]: results[topic][first_ts] msg.header.stamp results[topic][last_ts] msg.header.stamp except Exception as e: print(fError processing {topic} at {t}: {str(e)}) return results4. 实战应用与高级技巧4.1 批量处理多个bag文件def batch_process(bag_files, config): summary [] for bag_file in bag_files: extractor BagImageExtractor() output_dir os.path.join(config[output_root], os.path.splitext(os.path.basename(bag_file))[0]) result extractor.process_bag(bag_file, config[topics], output_dir) summary.append({ bag_file: bag_file, output_dir: output_dir, result: result }) return summary4.2 时间戳同步策略当需要对齐多个传感器的数据时同步方法精度实现复杂度适用场景硬件触发±1μs高多相机系统ROS消息时间戳±10ms中软件同步设备插值对齐±50ms低后处理分析推荐的时间戳对齐代码片段def align_timestamps(image_ts, target_ts_list, max_offset0.1): aligned_pairs [] target_idx 0 for img_ts in image_ts: while (target_idx len(target_ts_list) - 1 and abs(target_ts_list[target_idx1] - img_ts) abs(target_ts_list[target_idx] - img_ts)): target_idx 1 if abs(target_ts_list[target_idx] - img_ts) max_offset: aligned_pairs.append((img_ts, target_ts_list[target_idx])) return aligned_pairs5. 常见问题解决方案5.1 典型错误排查表错误现象可能原因解决方案ImportError: No module named cv2OpenCV未安装或版本不匹配pip install opencv-pythonROSBagUnindexedExceptionbag文件损坏或未完成录制使用rosbag reindex修复提取的图像全黑压缩格式解析错误检查cv2.imdecode参数时间戳重复消息头未正确设置检查传感器驱动程序配置5.2 性能优化建议对于大型bag文件10GB内存优化模式def read_large_bag(bag_file, chunk_size1000): with rosbag.Bag(bag_file, r) as bag: chunk [] for topic, msg, t in bag.read_messages(): chunk.append((topic, msg, t)) if len(chunk) chunk_size: yield chunk chunk [] if chunk: yield chunk多进程处理from concurrent.futures import ProcessPoolExecutor def parallel_extract(bag_files, workers4): with ProcessPoolExecutor(max_workersworkers) as executor: futures [executor.submit(process_bag, bf) for bf in bag_files] return [f.result() for f in futures]将完整代码保存为rosbag_image_extractor.py后可通过命令行直接运行python3 rosbag_image_extractor.py \ --input recording.bag \ --output ./extracted_images \ --topics /camera/left /camera/right
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2467036.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!