如何在TensorFlow数字识别中使用自己的手绘图像

2024-05-20 22:04:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些基本的Python代码来创建一个非常基本的神经网络,对MNIST数据集中的手绘数字进行分类。你知道吗

该网络正在工作,我想做一个预测,对一个手绘图像,不是MNIST数据集的一部分。你知道吗

这是我的代码:

import tensorflow as tf

mnist = tf.keras.datasets.mnist # 28x28 images of handwritten digits (0-9)

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

model.compile(optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'])

model.fit(x_train, y_train, epochs=3)

val_loss, val_acc = model.evaluate(x_test, y_test)
print(val_loss, val_acc)

import matplotlib.pyplot as plt

下面是我可以做预测的地方。我想改变代码,以便我可以预测对我自己的手绘图像(标记为“测试”)_文件段“):

predictions = model.predict([x_test])

import numpy as np

print(np.argmax(predictions[0]))

任何想法都会很有帮助!你知道吗


Tags: 代码testimportaddmodellayerstfas
1条回答
网友
1楼 · 发布于 2024-05-20 22:04:17

由于您的模型是在黑白图像上训练的,因此您只有一个通道,需要将图像转换为灰度:

import numpy as np
import cv2

img = cv2.imread('test_image.jpg')
img = cv2.resize(img, (28,28))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = np.reshape(img, [1,28,28])

predictions = model.predict(img)
print(np.argmax(predictions[0]))

相关问题 更多 >