在单张图片分类的基础上文章进一步研究多张图片的分类:
1)新建predictmultipy.py,输入以下内容
import tensorflow as tf
import numpy as np
import os,glob,cv2
import sys,argparse
from utils.copy import get_file_list
# First, pass the path of the image
def predict_batch(images_dir, phase='jpg'):
file_list = get_file_list(images_dir)#获取文件夹下文件列表
a1=open('result.txt','a+')#将分类结果输入result.txt中,a+追加模式
for file in file_list:
if not file.split('.')[-1] == phase:
continue
print(file)
images = []
image=cv2.imread(os.path.join(images_dir,file),-1)#-1,代表原图输入,0灰度图
image = cv2.resize(image, (128, 128),0,0, cv2.INTER_LINEAR)
images.append(image)
#x = tf.placeholder(name='x'], dtype=tf.float32,shape=[None, 128, 128, 3])
images=np.array(images,dtype=np.uint8)
images=images.astype('float32')
images=np.multiply(images,1.0/255.0)
x_batch = np.reshape(images,[len(images), 128, 128, 3])
with tf.Session()as sess:
saver = tf.train.import_meta_graph('dogs-cats-model.meta')#一个 TensorFlow 图描述了计算的过程. 为了进行计算, 图必须在 会话 里被启动. 会话 将图的 op 分发到诸如 CPU 或 GPU 之类的 设备 上, 同时提供执行 op 的方法
saver.restore(sess, tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()
y_pred = graph.get_tensor_by_name("y_pred:0")
x= graph.get_tensor_by_name("x:0")
y_true = graph.get_tensor_by_name("y_true:0")
y_test_images = np.zeros((1, len(os.listdir('training_data'))))
feed_dict_testing = {x: x_batch, y_true: y_test_images}
results=sess.run(y_pred, feed_dict=feed_dict_testing)
# result is of this format [probabiliy_of_rose probability_of_sunflower]
a1.write(file+str(results)+'\n')
return results
a1.close()
## Let us restore the saved model
if __name__ == "__main__":
images_path='testing_data/dogs'
results=predict_batch(images_path,'jpg')