在python中的同一file.csv中写入图像的标签和图像的位置

时间:2018-08-13 06:38:51

标签: python-2.7 csv


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import re
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Vector3
from tf.transformations import euler_from_quaternion, quaternion_from_euler
global yaw
global i
FLAGS = tf.app.flags.FLAGS
# classify_image_graph_def.pb:
#   Binary representation of the GraphDef protocol buffer.
# imagenet_synset_to_human_label_map.txt:
#   Map from synset ID to a human readable string.
# imagenet_2012_challenge_label_map_proto.pbtxt:
#   Text representation of a protocol buffer mapping a label to synset ID.
tf.app.flags.DEFINE_string(
   'model_dir', '/tmp/imagenet',
    """Path to classify_image_graph_def.pb, """
    """imagenet_synset_to_human_label_map.txt, and """
    """imagenet_2012_challenge_label_map_proto.pbtxt.""")
tf.app.flags.DEFINE_string('image_file', '',
                          """Absolute path to image file.""")
tf.app.flags.DEFINE_integer('num_top_predictions', 1,
                            """Display this many predictions.""")
# pylint: disable=line-too-long
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-long
class NodeLookup(object):
  """Converts integer node ID's to human readable labels."""
  def __init__(self,
               label_lookup_path=None,
               uid_lookup_path=None):
    if not label_lookup_path:
      label_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
    if not uid_lookup_path:
      uid_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')
    self.node_lookup = self.load(label_lookup_path, uid_lookup_path)
  def load(self, label_lookup_path, uid_lookup_path):
    """Loads a human readable English name for each softmax node.
    Args:
      label_lookup_path: string UID to integer node ID.
      uid_lookup_path: string UID to human-readable string.
    Returns:
      dict from integer node ID to human-readable string.
    """
    if not tf.gfile.Exists(uid_lookup_path):
      tf.logging.fatal('File does not exist %s', uid_lookup_path)
    if not tf.gfile.Exists(label_lookup_path):
      tf.logging.fatal('File does not exist %s', label_lookup_path)
    # Loads mapping from string UID to human-readable string
    proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
    uid_to_human = {}
    p = re.compile(r'[n\d]*[ \S,]*')
    for line in proto_as_ascii_lines:
      parsed_items = p.findall(line)
      uid = parsed_items[0]
      human_string = parsed_items[2]
      uid_to_human[uid] = human_string
    # Loads mapping from string UID to integer node ID.
    node_id_to_uid = {}
    proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
    for line in proto_as_ascii:
      if line.startswith('  target_class:'):
        target_class = int(line.split(': ')[1])
      if line.startswith('  target_class_string:'):
        target_class_string = line.split(': ')[1]
        node_id_to_uid[target_class] = target_class_string[1:-2]
    # Loads the final mapping of integer node ID to human-readable string
    node_id_to_name = {}
    for key, val in node_id_to_uid.items():
      if val not in uid_to_human:
        tf.logging.fatal('Failed to locate: %s', val)
      name = uid_to_human[val]
      node_id_to_name[key] = name
    return node_id_to_name
  def id_to_string(self, node_id):
    if node_id not in self.node_lookup:
      return ''
    return self.node_lookup[node_id]
def create_graph():
  """Creates a graph from saved GraphDef file and returns a saver."""
  # Creates graph from saved graph_def.pb.
  with tf.gfile.FastGFile(os.path.join(
      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')
def run_inference_on_image(image):
  """Runs inference on an image.
  Args:
    image: Image file name.
  Returns:
    Nothing
  """
  if not tf.gfile.Exists(image):
    tf.logging.fatal('File does not exist %s', image)
  image_data = tf.gfile.FastGFile(image, 'rb').read()
  # Creates graph from saved GraphDef.
  create_graph()
  with tf.Session() as sess:
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})
    predictions = np.squeeze(predictions)
    # Creates node ID --> English string lookup.
    node_lookup = NodeLookup()
    top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
    for node_id in top_k:
      human_string = node_lookup.id_to_string(node_id)
      score = predictions[node_id]
      print('%s (score = %.5f)' % (human_string, score))
      with open("Textspeech.csv", "a") as text_file:
      	text_file.write("\t%s" %format(human_string))
