Skip to content

Instantly share code, notes, and snippets.

@ritiek
Last active November 6, 2022 13:23
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • 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)
@ZER-0-NE
Copy link

Line 23: img = image.img_to_array(img)

@ritiek
Copy link
Author

ritiek commented Jun 19, 2019

Done, thanks!

@SHAHEENGEOLO
Copy link

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

@tharindu326
Copy link

Line 22 : img = image.load_img(folder_path + img, target_size=(img_width, img_height))
your one didnt work for me!!

@ritiek
Copy link
Author

ritiek commented Aug 10, 2019

@tharindu326 Fixed, thanks!

@xaber14
Copy link

xaber14 commented Aug 26, 2019

why i got this error?
OSError: Unable to open file (unable to open file: name = '/model/model.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)

@puneethrj
Copy link

The code could use
img = img/255 after line 24
or
images = images/255 after line 28

@BhagyasriYella
Copy link

Hi,
I have a scenario where I have to predict images into Crack and Non-Crack. I have prepared the model for that and used your code to predict the images, but unable to save them into folders where images with Crack should be saved in "/Crack" folder and images with Non-Crack should be saved in "/Non-Crack" folder.
Can anyone please help me on how to save the predicted images.

@tharindu326
Copy link

@BhagyasriYella

i just copied the code i have used. this is the way to do it! plz rearrange saving formats as you want

model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])

###############change the code as follow ################

    img = image.load_img(filename, target_size=(img_width, img_height))
    img = image.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    classes = model.predict_classes(img, batch_size=16)
    print(classes)
    if classes == 0:
        filename1 = result_negative_folder + "/image_" + str(int(frameId)) + ".jpg"  
        cv2.imwrite(filename1, img)
    elif classes == 1:
        filename2 = result_possitive_folder + "/image_" + str(int(frameId)) + ".jpg"
        cv2.imwrite(filename2, img)

use the directories as follow
result_possitive_folder = 'G:/Uni/7th sem/load_model_test01//Crack'
result_negative_folder = 'G:/Uni/7th sem/load_model_test01//non_Crack'

or if it is a folder inside your code folder (envi), "/crack" and "/non _crack" will enough
Note: use a loop for 'frameId' or else all images will replace!! if not just save by the default image name that you loaded

@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