Handwritten digit recognition model invokes and predicts

 Call the trained model parameters to predict handwritten digits.

from PIL import Image
import numpy as np
import tensorflow as tf

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)
    # 模型转灰度
    img_arr = np.array(img.convert('L'))

    # *********************图片预处理
    img_arr = 255 - img_arr


    """
    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
    print("img_arr:", img_arr.shape)
    # 升维度
    # 为什么要升维度:由于predict是按照batch作为输入的,在这里batch是1,即我们输入的那张图片,所以应该要升维度1,且该维度在最前面
    x_predict = img_arr[tf.newaxis, ...]
    print("x_predict:", x_predict.shape)
    result = model.predict(x_predict)

    pred = tf.argmax(result, axis=1)

    print('\n')
    tf.print(pred)

A few notes in the code:

        The image loads the trained model, you need to set the shape of the input and convert it to grayscale:

# Redefine the input size so that it is the same as the trained model input, set ANTIALIAS, that is, anti-aliasing

         When predicting, you need to increase the dimension:


 # Why increase the dimension: Since the predict is input according to the batch, here the batch is 1, that is, the picture we input, so the dimension should be increased by 1, and this dimension is at the front

Guess you like

Origin blog.csdn.net/qq_46006468/article/details/119648551