簡體   English   中英

如何在 TensorFlow 號碼識別中使用自己的手繪圖像

[英]How do I use my own Hand-Drawn Image in TensorFlow Number Recognition

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

任何想法都會非常有幫助!

由於您的 model 是在黑白圖像上訓練的,因此您只有一個通道,您需要將圖像轉換為灰度:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM