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数据集预测中输入图片的问题
本文介绍了一个使用TensorFlow搭建的手写数字识别模型,并演示了如何加载预训练权重,通过输入自定义的手写数字图像进行预测的过程。文章包括图像预处理、模型加载及预测结果输出等关键步骤。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
TensorFlow-v2.15
TensorFlow
TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型






