from PIL import Image
import numpy as np
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# 下载参数
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:"))
# 预测过程
# 1.打开图片 Image.open
# 2.转换像素大小+图片类型
# 3.增强处理
# 4.除255.0符合0,1分布
# 5.增加batch维度
for i in range(preNum):
image_path = input("the path of test picture:")
img = Image.open(image_path)
# 原图片为739*942的rgb彩图
print(img)
# 将图片转化为高质量28*28像素的图
img = img.resize((28, 28), Image.ANTIALIAS)
# L代表灰度图像
img_arr = np.array(img.convert('L'))
# 灰度增强
for i in range(28):
for j in range(28):
if img_arr[i][j] < 200:
img_arr[i][j] = 255
else:
img_arr[i][j] = 0
img_arr = img_arr / 255.0
x_predict = img_arr[tf.newaxis, ...]
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)
mnist数据集预测中输入图片的问题
最新推荐文章于 2022-01-29 13:57:46 发布