使用Inception v3实现图像识别

约定不等于承诺〃 2023-07-23 10:59 16阅读 0赞

官方相关模型及文件下载:http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz
下载的文件列表:
在这里插入图片描述
里面有训练好的pb模型,以及标签特征对应文件
在这里插入图片描述

载入相关库:

  1. import tensorflow as tf
  2. import os
  3. import numpy as np
  4. import re
  5. from PIL import Image
  6. import matplotlib.pyplot as plt

code:

  1. class NodeLookup(object):
  2. def __init__(self):
  3. #加载对应的分类文件
  4. label_path = "inception_model/imagenet_2012_challenge_label_map_proto.pbtxt"
  5. uid_path = "inception_model/imagenet_synset_to_human_label_map.txt"
  6. self.node_lookup = self.load(label_path, uid_path)
  7. def load(self, label_path, uid_path):
  8. #读取pbtxt文件,按行读取
  9. proto_label_line = tf.gfile.GFile(label_path).readlines()
  10. #将读取的内容以字典的方式存储,key-value
  11. node_to_label_uid = { }
  12. #遍历每一行
  13. for line in proto_label_line:
  14. #去掉换行符
  15. line = line.strip('\n')
  16. #如果每一行以target_class开头:则对应的内容为 target_class: 442
  17. if line.startswith(" target_class:"):
  18. target_class = int(line.split(": ")[1])#442
  19. if line.startswith(" target_class_string:"):
  20. #包含引号
  21. target_class_string = line.split(": ")[1]
  22. # target_class_string: "n01494475",取中间的字母数字部分,不包含引号
  23. node_to_label_uid[target_class] = target_class_string[1:-1]
  24. proto_uid_line = tf.gfile.GFile(uid_path).readlines()
  25. uid_to_label_human = { }
  26. for line in proto_uid_line:
  27. line = line.strip('\n')
  28. #分割
  29. parse_items = line.split("\t")
  30. uid = parse_items[0]
  31. target = parse_items[1]
  32. uid_to_label_human[uid] = target
  33. #uid_to_label_human[parse_items[0]] = parse_items[1]
  34. #重新对应如种类编号442对应类别cat(假设)
  35. node_id_to_name = { }
  36. for key, val in node_to_label_uid.items():
  37. name = uid_to_label_human[val]
  38. node_id_to_name[key] = name
  39. return node_id_to_name
  40. def id_to_string(self, node_id):
  41. if node_id not in self.node_lookup:
  42. return ''
  43. return self.node_lookup[node_id]
  44. #读取模型,重新创建相应的图,固定书写模式
  45. with tf.gfile.GFile("inception_model/classify_image_graph_def.pb",'rb') as f:
  46. graph_def = tf.GraphDef()
  47. graph_def.ParseFromString(f.read())
  48. tf.import_graph_def(graph_def, name="")
  49. with tf.Session() as sess:
  50. softmax_tensor = sess.graph.get_tensor_by_name("softmax:0")
  51. for root, dirs, files in os.walk("images/"):
  52. for file in files:
  53. image_data = tf.gfile.GFile(os.path.join(root, file), 'rb').read()
  54. predict = sess.run(softmax_tensor, { "DecodeJpeg/contents:0":image_data})#图片是jpg格式
  55. predict = np.squeeze(predict)#将结果转为一维数据
  56. print(predict.shape)
  57. image_path = os.path.join(root, file)
  58. print(image_path)
  59. img = Image.open(image_path)
  60. plt.imshow(img)
  61. plt.axis("off")
  62. plt.show()
  63. top_pre = predict.argsort()[-3:][::-1]#升序排列,选择最后三个数据,再倒叙,即降序
  64. node_lookup = NodeLookup()
  65. for node_id in top_pre:
  66. human_string = node_lookup.id_to_string(node_id)
  67. score = predict[node_id]
  68. print("%s (score=%.5f)" %(human_string, score))
  69. print("*************************")

结果:
在这里插入图片描述

bug

1、readline()&readlines(),这里使用readlines(),否则只读取一行数据

  1. ---------------------------------------------------------------------------
  2. IndexError Traceback (most recent call last)
  3. <ipython-input-21-74081abf60d9> in <module>
  4. 74 #对预测结果排序,从小到大排序,取最后几个,[::-1]:对最后的五个概率值取倒叙
  5. 75 top_k = predictions.argsort()[-5:][: :-1]
  6. ---> 76 node_lookup = NodeLookUp()
  7. 77 for node_id in top_k:
  8. 78 #获取分类名称
  9. <ipython-input-21-74081abf60d9> in __init__(self)
  10. 4 label_lookup_path = "inception_model/imagenet_2012_challenge_label_map_proto.pbtxt"
  11. 5 uid_lookup_path = "inception_model/imagenet_synset_to_human_label_map.txt"
  12. ----> 6 self.node_lookup = self.load(label_lookup_path, uid_lookup_path)
  13. 7
  14. 8 #载入数据进行处理
  15. <ipython-input-21-74081abf60d9> in load(self, label_lookup_path, uid_lookup_path)
  16. 19 #用键值对存储数据
  17. 20 uid = parsed_items[0]
  18. ---> 21 human_string = parsed_items[1]
  19. 22 #保存id和字符串为对应的映射关系
  20. 23 uid_to_human[uid] = human_string
  21. IndexError: list index out of range

2、载入模型时没有对其采用二进制读取,‘rb’

  1. ---------------------------------------------------------------------------
  2. UnicodeDecodeError Traceback (most recent call last)
  3. <ipython-input-27-052cb1c2f17f> in <module>
  4. 40 with tf.gfile.GFile("inception_model/classify_image_graph_def.pb") as f:
  5. 41 graph_def = tf.GraphDef()
  6. ---> 42 graph_def.ParseFromString(f.read())
  7. 43 tf.import_graph_def(graph_def, name="")
  8. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 1: invalid start byte

‘r’:默认值,表示从文件读取数据。
‘w’:表示要向文件写入数据,并截断以前的内容
‘a’:表示要向文件写入数据,添加到当前内容尾部
‘r+’:表示对文件进行可读写操作(删除以前的所有数据)
‘r+a’:表示对文件可进行读写操作(添加到当前文件尾部)
‘b’:表示要读写二进制数据

3、未定义,tab,代码格式问题

  1. if line.startswith(" target_class_string:"):
  2. target_class_string = line.split(": ")[1]
  3. node_to_label_uid[target_class] = target_class_string[1:-1]
  4. <ipython-input-28-ecfdf82b86d1> in load(self, label_path, uid_path)
  5. 14 if line.startswith(" target_class_string:"):
  6. 15 target_class_string = line.split(": ")[1]
  7. ---> 16 node_to_label_uid[target_class] = target_class_string
  8. 17
  9. 18 proto_uid_line = tf.gfile.GFile(uid_path).readlines()
  10. UnboundLocalError: local variable 'target_class_string' referenced before assignment

发表评论

表情:
评论列表 (有 0 条评论,16人围观)

还没有评论,来说两句吧...

相关阅读