How to save multiple images when subscribing to a node?

asked 2018-01-25 08:22:32 -0600

hassanyf gravatar image

I created a simple function where it subscribes to Kinect V2 IR's camera. I can take one image but when I save multiple using a loop, the camera hangs.

I have used for and while inside the if c==10 but the camera will hang and eventually crash.

I have tried using global variable, but it gives me an error saying Variable referenced before assignment. Can anyone find a solution to this?

mycode.py

#!/usr/bin/python
import roslib
import rospy
import cv2
import sys
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from datetime import datetime
import random


global total

class PositionTracker:
    total = 0
    def __init__(self):   
        global total;       
        # subscribe to kinect image messages
        self.sub = rospy.Subscriber("kinect2/sd/image_ir", Image, self.image_callback, queue_size=1)
        self.bridge = CvBridge()

    def image_callback(self,data):

        total = total + 1
        try:
            cv_image = self.bridge.imgmsg_to_cv2(data)
        except CvBridgeError as e:
            print(e)
        cv2.imshow("Image window", cv_image)
        c=cv2.waitKey(10)%256
        if c == 10:
            h,w=cv_image.shape           
            bitmap=cv2.cv.CreateImage((w,h), cv2.cv.IPL_DEPTH_16S, 1)
            cv2.cv.SaveImage('dataset/hand'+str(total)+'_0'+'.jpg',bitmap)


def main(args):
    PositionTracker()
    rospy.init_node('kinect_tracker')
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("Shutting down")
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main(sys.argv)
edit retag flag offensive close merge delete

Comments

Does the camera also crash if you subscribe to the image via RVIZ?

NEngelhard gravatar imageNEngelhard ( 2018-01-25 08:48:40 -0600 )edit

No, it only crashes inside the def image_calback function

hassanyf gravatar imagehassanyf ( 2018-01-25 09:13:02 -0600 )edit

What exactly does happen? Does the camera-node crash or your node?

NEngelhard gravatar imageNEngelhard ( 2018-01-25 13:06:52 -0600 )edit