{"id":2280,"date":"2017-04-17T14:02:57","date_gmt":"2017-04-17T05:02:57","guid":{"rendered":"http:\/\/nantoka.filmm.info\/blog\/?p=2280"},"modified":"2017-07-11T20:59:38","modified_gmt":"2017-07-11T11:59:38","slug":"tensorflow%e3%81%a7opencv","status":"publish","type":"post","link":"https:\/\/nantoka.filmm.info\/blog\/?p=2280","title":{"rendered":"Tensorflow\u3067opencv"},"content":{"rendered":"<p>opencv\u306f\u3044\u3063\u3066\u306a\u304b\u3063\u305f<\/p>\n<p>&nbsp;<\/p>\n<p>http:\/\/qiita.com\/suppy193\/items\/91609e75789e9f458c39<\/p>\n<p>\u3067Opencv2.7\u3044\u308c\u3066<\/p>\n<p>http:\/\/arkouji.cocolog-nifty.com\/blog\/2016\/08\/tensorflowraspb.html<\/p>\n<p>\u3067classfy_image.py\u304c\u306a\u3044\uff08\u305d\u3082\u305d\u3082models\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u304c\u306a\u3044\uff09\u306e\u3067\u3001TensorFlow\u306e\u30bd\u30fc\u30b9\u307f\u3066<\/p>\n<p>nano classify_image.py<\/p>\n<pre class=\"lang:default decode:true \"># Copyright 2015 The TensorFlow Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n#     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\r\n\"\"\"Simple image classification with Inception.\r\n\r\nRun image classification with Inception trained on ImageNet 2012 Challenge data\r\nset.\r\n\r\nThis program creates a graph from a saved GraphDef protocol buffer,\r\nand runs inference on an input JPEG image. It outputs human readable\r\nstrings of the top 5 predictions along with their probabilities.\r\n\r\nChange the --image_file argument to any jpg image to compute a\r\nclassification of that image.\r\n\r\nPlease see the tutorial and website for a detailed description of how\r\nto use this script to perform image recognition.\r\n\r\nhttps:\/\/tensorflow.org\/tutorials\/image_recognition\/\r\n\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport argparse\r\nimport os.path\r\nimport re\r\nimport sys\r\nimport tarfile\r\n\r\nimport numpy as np\r\nfrom six.moves import urllib\r\nimport tensorflow as tf\r\n\r\nFLAGS = None\r\n\r\n# pylint: disable=line-too-long\r\nDATA_URL = 'http:\/\/download.tensorflow.org\/models\/image\/imagenet\/inception-2015-12-05.tgz'\r\n# pylint: enable=line-too-long\r\n\r\n\r\nclass NodeLookup(object):\r\n  \"\"\"Converts integer node ID's to human readable labels.\"\"\"\r\n\r\n  def __init__(self,\r\n               label_lookup_path=None,\r\n               uid_lookup_path=None):\r\n    if not label_lookup_path:\r\n      label_lookup_path = os.path.join(\r\n          FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')\r\n    if not uid_lookup_path:\r\n      uid_lookup_path = os.path.join(\r\n          FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')\r\n    self.node_lookup = self.load(label_lookup_path, uid_lookup_path)\r\n\r\n  def load(self, label_lookup_path, uid_lookup_path):\r\n    \"\"\"Loads a human readable English name for each softmax node.\r\n\r\n    Args:\r\n      label_lookup_path: string UID to integer node ID.\r\n      uid_lookup_path: string UID to human-readable string.\r\n\r\n    Returns:\r\n      dict from integer node ID to human-readable string.\r\n    \"\"\"\r\n    if not tf.gfile.Exists(uid_lookup_path):\r\n      tf.logging.fatal('File does not exist %s', uid_lookup_path)\r\n    if not tf.gfile.Exists(label_lookup_path):\r\n      tf.logging.fatal('File does not exist %s', label_lookup_path)\r\n\r\n    # Loads mapping from string UID to human-readable string\r\n    proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()\r\n    uid_to_human = {}\r\n    p = re.compile(r'[n\\d]*[ \\S,]*')\r\n    for line in proto_as_ascii_lines:\r\n      parsed_items = p.findall(line)\r\n      uid = parsed_items[0]\r\n      human_string = parsed_items[2]\r\n      uid_to_human[uid] = human_string\r\n\r\n    # Loads mapping from string UID to integer node ID.\r\n    node_id_to_uid = {}\r\n    proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()\r\n    for line in proto_as_ascii:\r\n      if line.startswith('  target_class:'):\r\n        target_class = int(line.split(': ')[1])\r\n      if line.startswith('  target_class_string:'):\r\n        target_class_string = line.split(': ')[1]\r\n        node_id_to_uid[target_class] = target_class_string[1:-2]\r\n\r\n    # Loads the final mapping of integer node ID to human-readable string\r\n    node_id_to_name = {}\r\n    for key, val in node_id_to_uid.items():\r\n      if val not in uid_to_human:\r\n        tf.logging.fatal('Failed to locate: %s', val)\r\n      name = uid_to_human[val]\r\n      node_id_to_name[key] = name\r\n\r\n    return node_id_to_name\r\n\r\n  def id_to_string(self, node_id):\r\n    if node_id not in self.node_lookup:\r\n      return ''\r\n    return self.node_lookup[node_id]\r\n\r\n\r\ndef create_graph():\r\n  \"\"\"Creates a graph from saved GraphDef file and returns a saver.\"\"\"\r\n  # Creates graph from saved graph_def.pb.\r\n  with tf.gfile.FastGFile(os.path.join(\r\n      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:\r\n    graph_def = tf.GraphDef()\r\n    graph_def.ParseFromString(f.read())\r\n    _ = tf.import_graph_def(graph_def, name='')\r\n\r\n\r\ndef run_inference_on_image(image):\r\n  \"\"\"Runs inference on an image.\r\n\r\n  Args:\r\n    image: Image file name.\r\n\r\n  Returns:\r\n    Nothing\r\n  \"\"\"\r\n  if not tf.gfile.Exists(image):\r\n    tf.logging.fatal('File does not exist %s', image)\r\n  image_data = tf.gfile.FastGFile(image, 'rb').read()\r\n\r\n  # Creates graph from saved GraphDef.\r\n  create_graph()\r\n\r\n  with tf.Session() as sess:\r\n    # Some useful tensors:\r\n    # 'softmax:0': A tensor containing the normalized prediction across\r\n    #   1000 labels.\r\n    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048\r\n    #   float description of the image.\r\n    # 'DecodeJpeg\/contents:0': A tensor containing a string providing JPEG\r\n    #   encoding of the image.\r\n    # Runs the softmax tensor by feeding the image_data as input to the graph.\r\n    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')\r\n    predictions = sess.run(softmax_tensor,\r\n                           {'DecodeJpeg\/contents:0': image_data})\r\n    predictions = np.squeeze(predictions)\r\n\r\n    # Creates node ID --&gt; English string lookup.\r\n    node_lookup = NodeLookup()\r\n\r\n    top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]\r\n    for node_id in top_k:\r\n      human_string = node_lookup.id_to_string(node_id)\r\n      score = predictions[node_id]\r\n      print('%s (score = %.5f)' % (human_string, score))\r\n\r\n\r\ndef maybe_download_and_extract():\r\n  \"\"\"Download and extract model tar file.\"\"\"\r\n  dest_directory = FLAGS.model_dir\r\n  if not os.path.exists(dest_directory):\r\n    os.makedirs(dest_directory)\r\n  filename = DATA_URL.split('\/')[-1]\r\n  filepath = os.path.join(dest_directory, filename)\r\n  if not os.path.exists(filepath):\r\n    def _progress(count, block_size, total_size):\r\n      sys.stdout.write('\\r&gt;&gt; Downloading %s %.1f%%' % (\r\n          filename, float(count * block_size) \/ float(total_size) * 100.0))\r\n      sys.stdout.flush()\r\n    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\r\n    print()\r\n    statinfo = os.stat(filepath)\r\n    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\r\n  tarfile.open(filepath, 'r:gz').extractall(dest_directory)\r\n\r\n\r\ndef main(_):\r\n  maybe_download_and_extract()\r\n  image = (FLAGS.image_file if FLAGS.image_file else\r\n           os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))\r\n  run_inference_on_image(image)\r\n\r\n\r\nif __name__ == '__main__':\r\n  parser = argparse.ArgumentParser()\r\n  # classify_image_graph_def.pb:\r\n  #   Binary representation of the GraphDef protocol buffer.\r\n  # imagenet_synset_to_human_label_map.txt:\r\n  #   Map from synset ID to a human readable string.\r\n  # imagenet_2012_challenge_label_map_proto.pbtxt:\r\n  #   Text representation of a protocol buffer mapping a label to synset ID.\r\n  parser.add_argument(\r\n      '--model_dir',\r\n      type=str,\r\n      default='\/tmp\/imagenet',\r\n      help=\"\"\"\\\r\n      Path to classify_image_graph_def.pb,\r\n      imagenet_synset_to_human_label_map.txt, and\r\n      imagenet_2012_challenge_label_map_proto.pbtxt.\\\r\n      \"\"\"\r\n  )\r\n  parser.add_argument(\r\n      '--image_file',\r\n      type=str,\r\n      default='',\r\n      help='Absolute path to image file.'\r\n  )\r\n  parser.add_argument(\r\n      '--num_top_predictions',\r\n      type=int,\r\n      default=5,\r\n      help='Display this many predictions.'\r\n  )\r\n  FLAGS, unparsed = parser.parse_known_args()\r\n  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\r\n<\/pre>\n<p>\u3067\u3001<\/p>\n<p>python classify_image.py<\/p>\n<p>\u3084\u3063\u3066<\/p>\n<p>giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca (score = 0.89107)<br \/>\nindri, indris, Indri indri, Indri brevicaudatus (score = 0.00779)<br \/>\nlesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens (score = 0.00296)<br \/>\ncustard apple (score = 0.00147)<br \/>\nearthstar (score = 0.00117)<\/p>\n<p>\u30d1\u30f3\u30c089%\u3000\u30a4\u30f3\u30c9\u30ea\uff08\u30b5\u30eb\uff090.7%\u3001\u30ec\u30c3\u30b5\u30fc\u30d1\u30f3\u30c00.2%\u3001custard apple\uff08\u30ea\u30f3\u30b4\u306e\u4ef2\u9593\uff1f\uff090.14\uff05\u3001\u30a2\u30fc\u30b9\u30b9\u30bf\u30fc\u3063\u3066\u8b0e\u306e\u82b10.11%\u3000\u3058\u3083\u306a\u3044\u3063\u3066\u51fa\u308b<\/p>\n<p>&nbsp;<\/p>\n<p>\u81ea\u5206\u3067\u4f5c\u308b\u53c2\u8003<\/p>\n<p>http:\/\/arkouji.cocolog-nifty.com\/blog\/2016\/08\/tensorflow-76e9.html<\/p>\n<p>\u3053\u306e\u30b5\u30a4\u30c8\u3068\u305d\u3053\u306b\u306e\u3063\u3066\u308b\u53c2\u8003\u30b5\u30a4\u30c8<\/p>\n<p>http:\/\/qiita.com\/khayate\/items\/bb7c61f447b4c579ddd1<\/p>\n<p>&nbsp;<\/p>\n<p>\u308f\u304b\u308a\u3084\u3059\u3044\u89e3\u8aac<\/p>\n<p><iframe class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" title=\"TensorFlow\u3067\u59cb\u3081\u308b\u6df1\u5c64\u5b66\u7fd2\u3000(\uff13)\u6a5f\u68b0\u5b66\u7fd2\u304b\u3089\u6df1\u5c64\u5b66\u7fd2\u306e\u6249\u3092\u958b\u304f - \u3050\u308b\u306a\u3073\u3092\u3061\u3087\u3063\u3068\u826f\u304f\u3059\u308b\u30a8\u30f3\u30b8\u30cb\u30a2\u30d6\u30ed\u30b0\" src=\"https:\/\/hatenablog-parts.com\/embed?url=http%3A%2F%2Fdevelopers.gnavi.co.jp%2Fentry%2Ftensorflow-deeplearning-3#?secret=Awhh4d9h8n\" data-secret=\"Awhh4d9h8n\" scrolling=\"no\" frameborder=\"0\"><\/iframe><\/p>\n<p>WEB\u30a2\u30d7\u30ea\u5316\u3059\u308b<\/p>\n<p><iframe class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" title=\"TensorFlow\u306b\u3088\u308b\u30c7\u30a3\u30fc\u30d7\u30e9\u30fc\u30cb\u30f3\u30b0\u3067\u3001\u30a2\u30a4\u30c9\u30eb\u306e\u9854\u3092\u8b58\u5225\u3059\u308b - \u3059\u304e\u3083\u30fc\u3093\u30e1\u30e2\" src=\"https:\/\/hatenablog-parts.com\/embed?url=http%3A%2F%2Fmemo.sugyan.com%2Fentry%2F20160112%2F1452558576#?secret=jiyka4uqqW\" data-secret=\"jiyka4uqqW\" scrolling=\"no\" frameborder=\"0\"><\/iframe><\/p>\n<p>&nbsp;<\/p>\n<p>\u3044\u308d\u3044\u308d\u5165\u308c\u308b\u306e<\/p>\n<p>http:\/\/qiita.com\/PonDad\/items\/9fbdf4d694f825dd1b6e<\/p>\n","protected":false},"excerpt":{"rendered":"<p>opencv\u306f\u3044\u3063\u3066\u306a\u304b\u3063\u305f &nbsp; http:\/\/qiita.com\/suppy193\/items\/91609e75789e9f458c39 \u3067Opencv2.7\u3044\u308c\u3066 http:\/\/arkouji.cocolo &hellip; <a href=\"https:\/\/nantoka.filmm.info\/blog\/?p=2280\" class=\"more-link\">\u7d9a\u304d\u3092\u8aad\u3080 <span class=\"screen-reader-text\">Tensorflow\u3067opencv<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[41,40,39,48,47],"tags":[],"class_list":["post-2280","post","type-post","status-publish","format-standard","hentry","category-ai","category-deeplearning","category-raspi","category-48","category-47"],"_links":{"self":[{"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=\/wp\/v2\/posts\/2280","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2280"}],"version-history":[{"count":8,"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=\/wp\/v2\/posts\/2280\/revisions"}],"predecessor-version":[{"id":2288,"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=\/wp\/v2\/posts\/2280\/revisions\/2288"}],"wp:attachment":[{"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2280"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2280"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nantoka.filmm.info\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}