欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

rosbag image to cv image

程序员文章站 2022-07-12 10:06:50
...

1.use ros.wiki launch method

roswiki link

2.convert compressed image of bag to cv image

#!/usr/bin/python

# Extract images from a bag file.

#PKG = 'beginner_tutorials'
import roslib;   #roslib.load_manifest(PKG)
import rosbag
import rospy
import cv2
#from sensor_msgs.msg import Image
from sensor_msgs.msg import CompressedImage
from cv_bridge import CvBridge
from cv_bridge import CvBridgeError
import numpy as np
# Reading bag filename from command line or roslaunch parameter.
import os
import sys


class ImageCreator():


	def __init__(self):
		self.bridge = CvBridge()
       	with rosbag.Bag('/home/xxx/rosbag_images/zero.bag', 'r') as bag:  
            for topic,msg,t in bag.read_messages():
                if topic == "/camera/rgb/image_raw_L/compressed": 
					print 'received image of type: "%s"' % msg.format
					np_arr = np.fromstring(msg.data,np.uint8)
					cv_image = cv2.imdecode(np_arr,cv2.IMREAD_COLOR)
					img_file = "/home/xxx/rosbag_images/zero"
					timestr = "%.6f" %  msg.header.stamp.to_sec()
                        
					image_name = timestr+ ".png"
					cv2.imwrite(img_file +"/"+ image_name, cv_image)

if __name__ == '__main__':

    #rospy.init_node(PKG)

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

3. convert compressed image of bag to .avi video

#!/usr/bin/env python

import cv2
import numpy as np
import os
import rosbag
from sensor_msgs.msg import CompressedImage
from cv_bridge import CvBridge
from cv_bridge import CvBridgeError


# SETTINGS FOR SAVING OUTPUT VIDEO
out_file = 'outdoors01.avi'
fourcc_setings = cv2.VideoWriter_fourcc(*'XVID')
out_vid_dims = (640, 480)
fps = 30
out = cv2.VideoWriter(out_file,
                      fourcc=fourcc_setings,
                      fps=fps,
                      frameSize=out_vid_dims,
                      isColor=True)

# ROSBAG SETTINGS
bag_file = 'outdoors01_compressedimage.bag'

# OPEN BAG
bag = rosbag.Bag(bag_file, "r")
messages = bag.read_messages(topics=["/usb_cam/image_raw/compressed"])
num_images = bag.get_message_count(topic_filters=["/usb_cam/image_raw/compressed"])

for topic, msg, t in  bag.read_messages():
    if topic == "/usb_cam/image_raw/compressed":

        # CONVERT MESSAGE TO A NUMPY ARRAY
        np_arr = np.fromstring(msg.data, np.uint8)
        img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)

        if img is not None:
            print ('received image of type: "%s"' % msg.format)
            img = cv2.resize(img, out_vid_dims)

            # SHOW THE IMAGE
            cv2.imshow("rosbag_video", img)

            # SAVE THE FRAME TO THE OUTPUT VIDEO
            out_vid = cv2.resize(img, out_vid_dims)
            out.write(out_vid)

out.release()
cv2.destroyWindow('rosbag_video')
print("done!")
相关标签: ROS使用