Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ROS Image Subscriber / JPEG Saver
#! /usr/bin/python
# Copyright (c) 2015, Rethink Robotics, Inc.
# Using this CvBridge Tutorial for converting
# ROS images to OpenCV2 images
# http://wiki.ros.org/cv_bridge/Tutorials/ConvertingBetweenROSImagesAndOpenCVImagesPython
# Using this OpenCV2 tutorial for saving Images:
# http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html
# rospy for the subscriber
import rospy
# ROS Image message
from sensor_msgs.msg import Image
# ROS Image message -> OpenCV2 image converter
from cv_bridge import CvBridge, CvBridgeError
# OpenCV2 for saving an image
import cv2
# Instantiate CvBridge
bridge = CvBridge()
def image_callback(msg):
print("Received an image!")
try:
# Convert your ROS Image message to OpenCV2
cv2_img = bridge.imgmsg_to_cv2(msg, "bgr8")
except CvBridgeError, e:
print(e)
else:
# Save your OpenCV2 image as a jpeg
cv2.imwrite('camera_image.jpeg', cv2_img)
def main():
rospy.init_node('image_listener')
# Define your image topic
image_topic = "/cameras/left_hand_camera/image"
# Set up your subscriber and define its callback
rospy.Subscriber(image_topic, Image, image_callback)
# Spin until ctrl + c
rospy.spin()
if __name__ == '__main__':
main()
@Binsoma

This comment has been minimized.

Copy link

Binsoma commented Feb 23, 2018

Hi, Is there a way to republish converted jpeg to a certain topic? Using this program as a real-time converter?
Thanks.

@MorganWoods

This comment has been minimized.

Copy link

MorganWoods commented Feb 23, 2018

good job

@utkarshanand

This comment has been minimized.

Copy link

utkarshanand commented Mar 1, 2018

Hey, I tried this code with an autonomous car simulator. I tried to subscribe to a camera topic (encoded-images). I ran the code an it ran but nothing happened. I can't figure out what the problem is. Do you have any suggestions?

@BvEden

This comment has been minimized.

Copy link

BvEden commented Sep 12, 2018

Thank you.

@foemre

This comment has been minimized.

Copy link

foemre commented Oct 5, 2018

I used this code to simulate a pipeline where my robot detects text in a cluttered environment and reads it. I needed images every 1 second so I added a simple rospy.sleep(1) after line 27.

@leader1313

This comment has been minimized.

Copy link

leader1313 commented Oct 23, 2019

I got an error.
I run this program but It doesn't work
only printed

segmentation fault

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.