def maybe_download_and_extract():
  """Download and extract model tar file."""
  dest_directory = FLAGS.model_dir
  if not os.path.exists(dest_directory):
    os.makedirs(dest_directory)
  filename = DATA_URL.split('/')[-1]
  filepath = os.path.join(dest_directory, filename)
  if not os.path.exists(filepath):
    def _progress(count, block_size, total_size):
      sys.stdout.write('\r>> Downloading %s %.1f%%' % (
          filename, float(count * block_size) / float(total_size) * 100.0))
      sys.stdout.flush()
    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
    print()
    statinfo = os.stat(filepath)
    print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
  tarfile.open(filepath, 'r:gz').extractall(dest_directory)
def callback1(msg):
    x = msg.pose.pose.position.x
    y = msg.pose.pose.position.y
    rospy.loginfo('X:{}, Y{}'.format(x, y))
'''
def callback2(msg):
    global yaw
    global i
    r = msg.x
    p = msg.y
    yaw = msg.z
    if(i==1):
    	with open("Textspeech.csv", "a") as text_file:	      	
    		text_file.write("\n%5f" % (yaw))
    	i = 2
'''    
def get_rotation (msg):
    global roll, pitch, yaw, i
    orientation_q = msg.pose.pose.orientation
    
    orientation_list = [orientation_q.x, orientation_q.y, orientation_q.z, orientation_q.w]
    (roll, pitch, yaw) = euler_from_quaternion (orientation_list)
    print (yaw)     
    i = 1
    if (i==1):
        with open("Textspeech.csv", "a") as text_file:	      	
            text_file.write("\n%5f" % (yaw))
        
    i = 2
        
def main(_):
  global yaw
  global i
  i = 1
  
  rospy.init_node('test', anonymous=True)
  #rospy.Subscriber("/odom", Odometry, callback1) #If needed for position information
  rospy.Subscriber("/odom", Odometry, get_rotation)
  maybe_download_and_extract()
  image = (FLAGS.image_file if FLAGS.image_file else
           os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))
  run_inference_on_image(image)
#Odometry subscriber
  #rospy.spin()
  
if __name__ == '__main__':
  tf.app.run() 
 我正在尝试使用两个函数将图像的(标签和位置)一起编写,这是我的代码t [ Blockquote ] [1]     原始代码[1]:https://github.com/AbhiRP/Autonomous-Robot-Navigation-using-Deep-Learning-Vision-Landmark-Framework/blob/master/Scripts/classify_image.py我的结果
	      carton
0.342085
0.347670
0.353255
2.513623
2.520255
2.526713
2.533345
2.539803
2.546086
2.555511
2.561445
2.567379
2.573139
2.579073
2.585007
2.591290
2.600715
2.606998
2.613107
2.619041
2.624626
2.629862
2.634749
2.639287
2.646443
2.651679
2.657264
2.663372
2.670179
2.677161
2.684316
2.694614
2.701246
2.707355
2.712940
2.718001
2.722888
2.727601
2.732487
2.740516
2.746450
2.752733
2.759366
2.766172
2.772805
2.779262
2.788163
2.793923
2.799334
2.804570
2.810155
2.816089
2.822372
2.828830
2.838778
2.845236
2.851519	space heater
2.857628
2.863387
2.869147
2.874732
2.883109
2.888694
2.894629
2.900563
2.906846
2.913304
2.919761
2.926219
2.935644
2.941752
2.947687
2.953272
2.958857
2.964442
2.970201
2.979277
2.985560
2.992192
2.998476
3.004759
3.010693
3.016453
3.021863
3.029717
3.034953
3.040189
3.045774
3.051883
3.058166	desk
-0.597775
-0.591667
-0.582940
-0.577355
-0.571944
-0.566185
-0.560425 
 我需要在偏航角给我标签时写下它的值,而其余的值会使它断裂,请帮助我。


0 个答案:

没有答案