Skip to content

Instantly share code, notes, and snippets.

@ritiek
Last active November 6, 2022 13:23
Show Gist options
  • Save ritiek/5fa903f97eb6487794077cf3a10f4d3e to your computer and use it in GitHub Desktop.
Save ritiek/5fa903f97eb6487794077cf3a10f4d3e to your computer and use it in GitHub Desktop.
Keras predicting on all images in a directory
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
import os
# image folder
folder_path = '/path/to/folder/'
# path to model
model_path = '/path/to/saved/model.h5'
# dimensions of images
img_width, img_height = 320, 240
# load the trained model
model = load_model(model_path)
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# load all images into a list
images = []
for img in os.listdir(folder_path):
img = os.path.join(folder_path, img)
img = image.load_img(img, target_size=(img_width, img_height))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
images.append(img)
# stack up images list to pass for prediction
images = np.vstack(images)
classes = model.predict_classes(images, batch_size=10)
print(classes)
@BhagyasriYella
Copy link

@tharindu326

Hey, thanks for the code. My code ran successfully :)

@RamananThiru
Copy link

Thank You for your code please how to plot or show the predicting result as images using pyplot or another library

Did you get any reply regarding it?

@ccwpog
Copy link

ccwpog commented May 22, 2020

Hello,
I have a similar problem like @BhagyasriYella, only that my classifier uses rescaled images. I solved this in the code via

    img /= 255.
    classes = model.predict_classes(img, batch_size=10)
    img *= 255.

However, with the rescaling and without, I do get my original images (.jpg) classified correctly (as seen on the names) but somehow I cannot open them and they are 0KB. Any ideas on why that is?

@fjonabushi
Copy link

Hello,
can you please help me with my issue:
I want to show the results on a table showing the correct and incorrect predictions but after several tries I have not been able to implement the prettytable correctly in your code.
Can you please help me!
Thank you in advance

@sebyo
Copy link

sebyo commented Aug 8, 2020

Hello
can you please help me !
if I want to save the predicted images into a folder ,how should I do it!

@MohitMakadia
Copy link

It worked Thanks..

@veronicanatividade
Copy link

veronicanatividade commented Jul 30, 2021

Thank you for the code! I just had to substitute img_to_array(img) to np.asarray(img), then it worked.

@nitin-rathore08
Copy link

I am getting following error while running above code
AttributeError: 'Model' object has no attribute 'predict_classes'

@Ayanda1993
Copy link

Hello, please help. I am getting this error:

cannot identify image file <_io.BytesIO object at 0x7fbe54eb8090>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment