Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extract images from a rosbag.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2016 Massachusetts Institute of Technology
"""Extract images from a rosbag.
"""
import os
import argparse
import cv2
import rosbag
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
def main():
"""Extract a folder of images from a rosbag.
"""
parser = argparse.ArgumentParser(description="Extract images from a ROS bag.")
parser.add_argument("bag_file", help="Input ROS bag.")
parser.add_argument("output_dir", help="Output directory.")
parser.add_argument("image_topic", help="Image topic.")
args = parser.parse_args()
print "Extract images from %s on topic %s into %s" % (args.bag_file,
args.image_topic, args.output_dir)
bag = rosbag.Bag(args.bag_file, "r")
bridge = CvBridge()
count = 0
for topic, msg, t in bag.read_messages(topics=[args.image_topic]):
cv_img = bridge.imgmsg_to_cv2(msg, desired_encoding="passthrough")
cv2.imwrite(os.path.join(args.output_dir, "frame%06i.png" % count), cv_img)
print "Wrote image %i" % count
count += 1
bag.close()
return
if __name__ == '__main__':
main()
@peteflorence

This comment has been minimized.

Copy link

commented Feb 27, 2018

great gist @wngreene, and also just found this from googling!

@kyelok

This comment has been minimized.

Copy link

commented Jul 25, 2018

@wngreene @peteflorence I just found this from googling as well lol

@abexultan

This comment has been minimized.

Copy link

commented Sep 4, 2018

Thank you!

@Babaevzhu

This comment has been minimized.

Copy link

commented Dec 12, 2018

good job, thanks!

@GenuineYZR

This comment has been minimized.

Copy link

commented Dec 13, 2018

Thanks, it's cool!

@FYamazaki

This comment has been minimized.

Copy link

commented Feb 8, 2019

Great. Thank you.

@paramaggarwal

This comment has been minimized.

Copy link

commented Feb 26, 2019

If you use ros-perception then just run rosrun image_view extract_images image:=<topic>. Documentation here.

@Akashbaskaran

This comment has been minimized.

Copy link

commented Apr 28, 2019

When I try this out, the images are getting saved as grayscale images. Is there any way I can get rgb images?

@lhoangan

This comment has been minimized.

Copy link

commented May 16, 2019

To export RGB, change desired_encoding to "bgr8", more sophisticated example can be seen here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.