import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import String
from cv_bridge import CvBridge
import cv2
import numpy as np
import tensorflow as tf
import classify_image


class RosTensorFlow():
    def __init__(self):
        classify_image.maybe_download_and_extract()
        self._session = tf.Session()
        classify_image.create_graph()
        self._cv_bridge = CvBridge()

        self._sub = rospy.Subscriber('/usb_cam/image_raw', Image, self.callback, queue_size=1)
        self._pub = rospy.Publisher('result', String, queue_size=1)
        self.score_threshold = rospy.get_param('~score_threshold', 0.1)
        self.use_top_k = rospy.get_param('~use_top_k', 5)

    def callback(self, image_msg):
        cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, "bgr8")
        # copy from
        # classify_image.py
        image_data = cv2.imencode('.jpg', cv_image)[1].tostring()
        # Creates graph from saved GraphDef.
        softmax_tensor = self._session.graph.get_tensor_by_name('softmax:0')
        predictions = self._session.run(
            softmax_tensor, {'DecodeJpeg/contents:0': image_data})
        predictions = np.squeeze(predictions)
        # Creates node ID --> English string lookup.
        node_lookup = classify_image.NodeLookup()
        top_k = predictions.argsort()[-self.use_top_k:][::-1]
        for node_id in top_k:
            human_string = node_lookup.id_to_string(node_id)
            score = predictions[node_id]
            if score > self.score_threshold:
                rospy.loginfo('%s (score = %.5f)' % (human_string, score))
                self._pub.publish(human_string)

    def main(self):
        rospy.spin()

if __name__ == '__main__':
    classify_image.setup_args()
    rospy.init_node('rostensorflow')
    tensor = RosTensorFlow()
    tensor.main()

[((47, 4, 47, 31), 'classify_image.setup_args', 'classify_image.setup_args', ({}, {}), '()', False, 'import classify_image\n'), ((48, 4, 48, 36), 'rospy.init_node', 'rospy.init_node', ({(48, 20, 48, 35): '"""rostensorflow"""'}, {}), "('rostensorflow')", False, 'import rospy\n'), ((13, 8, 13, 51), 'classify_image.maybe_download_and_extract', 'classify_image.maybe_download_and_extract', ({}, {}), '()', False, 'import classify_image\n'), ((14, 24, 14, 36), 'tensorflow.Session', 'tf.Session', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((15, 8, 15, 37), 'classify_image.create_graph', 'classify_image.create_graph', ({}, {}), '()', False, 'import classify_image\n'), ((16, 26, 16, 36), 'cv_bridge.CvBridge', 'CvBridge', ({}, {}), '()', False, 'from cv_bridge import CvBridge\n'), ((18, 20, 18, 94), 'rospy.Subscriber', 'rospy.Subscriber', (), '', False, 'import rospy\n'), ((19, 20, 19, 67), 'rospy.Publisher', 'rospy.Publisher', (), '', False, 'import rospy\n'), ((20, 31, 20, 71), 'rospy.get_param', 'rospy.get_param', ({(20, 47, 20, 65): '"""~score_threshold"""', (20, 67, 20, 70): '0.1'}, {}), "('~score_threshold', 0.1)", False, 'import rospy\n'), ((21, 25, 21, 57), 'rospy.get_param', 'rospy.get_param', ({(21, 41, 21, 53): '"""~use_top_k"""', (21, 55, 21, 56): '5'}, {}), "('~use_top_k', 5)", False, 'import rospy\n'), ((32, 22, 32, 45), 'numpy.squeeze', 'np.squeeze', ({(32, 33, 32, 44): 'predictions'}, {}), '(predictions)', True, 'import numpy as np\n'), ((34, 22, 34, 49), 'classify_image.NodeLookup', 'classify_image.NodeLookup', ({}, {}), '()', False, 'import classify_image\n'), ((44, 8, 44, 20), 'rospy.spin', 'rospy.spin', ({}, {}), '()', False, 'import rospy\n'), ((40, 16, 40, 74), 'rospy.loginfo', 'rospy.loginfo', ({(40, 30, 40, 73): "('%s (score = %.5f)' % (human_string, score))"}, {}), "('%s (score = %.5f)' % (human_string, score))", False, 'import rospy\n'), ((27, 21, 27, 51), 'cv2.imencode', 'cv2.imencode', ({(27, 34, 27, 40): '""".jpg"""', (27, 42, 27, 50): 'cv_image'}, {}), "('.jpg', cv_image)", False, 'import cv2\n')]