Skip to content

Instantly share code, notes, and snippets.

@fxprime
Created April 23, 2023 15:52
Show Gist options
  • Save fxprime/783dde91a03a7aa308dd62f9a178efcf to your computer and use it in GitHub Desktop.
Save fxprime/783dde91a03a7aa308dd62f9a178efcf to your computer and use it in GitHub Desktop.
Convert rosbag to video with .avi format, Usage rosbag_to_video.py [ROSBAG.bag] [OUTPUT.avi]
#!/usr/bin/env python
import sys
import rospy
import rosbag
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
def save_images_from_rosbag(rosbag_file, topic_name, output_file):
bag = rosbag.Bag(rosbag_file, 'r')
bridge = CvBridge()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = None
for topic, msg, _ in bag.read_messages(topics=[topic_name]):
if rospy.is_shutdown():
break
try:
img = bridge.imgmsg_to_cv2(msg, 'bgr8')
except CvBridgeError as e:
print(e)
continue
if out is None:
height, width, _ = img.shape
out = cv2.VideoWriter(output_file, fourcc, 30, (width, height))
out.write(img)
out.release()
bag.close()
if __name__ == '__main__':
if len(sys.argv) < 4:
print("Usage: rosbag_to_video.py <rosbag_file> <topic_name> <output_file>")
sys.exit(1)
rosbag_file = sys.argv[1]
topic_name = sys.argv[2]
output_file = sys.argv[3]
save_images_from_rosbag(rosbag_file, topic_name, output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment