Callback function for sensor_image sensor

asked 2019-05-29 06:07:54 -0500

massyp gravatar image

updated 2019-05-29 06:10:02 -0500

Hello ROS community,

I'm working with a subscriber in python to recover images from camera and I'm trying to save all the images that I received by using the code below. I understand my problem: it is that it save me the same image a lot of time because of the while loop. But when I delete the the while loop it saves me only the last image captured by the camera.

So I don't knew how my callback function exactly. I want to save every received image.

Thank you for your advises at advance

def image_callback(msg):
i = 0 
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:
while(True):
    # Save your OpenCV2 image as a jpeg 
        cv2.imwrite('camera_image'+str(i)+'.png', cv2_img)
    print("image enregistrer num ", str(i))
    i+=1`
edit retag flag offensive close merge delete

Comments

here is the best way :

def image_callback(msg):
global i
print("Received an image!")
try:
# Convert your ROS Image message to OpenCV2
    cv2_img = bridge.imgmsg_to_cv2(msg, "bgr8")
rospy.sleep(1)
except CvBridgeError, e:
    print(e)
else:
exists = os.path.isfile('./camera_image'+str(i)+'.png')

if exists:
    # Save your OpenCV2 image as a png 
    i+=1
        cv2.imwrite('camera_image'+str(i)+'.png', cv2_img)
    print("image enregistrer num ", str(i))
else : 
    cv2.imwrite('camera_image0.png', cv2_img)
    print("image enregistrer num ", str(i))
massyp gravatar image massyp  ( 2019-05-29 08:07:44 -0500 )edit
1

If you have a working solutions, please mark it as the accepted answer.

dasanche gravatar image dasanche  ( 2019-06-08 04:45:37 -0500 )edit

Sorry, But I can't mark, that says me that it is my own solution.

So I think that you can vote. It's a good solution

Thank you.

massyp gravatar image massyp  ( 2019-06-08 05:27:45 -0500 )edit