How To Predict A Single Image With Keras Imagedatagenerator?
Solution 1:
When you wish to predict a single image, you can use the following code.
It returns a list of probabilities of each class based on how the folders (classes) in your train dataset were arranged. So the first index of the returned list is the first folder (or class) in your train dataset and so on. The index with the highest probability is your predicted class.
from keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator
from keras.applications.vgg16 import preprocess_input
#load the image
my_image = load_img('your_single_image.jpeg', target_size=(224, 224))
#preprocess the image
my_image = img_to_array(my_image)
my_image = my_image.reshape((1, my_image.shape[0], my_image.shape[1], my_image.shape[2]))
my_image = preprocess_input(my_image)
#make the prediction
prediction = model.predict(my_image)
You can return a much clearer result by rounding the results to whole numbers using the list comprehension below.
import numpy as np
[np.round(x) for x in prediction]
The element with index 1 is your predicted class.
Solution 2:
The image data generator looks at the directory you specify and searches for sub directories within that directory that specify the classes. So create a directory called './single_prediction. Within that directory create a single sub directory call it test. Within that sub directory named test place the images that you want to test. Alternatively you can write some python code to produce the pre-processed images. Create a directory called test and place your images in it. I have not tested it but the code below should work.
import cv2
import numpy as np
import os
data_list=[]
dir=r'c:\test'
test_list=os.listdir(dir) # create a list of the files in the directory
batch_size=len(test_list) # determine number of files to processfor f in test_list: # iterate through the files
fpath=os.path.join (dir, f) # create path to the image file
img=cv2.imread(fpath) # read image using cv2
img=cv2.resize(img, (224,224)) # resize the image
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # cv2 creates bgr images, convert to rgb images
img=tf.keras.applications.vgg16.preprocess_input(img) # apply the Vgg16 preprocess function
data_list.append(img) # append processed image to the list
data=np.array(data_list)/255# convert to an np array and rescale imagesprint (data.shape, batch_size)
predictions=model.predict(data,batch_size=batch_size, verbose=0 )
trials=len (predictions)
for i inrange(0,trials):
predicted_class=predictions[i].argmax() # get index of highest probabilityprint (test_list[i], predicted_class) # print file name and class prediction
Post a Comment for "How To Predict A Single Image With Keras Imagedatagenerator?"