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)
@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