Bogdan  Korecki
Bogdan Korecki

Reputation: 87

Preprocessing of a single image for prediction. ( CNN build and trained with Keras)

Had a lack of understanding how to make a single prediction with existing trained model( keras Sequential.

The preprocessing and training of CNN looked like this: from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale=1./255,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size=(64, 64),
                                                 batch_size=32,
                                                 class_mode='binary')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size=(64, 64),
                                            batch_size=32,
                                            class_mode='binary')

classifier.fit_generator(training_set,
                         steps_per_epoch=8000,
                         epochs=25,
                         validation_data=test_set,
                         validation_steps=2000)

As the predict_generator did not work I stucked...

Upvotes: 2

Views: 3609

Answers (2)

Sudhirln92
Sudhirln92

Reputation: 119

import numpy as np
from keras.preprocessing import image

test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size(64,64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image,axis=0)
result = classifier.predict(test_image)
training_set.class_indices

Upvotes: 3

Bogdan  Korecki
Bogdan Korecki

Reputation: 87

After some googling I found that single image is better to preprocess with opencv, so went to its documentation, installed on mac via terminal( using conda).

conda install opencv

Next in code tried this:

import cv2
import numpy as np

predict_datagen = ImageDataGenerator(rescale=1./255)

img1 = cv2.imread('path_to_image/img_1.jpg')
img1 = cv2.resize(img1, (64, 64))

Knowing that model's image input shape was (64, 64, 3) after resizing I checked if the shape matches with

print(img1.shape)

It went out that all was good so I needed to add dimension to match model's requirements, that I figured out after receiving ValueError:

ValueError: Error when checking : expected conv2d_1_input to have 4 dimensions, but got array with shape (64, 64, 3)

So the image was reshaped:

img1 = np.array(img1).reshape((1, 64, 64, 3))#do not miss the order in tuple

After that I received the image of a needed shape and size and ready for a single prediction with predict method.

Upvotes: 1

Related Questions