I'm trying to create the NN using example on Tensorflow and feed it my own hand-written digit to predict right label but shape of array doesn't allow me to do this.
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
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=5)
model.evaluate(x_test, y_test)
path = 'C:/Users/pewdu/Desktop/third.jpg'
img = cv2.imread(path)
new_img = cv2.resize(img, (28, 28))
new_img = new_img / 255.0
print(new_img.shape) # it equals to (28,28,3)
prediction = model.predict(new_img)
So the error is:
ValueError: Error when checking input: expected flatten_7_input to have shape (28, 28) but got array with shape (28, 3)
The Error
message says it all.
The model you initialized expects data in a N x W x H
format where,
When you are reading the image using cv2.imread()
, you can see that the image size is given in W x H x C
format where,
Your model is expecting a grayscale normalized image. And since you are sending only one image (single example), you need to reshape your image array by adding an axis at the front.
img = cv2.imread(path)
new_img = cv2.resize(img, (28, 28))
new_img = new_img[:,:,0] / 255.0 # Take only first channel and normalize
new_img = np.expand_dims(new_img, axis=0) # Adding the dimension
print(new_img.shape) # it equals to (1, 28, 28)
prediction = model.predict(new_img)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.