classify_image.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Simple image classification with Inception.
  16. Run image classification with Inception trained on ImageNet 2012 Challenge data
  17. set.
  18. This program creates a graph from a saved GraphDef protocol buffer,
  19. and runs inference on an input JPEG image. It outputs human readable
  20. strings of the top 5 predictions along with their probabilities.
  21. Change the --image_file argument to any jpg image to compute a
  22. classification of that image.
  23. Please see the tutorial and website for a detailed description of how
  24. to use this script to perform image recognition.
  25. https://tensorflow.org/tutorials/image_recognition/
  26. """
  27. from __future__ import absolute_import
  28. from __future__ import division
  29. from __future__ import print_function
  30. import argparse
  31. import os.path
  32. import re
  33. import sys
  34. import tarfile
  35. import numpy as np
  36. from six.moves import urllib
  37. import tensorflow as tf
  38. FLAGS = None
  39. # pylint: disable=line-too-long
  40. DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
  41. # pylint: enable=line-too-long
  42. class NodeLookup(object):
  43. """Converts integer node ID's to human readable labels."""
  44. def __init__(self,
  45. label_lookup_path=None,
  46. uid_lookup_path=None):
  47. if not label_lookup_path:
  48. label_lookup_path = os.path.join(
  49. FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
  50. if not uid_lookup_path:
  51. uid_lookup_path = os.path.join(
  52. FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')
  53. self.node_lookup = self.load(label_lookup_path, uid_lookup_path)
  54. def load(self, label_lookup_path, uid_lookup_path):
  55. """Loads a human readable English name for each softmax node.
  56. Args:
  57. label_lookup_path: string UID to integer node ID.
  58. uid_lookup_path: string UID to human-readable string.
  59. Returns:
  60. dict from integer node ID to human-readable string.
  61. """
  62. if not tf.gfile.Exists(uid_lookup_path):
  63. tf.logging.fatal('File does not exist %s', uid_lookup_path)
  64. if not tf.gfile.Exists(label_lookup_path):
  65. tf.logging.fatal('File does not exist %s', label_lookup_path)
  66. # Loads mapping from string UID to human-readable string
  67. proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
  68. uid_to_human = {}
  69. p = re.compile(r'[n\d]*[ \S,]*')
  70. for line in proto_as_ascii_lines:
  71. parsed_items = p.findall(line)
  72. uid = parsed_items[0]
  73. human_string = parsed_items[2]
  74. uid_to_human[uid] = human_string
  75. # Loads mapping from string UID to integer node ID.
  76. node_id_to_uid = {}
  77. proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
  78. for line in proto_as_ascii:
  79. if line.startswith(' target_class:'):
  80. target_class = int(line.split(': ')[1])
  81. if line.startswith(' target_class_string:'):
  82. target_class_string = line.split(': ')[1]
  83. node_id_to_uid[target_class] = target_class_string[1:-2]
  84. # Loads the final mapping of integer node ID to human-readable string
  85. node_id_to_name = {}
  86. for key, val in node_id_to_uid.items():
  87. if val not in uid_to_human:
  88. tf.logging.fatal('Failed to locate: %s', val)
  89. name = uid_to_human[val]
  90. node_id_to_name[key] = name
  91. return node_id_to_name
  92. def id_to_string(self, node_id):
  93. if node_id not in self.node_lookup:
  94. return ''
  95. return self.node_lookup[node_id]
  96. def create_graph():
  97. """Creates a graph from saved GraphDef file and returns a saver."""
  98. # Creates graph from saved graph_def.pb.
  99. with tf.gfile.FastGFile(os.path.join(
  100. FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
  101. graph_def = tf.GraphDef()
  102. graph_def.ParseFromString(f.read())
  103. _ = tf.import_graph_def(graph_def, name='')
  104. def run_inference_on_image(image):
  105. """Runs inference on an image.
  106. Args:
  107. image: Image file name.
  108. Returns:
  109. Nothing
  110. """
  111. if not tf.gfile.Exists(image):
  112. tf.logging.fatal('File does not exist %s', image)
  113. image_data = tf.gfile.FastGFile(image, 'rb').read()
  114. # Creates graph from saved GraphDef.
  115. create_graph()
  116. with tf.Session() as sess:
  117. # Some useful tensors:
  118. # 'softmax:0': A tensor containing the normalized prediction across
  119. # 1000 labels.
  120. # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
  121. # float description of the image.
  122. # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
  123. # encoding of the image.
  124. # Runs the softmax tensor by feeding the image_data as input to the graph.
  125. softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
  126. predictions = sess.run(softmax_tensor,
  127. {'DecodeJpeg/contents:0': image_data})
  128. predictions = np.squeeze(predictions)
  129. # Creates node ID --> English string lookup.
  130. node_lookup = NodeLookup()
  131. top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
  132. for node_id in top_k:
  133. human_string = node_lookup.id_to_string(node_id)
  134. score = predictions[node_id]
  135. print('%s (score = %.5f)' % (human_string, score))
  136. def maybe_download_and_extract():
  137. """Download and extract model tar file."""
  138. dest_directory = FLAGS.model_dir
  139. if not os.path.exists(dest_directory):
  140. os.makedirs(dest_directory)
  141. filename = DATA_URL.split('/')[-1]
  142. filepath = os.path.join(dest_directory, filename)
  143. if not os.path.exists(filepath):
  144. def _progress(count, block_size, total_size):
  145. sys.stdout.write('\r>> Downloading %s %.1f%%' % (
  146. filename, float(count * block_size) / float(total_size) * 100.0))
  147. sys.stdout.flush()
  148. filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
  149. print()
  150. statinfo = os.stat(filepath)
  151. print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  152. tarfile.open(filepath, 'r:gz').extractall(dest_directory)
  153. def main(_):
  154. maybe_download_and_extract()
  155. image = (FLAGS.image_file if FLAGS.image_file else
  156. os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))
  157. run_inference_on_image(image)
  158. if __name__ == '__main__':
  159. parser = argparse.ArgumentParser()
  160. # classify_image_graph_def.pb:
  161. # Binary representation of the GraphDef protocol buffer.
  162. # imagenet_synset_to_human_label_map.txt:
  163. # Map from synset ID to a human readable string.
  164. # imagenet_2012_challenge_label_map_proto.pbtxt:
  165. # Text representation of a protocol buffer mapping a label to synset ID.
  166. parser.add_argument(
  167. '--model_dir',
  168. type=str,
  169. default='/tmp/imagenet',
  170. help="""\
  171. Path to classify_image_graph_def.pb,
  172. imagenet_synset_to_human_label_map.txt, and
  173. imagenet_2012_challenge_label_map_proto.pbtxt.\
  174. """
  175. )
  176. parser.add_argument(
  177. '--image_file',
  178. type=str,
  179. default='',
  180. help='Absolute path to image file.'
  181. )
  182. parser.add_argument(
  183. '--num_top_predictions',
  184. type=int,
  185. default=5,
  186. help='Display this many predictions.'
  187. )
  188. FLAGS, unparsed = parser.parse_known_args()
  189. tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)