Rosbag to Image
rosbag file에서 image 토픽만 따로 뽑아쓸 때 사용하기 좋은 코드다.
실행 코드
bag_to_images.py
#!/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()
실행 방법
python bag_to_images.py bagfile_경로 image_저장경로 image_topic
ex)
python bag_to_image.py /home/eddy/harddisk_1/husky/camera/2022-12-29-20-31-01.bag /home/eddy/harddisk_1/husky/camera/extracted_image_5 /5/65_camera/pylon_camera_node/image_raw
실행 결과
위와 같이 설정한 경로에 bagfile에 있던 image 토픽이 png 파일로 전부 추출된 것을 확인할 수 있다.
Reference
https://gist.github.com/wngreene/835cda68ddd9c5416defce876a4d7dd9