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

标签 python tensorflow machine-learning keras deep-learning

我有一些基本的 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

下面是我可以做出预测的地方。我想更改代码,以便可以根据自己的手绘图像(标记为“test_image.jpg”)进行预测:

predictions = model.predict([x_test])

import numpy as np

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

任何想法都会非常有帮助!

最佳答案

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

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]))

关于python - 如何在 TensorFlow 数字识别中使用自己的手绘图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58615611/

相关文章:

python - 在 View django中返回多个值

python - 递归函数中的内存

python - 多输入预训练模型

python - 具有多个输入的 Keras 顺序模型

tensorflow - 构建 tf_estimator 时在tensorflow2.0中遇到错误

python - 根据另一个字段的值验证 Django 模型字段?

python - 根据条件填充数据框时出错

tensorflow - tensorflow 中 tf.losses.log_loss(labels, predictions) 的输入是什么?

machine-learning - Weka ARFF 如何处理每个数据项可以有超过 1 个值的特征/属性

python - 在 DBSCAN 中使用 Mahalanobis 等替代距离度量