如何讓經過訓練的模型識別我從其他地方提取的圖像?該模型使用 MNIST 數據集進行訓練,模型要識別的圖像是從文檔中提取的手寫數字。使用的庫是tensorflow 2.0、cv2和numpy。據我了解,model.predict()確定其輸入。我的意思是,如果我在那里以某種形式輸入“3”的手寫圖像,它將識別并輸出“3”。同樣,這說model是使用基于這組教程的 MNIST 數據集進行訓練的。假設是,我想知道函數的參數,或者我將如何格式化圖像/圖像集以獲得預期的輸出。如果沒有,我想知道我將如何準確地做到這一點。import cv2import matplotlib.pyplot as pltimport numpy as npimport tensorflow as tffrom tensorflow import keras# Load and prepare the MNIST dataset. Convert the samples from integers to floating-point numbers:(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0def createModel(): # Build the tf.keras.Sequential model by stacking layers. # Choose an optimizer and loss function used for training: model = tf.keras.models.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) return modelmodel = createModel()model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))model.evaluate(x_test, y_test)c = cv2.imread("./3.png", 1)c = c.reshape(-1, 28*28)/255.0# now what?我預計model.predict()會做我需要的。到目前為止,這是我的嘗試:model.predict(c) 輸出 TypeError: predict() missing 1 required positional argument: 'x'model.predict([""], c)輸出ValueError: When using data tensors as input to a model, you should specify the步驟argument.等等。我知道在這一點上我會盲目和錯誤地進入。朝著正確方向邁出的任何一步都值得贊賞。謝謝!編輯:所以我知道輸入圖像c應該是灰度 28x28 甚至在重塑之前,所以我嘗試跳過它。我實現預測時出現的錯誤是:...tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [28,28], In[1]: [784,128] [[{{node dense/MatMul}}]] [Op:__inference_keras_scratch_graph_2593]所以我c = c.reshape(-1, 28*28)/255.0在預測之前使用過,但它從來沒有預測任何數字的正確值。然后我嘗試用它cv2.imshow(str(predicted_value), c)來顯示輸入圖像的樣子。顯示的圖像只是黑色和白色斑點的細線。由于我仍然無法鏈接圖像,因此這里是指向輸出的鏈接。我的問題是,這是否是模型的圖像應該看起來的樣子?或者我可能搞砸了?謝謝!
1 回答

qq_笑_17
TA貢獻1818條經驗 獲得超7個贊
當您的模型使用灰度圖像進行訓練時,它期望輸入圖像是灰度的。RGB 圖像有 3 個通道?;叶葓D像只有 1 個通道。
因此,當加載圖像而不是代表cv2.IMREAD_COLOR的1時,使用對應于cv2.IMREAD_GRAYSCALE的0以灰度模式加載圖像。
(注意:使用-1表示cv2.IMREAD_UNCHANGED有關詳細信息,請參閱此處的 opencv 文檔)
yourimage = cv2.imread("yourimage.png", 0)
對于預測,在重塑后,您可以使用:
predicted_value = np.argmax(model.predict(yourimage))
添加回答
舉報
0/150
提交
取消