bag2csv.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 
5 import rospy
6 import rosbag
7 
8 from optparse import OptionParser
9 import StringIO
10 from datetime import datetime
11 import uuid
12 
13 
14 def message_to_csv(stream, msg, flatten=False):
15  """
16  stream: StringIO
17  msg: message
18  """
19  try:
20  for s in type(msg).__slots__:
21  val = msg.__getattribute__(s)
22  message_to_csv(stream, val, flatten)
23  except:
24  msg_str = str(msg)
25  if msg_str.find(",") is not -1:
26  if flatten:
27  msg_str = msg_str.strip("(")
28  msg_str = msg_str.strip(")")
29  msg_str = msg_str.strip(" ")
30  else:
31  msg_str = "\"" + msg_str + "\""
32  stream.write("," + msg_str)
33 
34 def message_type_to_csv(stream, msg, parent_content_name="", flatten=False):
35  """
36  stream: StringIO
37  msg: message
38  """
39  try:
40  for s in type(msg).__slots__:
41  val = msg.__getattribute__(s)
42  if flatten and type(val) == tuple:
43  for i in range(len(val)):
44  stream.write("," + ".".join([parent_content_name, s, str(i)]))
45  else:
46  stream.write("," + ".".join([parent_content_name, s]))
47  except:
48  stream.write("," + parent_content_name)
49 
50 seq = 0
51 nowtime = datetime.now().strftime("%Y%m%d-%H%M%S")
52 
53 def format_csv_filename(form, topic_name):
54  global seq
55  ret = form.replace('%t', topic_name.replace('/','-'))
56  ret = ret.replace('%s', str(seq))
57  seq += 1
58  ret = ret.replace('%d', nowtime)
59  ret = ret.replace('%u', str(uuid.uuid4()))
60  return ret
61 
62 def bag_to_csv(options, args):
63  try:
64  bag = rosbag.Bag(args[0])
65  streamdict= dict()
66  stime = None
67  if options.start_time:
68  stime = rospy.Time(options.start_time)
69  etime = None
70  if options.end_time:
71  etime = rospy.Time(options.end_time)
72  except Exception as e:
73  rospy.logfatal('failed to load bag file: %s', e)
74  exit(1)
75 
76  try:
77  for topic, msg, time in bag.read_messages(topics=options.topic_names,
78  start_time=stime,
79  end_time=etime):
80  if streamdict.has_key(topic):
81  stream = streamdict[topic]
82  else:
83  stream = open(format_csv_filename(options.output_file_format, topic),'w')
84  streamdict[topic] = stream
85  # header
86  if options.header:
87  stream.write("time")
88  message_type_to_csv(stream, msg, flatten = options.flatten)
89  stream.write('\n')
90 
91  stream.write(datetime.fromtimestamp(time.to_time()).strftime('%Y/%m/%d/%H:%M:%S.%f'))
92  message_to_csv(stream, msg, flatten = options.flatten)
93  stream.write('\n')
94  [s.close for s in streamdict.values()]
95  except Exception as e:
96  rospy.logwarn("fail: %s", e)
97  finally:
98  bag.close()
99 
100 if __name__ == '__main__':
101  rospy.init_node('bag2csv', anonymous=True)
102  parser = OptionParser(usage="%prog [options] bagfile")
103  parser.add_option("-a", "--all", dest="all_topics",
104  action="store_true",
105  help="exports all topics", default=False)
106  parser.add_option("-t", "--topic", dest="topic_names",
107  action="append",
108  help="white list topic names", metavar="TOPIC_NAME")
109  parser.add_option("-O", "--output", dest="output_file_format",
110  help="output file names format\n%t: topic name\n%s: sequential number\n%d: datetime (now)\n%u: uuid\ne.g.: -O jskbag-$t-$d.csv", metavar="DESTINATION")
111  parser.add_option("-s", "--start-time", dest="start_time",
112  help="start time of bagfile", type="float")
113  parser.add_option("-e", "--end-time", dest="end_time",
114  help="end time of bagfile", type="float")
115  parser.add_option("-n", "--no-header", dest="header",
116  action="store_false", default=True,
117  help="no header / flatten array value")
118  parser.add_option("-f", "--flatten", dest="flatten",
119  action="store_true",
120  help="output the list type topic with flatten format", default=False)
121  (options, args) = parser.parse_args()
122 
123  if len(args) != 1:
124  parser.print_help()
125  exit(0)
126 
127  bag_to_csv(options, args)
def message_type_to_csv(stream, msg, parent_content_name="", flatten=False)
Definition: bag2csv.py:34
def format_csv_filename(form, topic_name)
Definition: bag2csv.py:53
def message_to_csv(stream, msg, flatten=False)
Definition: bag2csv.py:14
def bag_to_csv(options, args)
Definition: bag2csv.py:62


jsk_topic_tools
Author(s): Kei Okada , Yusuke Furuta
autogenerated on Tue Feb 6 2018 03:45:19