從rosbag 中解析出圖片資料

Philtell發表於2020-10-15

程式碼如下:

#coding:utf-8

import roslib; 
import rosbag
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from cv_bridge import CvBridgeError

path='/media/data/Data/longPic/' #存放圖片的位置
class ImageCreator():


    def __init__(self):
        self.bridge = CvBridge()
        with rosbag.Bag('long.bag', 'r') as bag:   #要讀取的bag檔案;
            for topic,msg,t in bag.read_messages():
                if topic == "/pylon_camera_node/image_raw":  #影像的topic;
                        try:
                            cv_image = self.bridge.imgmsg_to_cv2(msg,"bgr8")
                        except CvBridgeError as e:
                            print e
                        timestr = "%.6f" %  msg.header.stamp.to_sec()
                        #%.6f表示小數點後帶有6位,可根據精確度需要修改;
                        image_name = timestr+ ".jpg" #影像命名:時間戳.jpg
                        cv2.imwrite(path+image_name, cv_image)  #儲存;


if __name__ == '__main__':

    #rospy.init_node(PKG)

    try:
        image_creator = ImageCreator()
    except rospy.ROSInterruptException:
        pass

相關文章