有时候需要处理ROS录制的.bag中每一条信息。若使用发布和订阅的方法容易遗漏信息,无法达到要求。本文提供一种基于python和opencv的.bag文件转图片并保存的方法,主要利用了rosbag和cv_bridge两个库,精简了代码使其易于理解和使用。
import rosbag
import cv2
from cv_bridge import CvBridge
image_path = './images/'
bag_path = './image.bag'
topic_name = '/camera/left/image_raw'
bridge = CvBridge()
with rosbag.Bag(bag_path, 'r') as bag:
for topic,msg,t in bag.read_messages():
if topic == topic_name:
cv_image = bridge.imgmsg_to_cv2(msg,"bgr8")
timestr = "%.6f" % msg.header.stamp.to_sec()
image_name = timestr+ ".jpg"
cv2.imwrite(image_path+image_name, cv_image)