Guest User

Untitled

a guest
Jul 19th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. import rospy, rosbag
  2. import numpy as np
  3. import cv2
  4. import pickle
  5. import argparse
  6.  
  7.  
  8. def image_to_numpy(msg):
  9. """
  10. Convert a sensor_msgs/CompressedImage to numpy array
  11. """
  12. img_np_arr = np.fromstring(msg.data, np.uint8)
  13. img = cv2.imdecode(img_np_arr, cv2.IMREAD_COLOR)
  14. img = np.roll(img, 2, axis=-1) # To get the colors correct
  15.  
  16. return img
  17.  
  18.  
  19. def main(args):
  20. """
  21. Bag to state-action pairs, stored in a pickle file
  22. """
  23. bag = rosbag.Bag(args.bagfile)
  24.  
  25. # Initialize your current action to be 0s
  26. cur_action = (0., 0.)
  27.  
  28. actions = []
  29. images = []
  30. for topic, msg, t in bag.read_messages(topics=[args.img_topic, args.action_topic]):
  31. if topic == args.action_topic:
  32. # Change this line if your action msg is not of type duckietown_msgs/WheelsCmdStamped
  33. cur_action = (msg.vel_left, msg.vel_right)
  34. if topic == args.img_topic:
  35. actions.append(cur_action)
  36.  
  37. img = image_to_numpy(msg)
  38. images.append(img)
  39.  
  40. actions = np.array(actions)
  41. images = np.array(images)
  42.  
  43. with open(args.outfile, "wb") as f:
  44. pickle.dump((images, actions), f)
  45.  
  46. def load(args):
  47. """
  48. Test to make sure you have the right amount of sa pairs
  49. """
  50. with open(args.outfile, "rb") as f:
  51. img, act = pickle.load(f)
  52.  
  53. # Set show_proof to True if you'd like to see the image
  54. if args.show_proof:
  55. from PIL import Image
  56. im = Image.fromarray(img[-1])
  57. im.save('test.png')
  58.  
  59. print('Last 100 Actions', act[-100:])
  60.  
  61. print(img.shape, act.shape)
  62.  
  63. if __name__ == '__main__':
  64. parser = argparse.ArgumentParser(description='Rosbag->Numpy Synchronizer')
  65. parser.add_argument('--bagfile', type=str, help='bagfile name')
  66. parser.add_argument('--outfile', type=str, help='outfile name')
  67. parser.add_argument('--img-topic', type=str, help='image topic')
  68. parser.add_argument('--action-topic', type=str, help='action topic')
  69. parser.add_argument('--show-proof', help='Show proof that it worked', action='store_true')
  70.  
  71. args = parser.parse_args()
  72.  
  73. main(args)
  74. load(args)
Add Comment
Please, Sign In to add comment