I'm using the mnist dataset of handwritten digits and I am trying to predict a digit that I wrote. The problem is that my digit is of shape (28,28,3) and the expected shape for my neural network is (28,28,1). How can I convert it?
my code:
import tensorflow as to
from tensorflow import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import cv2
data = mnist.load_data()
(x_train, y_train), (x_test, y_test) = data
classes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
x_train = x_train / 255
x_test = x_test / 255
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=(28,28)))
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(10, activation='softmax'))
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
model.fit(x_train, y_train, epochs=7)
test_loss, test_acc = model.evaluate(x_test, y_test)
print('\nTest Loss:', test_loss)
print('Test accuracy:', test_acc)
img = Image.open("7.jpg").convert('L')
img_array = cv2.imread('7.jpg')
new_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
new_array = cv2.resize(new_array, (28,28))
print(new_array.shape)
print(x_test[0].shape)
plt.imshow(new_array, cmap='gray')
plt.show()
predictions = model.predict(new_array)
plt.grid(False)
plt.imshow(new_array, cmap='gray')
plt.title("Prediction: " + classes[np.argmax(predictions)])
plt.show()
cvtColor
. If you want to further reduce the info to black and white (1 channel) threshold the gray output. – PackthreadcvtColor
and/or giving the wrong conversion code. – Packthread