Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Execution: $ rosrun package_name file_name.py directory_name_to_store_information

#! /usr/bin/python

import os
import sys
import cv2
import csv
import rospy, rosbag
import numpy as np
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError

# Verifying output directory where Images and metadata(csv) will be stored

if len(sys.argv) == 2:
    out_dir = sys.argv[1]
    if not os.path.exists(sys.argv[1]):
        os.makedirs(out_dir)

    else:
        print sys.argv[1], 'already exists'
        sys.exit()

else:
    print 'specify output directory'
    sys.exit()

bridge = CvBridge()

def main():

    # Topic name 
    topicName0 = '/topic/image_raw/compressed'

    # Bag file 
    inbag_name ='/Path/2018-05-15-16-42-43.bag'

    bag = rosbag.Bag(inbag_name)

    for topic, msg, t in bag.read_messages():

        if(topic == topicName0 ):
            try:
                # Convert compressed image to RAW
                img = bridge.compressed_imgmsg_to_cv2(msg)

            except CvBridgeError, e:
                print(e)

            else:
                # Writing image to the directory mentioned while executing script
                cv2.imwrite(sys.argv[1]+'/frame_' + str(msg.header.stamp) + '.jpeg', img)

                # Saving metadata information as per requirement
                with open(sys.argv[1]+'/metadata.csv','ab') as f:
                    thewriter = csv.writer(f)
                    thewriter.writerow([str(msg.header.seq),str(msg.header.stamp),os.getcwd()+'/'+sys.argv[1]+'/', 'frame_'+ str(msg.header.stamp) + '.jpeg'])

    bag.close()
    rospy.spin()

if __name__ == "__main__":
    main()