当前位置:   article > 正文

【图片分类】基于inception的迁移学习图片分类单(多)张图片测试代码_迁移学习inceptionv3 测试单张图片分类

迁移学习inceptionv3 测试单张图片分类

1.源程序:

最近使用了官方Tensorflow的关于花朵分类迁移学习的代码,想要测试单张或者几张图片的分类识别效果。找了好久。总算是找到了一个可用的程序,贴出来:

  1. import tensorflow as tf
  2. import numpy as np
  3. import glob
  4. import os.path
  5. import tensorflow as tf
  6. import numpy as np
  7. import cv2
  8. # 模型目录
  9. CHECKPOINT_DIR = './ckpt/checkpoints/' #训练后生成的检查点文件夹,在当前工程下。
  10. INCEPTION_MODEL_FILE = './inception_dec_2015/tensorflow_inception_graph.pb'
  11. # inception-v3模型参数
  12. BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0' # inception-v3模型中代表瓶颈层结果的张量名称
  13. JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0' # 图像输入张量对应的名称
  14. # 测试数据
  15. #path = './test/33.jpg' #这里选择一张图片用于测试,该图片属于sunflower类别的花。
  16. #类别字典
  17. strings = ['0005', '0003', '0001', '0002', '0007','0009']
  18. def id_to_string(node_id):
  19. return strings[node_id]
  20. # 读取数据
  21. #image_data = tf.gfile.FastGFile(path, 'rb').read()
  22. # 评估
  23. checkpoint_file = tf.train.latest_checkpoint(CHECKPOINT_DIR)
  24. with tf.Graph().as_default() as graph:
  25. with tf.Session().as_default() as sess:
  26. # 读取训练好的inception-v3模型
  27. with tf.gfile.FastGFile(INCEPTION_MODEL_FILE, 'rb') as f:
  28. graph_def = tf.GraphDef()
  29. graph_def.ParseFromString(f.read())
  30. # 加载inception-v3模型,并返回瓶颈层输出张量和数据输入张量
  31. bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(
  32. graph_def,
  33. return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])
  34. # 使用inception-v3处理图片获取特征向量
  35. #bottleneck_values = sess.run(bottleneck_tensor,{jpeg_data_tensor: image_data})
  36. # 将四维数组压缩成一维数组,由于全连接层输入时有batch的维度,所以用列表作为输入 // add_FC_layer true imagedata
  37. #bottleneck_values = [np.squeeze(bottleneck_values)]
  38. # 加载图和变量(这里我选择的是step=200的图,使用的是绝对路径。)
  39. saver = tf.train.import_meta_graph('ckpt/best_0.987500.ckpt-800.meta')
  40. saver.restore(sess, tf.train.latest_checkpoint('./ckpt/'))
  41. softmax_tensor = sess.graph.get_tensor_by_name('final_training_ops/prob:0')
  42. # 通过名字从图中获取输入占位符 (add_FC_layer input placeholder )
  43. input_x = graph.get_operation_by_name(
  44. 'BottleneckInputPlaceholder').outputs[0]
  45. for root, dirs, files in os.walk('./test/'):
  46. for file in files:
  47. #
  48. image_data = tf.gfile.FastGFile(os.path.join(root, file), 'rb').read()
  49. print(type(image_data))
  50. # 使用inception-v3处理图片获取特征向量
  51. bottleneck_values = sess.run(bottleneck_tensor,{jpeg_data_tensor: image_data}) #resource data process use inceptipnv3
  52. # 将四维数组压缩成一维数组,由于全连接层输入时有batch的维度,所以用列表作为输入 // add_FC_layer true imagedata
  53. bottleneck_values = [np.squeeze(bottleneck_values)]
  54. predictions = sess.run(softmax_tensor, {input_x: bottleneck_values}) #
  55. predictions = np.squeeze(predictions) #
  56. #
  57. image_path = os.path.join(root, file)
  58. print(image_path)
  59. #
  60. top_k = predictions.argsort()[::-1] #从最后一个元素到第一个元素复制一遍 argsort将x中的元素index值 从小到大排列
  61. #print(top_k)
  62. human_string = id_to_string(top_k[0]) #得到对应标签
  63. # for node_id in top_k:
  64. # #
  65. # human_string = id_to_string(node_id)
  66. # #
  67. # score = predictions[node_id]
  68. # print('%s (score = %.5f)' % (human_string, score))
  69. # print()
  70. print('(预测为%s类)' % human_string)
  71. img = cv2.imread(image_path)
  72. cv2.imshow('image', img)
  73. #cv2.waitKey(0)
  74. cv2.destroyAllWindows()

2.场景2  上面场景1是自己从本地传入的图。也就是用了这个函数:

image_data = tf.gfile.FastGFile(os.path.join(root, file), 'rb').read()

现在我需要载入opencv resize 之后得到的path 这个变量。他是numpy数据类型。而上面代码1直接导入运行的是bytes(string)格式。所以需要经过一定的处理,将resize得到的图像转换为能够使用的tf.string格式。试了很多种方式,最终得到了我想要的。

即OpenCV的图像转换为字节字符串的方式为:

如果有一个图像img(这是一个numpy数组),您可以使用以下命令将其转换为字符串:

  1. >>> img_str = cv2.imencode('.jpg', img)[1].tostring()
  2. >>> type(img_str)
  3. 'str'

参考:https://codeday.me/bug/20181211/436854.html

