armin ariana
armin ariana

Reputation: 125

predicting my own image in cnn using keras

how to predict my own image(in the directory)using cnn in keras after training on MNIST dataset? I know I can use 'model.predict(X_test[:])' to make prediction on test set images but how do I predict my own image?

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.utils import to_categorical
#download mnist data and split into train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
#plot the first image in the dataset
plt.imshow(X_train[0])
X_train = X_train.reshape(60000,28,28,1)
X_test = X_test.reshape(10000,28,28,1)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
y_train[0]
#create model
model = Sequential()
#add model layers
model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(Conv2D(32, kernel_size=3, activation='relu'))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))
#compile model using accuracy as a measure of model performance
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train,validation_data=(X_test, y_test), epochs=1)

Upvotes: 0

Views: 3733

Answers (1)

keineahnung2345
keineahnung2345

Reputation: 2701

You should first read in your image by cv2 and resize it to (28,28). Finally add the batch dimension(0th dimension) and channel dimension(last dimension) before feeding it into the keras model.

import cv2
import numpy as np

img = cv2.imread("your_image.png",0)
img = cv2.resize(img, (28, 28))
img = np.reshape(img, [1, 28, 28, 1])
print(np.argmax(model.predict(img)))

Upvotes: 0

Related Questions