# coding:utf-8 #!/usr/bin/python # Extract images from a bag file. import sys import os import roslib #roslib.load_manifest(PKG) import rosbag import rospy import decimal import cv2 from sensor_msgs.msg import Image from cv_bridge import CvBridge from cv_bridge import CvBridgeError left_path = str(sys.argv[2])+'/left/' # 左目图像的路径,需提前手动创建,也可以使用程序自动创建 right_path = str(sys.argv[2])+'/right/' depth_path = str(sys.argv[2])+'/depth/' class ImageCreator(): def __init__(self): print(sys.argv[1]) # 创建文件夹 if not os.path.exists(left_path): os.makedirs(left_path) print('创建文件夹',left_path) if not os.path.exists(right_path): os.makedirs(right_path) print('创建文件夹',right_path) if not os.path.exists(depth_path): os.makedirs(depth_path) print('创建文件夹',depth_path) self.bridge = CvBridge() print('提取中...') with rosbag.Bag(sys.argv[1], 'r') as bag: # 读取bag文件,注意设置正确的bag文件路径 for topic,msg,t in bag.read_messages(): if topic == "/mynteye/left/image_color/compressed": # 左目图像的topic /left /mynteye/left/image_color # if topic == "/left": try: # cv_image = self.bridge.imgmsg_to_cv2(msg,"bgr8") # 不压缩的 cv_image = self.bridge.compressed_imgmsg_to_cv2(msg,"bgr8") # /compressed 压缩的 except CvBridgeError as e: print(e) # %.6f表示小数点后带有6位,可根据精确度需要修改 timestr = "%.6f" % msg.header.stamp.to_sec() image_name = timestr + ".jpg" #图像命名:时间戳.png cv2.imwrite(left_path + image_name, cv_image) # 保存图像 elif topic == "/mynteye/right/image_color/compressed": # 右目图像的topic /right # elif topic == "/right": try: cv_image = self.bridge.compressed_imgmsg_to_cv2(msg,"bgr8") except CvBridgeError as e: print(e) # %.6f表示小数点后带有6位,可根据精确度需要修改 timestr = "%.6f" % msg.header.stamp.to_sec() image_name = timestr + ".jpg" #图像命名:时间戳.png cv2.imwrite(right_path + image_name, cv_image) # 保存图像 elif topic == "/mynteye/depth/image_raw/compressed": # 深度图像的topic /depth # elif topic == "/depth": try: cv_image = self.bridge.compressed_imgmsg_to_cv2(msg,"bgr8") except CvBridgeError as e: print(e) # %.6f表示小数点后带有6位,可根据精确度需要修改 timestr = "%.6f" % msg.header.stamp.to_sec() image_name = timestr + ".png" #图像命名:时间戳.png cv2.imwrite(depth_path + image_name, cv_image) # 保存图像 print('提取结束') if __name__ == '__main__': try: image_creator = ImageCreator() except rospy.ROSInterruptException: pass
标签:right,python,image,topic,import,path,解析,rosbag,left From: https://www.cnblogs.com/gooutlook/p/17006723.html