ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

ROS Python Save Snapshot from Camera

asked 2015-06-01 06:51:39 -0500

jbak9141 gravatar image

Hi All, I am developing a module in Python to control a Baxter Robot from Rethink Robotics in solving a rubik's cube.

The problem I am having is that there doesn't seem to be any documentation on how to save a snapshot from one of the camera's to a Jpeg file (or any format usable by OpenCV). I currently have a module which I wish to call after saving a snapshot from Baxter's head camera into the working directory, is there a way to automate the capturing of a snapshot in python? I am aware that Imageview lets you save snapshots by right-clicking on the camera feed it opens but I am after code which I can put into a function and call automatically as required.

Any help would be greatly appreciated.

Cheers, J

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2015-06-02 10:17:38 -0500

imcmahon gravatar image

updated 2015-06-02 10:20:23 -0500

I've thrown together this gist on github, which functions as a very basic Python image subscriber & saver:

It creates a ROS subscriber, saves a jpeg on image callback, and then overwrites it on every subsequent callback invocation (~15 Hz for Baxter's cameras).

The important takeaway is the flow from ROS Image -> CvBridge Converter -> OpenCV2 -> JPEG file:

#! /usr/bin/python
# Copyright (c) 2015, Rethink Robotics, Inc.

# Using this CvBridge Tutorial for converting
# ROS images to OpenCV2 images

# Using this OpenCV2 tutorial for saving Images:

# 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!")
        # Convert your ROS Image message to OpenCV2
        cv2_img = bridge.imgmsg_to_cv2(msg, "bgr8")
    except CvBridgeError, e:
        # Save your OpenCV2 image as a jpeg 
        cv2.imwrite('camera_image.jpeg', cv2_img)

def main():
    # 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

if __name__ == '__main__':
edit flag offensive delete link more


would you always use a subscriber to save images? When would a service make sense?

waspinator gravatar image waspinator  ( 2018-01-25 21:20:14 -0500 )edit

Question Tools



Asked: 2015-06-01 06:51:39 -0500

Seen: 8,992 times

Last updated: Jun 02 '15