完整代码:

  1. import tensorflow as tf
  2. import numpy as np
  3. import glob
  4. import os.path
  5. import tensorflow as tf
  6. import numpy as np
  7. import cv2
  8. import sys
  9. sys.path.append('/mnt/4T/ycc/cnn mnistdata/personclassify_transfer')
  10. #from io import BytesIO
  11. from PIL import Image
  12. # 模型目录
  13. CHECKPOINT_DIR = '/mnt/4T/ycc/cnn mnistdata/personclassify_transfer/ckpt/checkpoints/' #训练后生成的检查点文件夹,在当前工程下。
  14. INCEPTION_MODEL_FILE = '/mnt/4T/ycc/cnn mnistdata/personclassify_transfer/inception_dec_2015/tensorflow_inception_graph.pb'
  15. # inception-v3模型参数
  16. BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0' # inception-v3模型中代表瓶颈层结果的张量名称
  17. JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0' # 图像输入张量对应的名称
  18. # 测试数据
  19. #path = './test/001.jpg' #这里选择一张图片用于测试,该图片属于sunflower类别的花。
  20. #类别字典
  21. strings = ['0005', '0003', '0001', '0002', '0007','0009']
  22. def id_to_string(node_id):
  23. return strings[node_id]
  24. def predictions(path):
  25. # 读取数据
  26. #image_data = tf.gfile.FastGFile(path, 'rb').read()
  27. #cv2.imshow('draw',path)
  28. # 评估
  29. checkpoint_file = tf.train.latest_checkpoint(CHECKPOINT_DIR)
  30. with tf.Graph().as_default() as graph:
  31. with tf.Session().as_default() as sess:
  32. # 读取训练好的inception-v3模型
  33. with tf.gfile.FastGFile(INCEPTION_MODEL_FILE, 'rb') as f:
  34. graph_def = tf.GraphDef()
  35. graph_def.ParseFromString(f.read())
  36. # 加载inception-v3模型,并返回瓶颈层输出张量和数据输入张量
  37. bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(graph_def,return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])
  38. # 使用inception-v3处理图片获取特征向量
  39. #bottleneck_values = sess.run(bottleneck_tensor,{jpeg_data_tensor: image_data})
  40. # 将四维数组压缩成一维数组,由于全连接层输入时有batch的维度,所以用列表作为输入 // add_FC_layer true imagedata
  41. #bottleneck_values = [np.squeeze(bottleneck_values)]
  42. # 加载图和变量(这里我选择的是step=200的图,使用的是绝对路径。)
  43. saver = tf.train.import_meta_graph('/mnt/4T/ycc/cnn mnistdata/personclassify_transfer/ckpt/best_0.987500.ckpt-800.meta')
  44. saver.restore(sess, tf.train.latest_checkpoint('/mnt/4T/ycc/cnn mnistdata/personclassify_transfer/ckpt/'))
  45. softmax_tensor = sess.graph.get_tensor_by_name('final_training_ops/prob:0')
  46. # 通过名字从图中获取输入占位符 (add_FC_layer input placeholder )
  47. input_x = graph.get_operation_by_name(
  48. 'BottleneckInputPlaceholder').outputs[0]
  49. print("out2=",type(path))
  50. #path这里是从opencv传入的resize过的图像,原始为numpy数据类型,现在需要转换为bytes/string类型
  51. image_data = cv2.imencode('.jpg', path)[1].tostring()
  52. print("out2=",type(image_data))
  53. #image_data = imageBuf.getvalue()
  54. #path=np.asarray(path, np.float32)
  55. #image_data = tf.convert_to_tensor(path, np.float32)
  56. #png_data = tf.placeholder(tf.string, shape=[])
  57. #image_data = tf.image.decode_png(path, channels=3)
  58. # 使用inception-v3处理图片获取特征向量
  59. bottleneck_values = sess.run(bottleneck_tensor,{jpeg_data_tensor: image_data}) #resource data process use inceptipnv3
  60. # 将四维数组压缩成一维数组,由于全连接层输入时有batch的维度,所以用列表作为输入 // add_FC_layer true imagedata
  61. bottleneck_values = [np.squeeze(bottleneck_values)]
  62. predictions = sess.run(softmax_tensor, {input_x: bottleneck_values}) #
  63. predictions = np.squeeze(predictions) #
  64. #
  65. #image_path = os.path.basename(path)
  66. #print(image_path)
  67. #
  68. top_k = predictions.argsort()[::-1] #从最后一个元素到第一个元素复制一遍 argsort将x中的元素index值 从小到大排列
  69. #print(top_k)
  70. human_string = id_to_string(top_k[0]) #得到对应标签
  71. # for node_id in top_k:
  72. # #
  73. # human_string = id_to_string(node_id)
  74. # #
  75. # score = predictions[node_id]
  76. # print('%s (score = %.5f)' % (human_string, score))
  77. # print()
  78. print('(预测为%s类)' % human_string)
  79. # img = cv2.imread(image_path)
  80. # cv2.imshow('image', img)
  81. #cv2.waitKey(0)
  82. return human_string
  83. #cv2.destroyAllWindows()

TIPS:以上的训练测试源码:链接:https://pan.baidu.com/s/16kj68OGYLu0bwQ1Winqm1g   提取码:9eun 
基于inception的迁移学习图片分类单(多)张图片测试代码。训练测试全套源码; 注:数据集格式为flowerdata放到与训练测试代码一个目录下,且数据集里的多个文件夹代表多个类别(例如:以花类别为例子) 

如果有c币也可以下载csdn的支持下,代码打包是一样的。https://download.csdn.net/download/ycc2011/11178612

(csdn已经不能自定义1个币下载了,所以很无奈)

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号