数字图片分类
使用我们之前使用mnsit训练的模型,对手写图片进行实际识别。
本次课程中,需要使用model.predict() 函数,其中函数的输入参数为待测试图片特征,包括图片总数,宽,高。通过训练好的模型,预测我们输入图片的类别。
由于训练时我们使用的是28 * 28的图片,所以在预测时,我们要将图片化为28 * 28的图片。
代码如下:
from PIL import Image
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
model_save_path = './checkpoint/mnist.ckpt'
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')])
# 加载模型参数
model.load_weights(model_save_path)
# 输入需要预测的次数
preNum = int(input("input the number of test pictures:"))
# 进行循环预测
for i in range(preNum):
image_path = input("the path of test picture:")
img = Image.open(image_path)
img = img.resize((28, 28), Image.ANTIALIAS) # 将图片化为28*28的图片。
img_arr = np.array(img.convert('L'))
# 查看图片缩减后用于测试的图片
plt.imshow(img_arr, cmap='gray')
plt.show()
# 由于使用mnist训练集进行训练时,训练集中的图片全是高对比的二值图,
# 所以我们在测试时,也可以将图片改变为只有0和255的高亮度对比图片,提高准确率
for h in range(28):
for j in range(28):
if img_arr[h][j] <= 200:
img_arr[h][j] = 255
else:
img_arr[h][j] = 0
img_arr = img_arr / 255.0 # 归一化
print("img_arr:", img_arr.shape)
x_predict = img_arr[tf.newaxis, ...] # 将输入的二维数组,转换成三维数组,
# 因为神经网络的输入特征shape(图片总数,宽,高)
print("x_predict:", x_predict.shape)
result = model.predict(x_predict) # 获取预测结果
print(result)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)
使用以上代码可以准确的确认出输入图片的类别。可以自己手写图片进行识别,但是要书写规范居中,这样验证准确率会更高。
实验输出结果:首先输入测试次数,再输入测试图片名称。
input the number of test pictures:100
the path of test picture:test.png
输入图片为一张图为9。
得到输出结果:
the path of test picture:test.png
img_arr: (28, 28)
x_predict: (1, 28, 28)
[[1.2422214e-05 3.2100375e-03 1.7562316e-03 2.7691040e-02 2.1994393e-02
1.3691573e-03 2.1526326e-05 4.8365969e-02 2.2982430e-01 6.6575491e-01]]
the path of test picture:[9]
学习使用到的图片,https://github.com/jlff/tf2_notes这里面是别的大佬做的笔记。可以在里面进行下载,包含课程代码和图片。