tensorflow09-调用手写识别模型

成功识别
import tensorflow as tf
import numpy as np
from PIL import Image
def fun(image_path):
# 加载模型
model = tf.keras.models.load_model('wirtenuber.h5')
# 加载要识别的图像
image = Image.open(image_path).convert('L') # 转换为灰度图像
image = image.resize((28, 28)) # 调整图像大小
image_array = np.array(image) / 255.0 # 将图像转换为 NumPy 数组,并进行标准化
# image_array = image_array.reshape(1, 28, 28, 1) # 调整数组形状以符合模型输入要求
image_array = image_array.reshape(1, 784)
# 使用模型进行预测
predictions = model.predict(image_array)
predicted_label = np.argmax(predictions[0])
return predicted_label
if __name__ == '__main__':
print(fun("888.png"))
注意训练模型和输入数据参数匹配
例如这里我碰到的问题就是 训练模型为28*28像素的图片灰度图的一维数组
就需要将输入的样本数组 转换为相同类型


浙公网安备 33010602011771号