How to predict multiple images from folder in python

Here is the code for the Prediction of multiple images from the folder. But getting the same label(class) for all the images.I'm not able to find out why every image shows the same label.

# import the necessary packages
from tensorflow.keras.models import load_model
import argparse
import pickle
import cv2
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.imagenet_utils import decode_predictions
import numpy as np
import logging, os
import sys 
from keras.preprocessing import image
import tensorflow as tf
import math
import operator
from pathlib import Path

# disable the warnings
logging.disable(logging.WARNING)
os.environ[TF_CPP_MIN_LOG_LEVEL] = 3

image_path = test_image_folder

images = []
    
# load all images into a list
for img in os.listdir(image_path):
        img = os.path.join(image_path, img)
        img = image.load_img(img, target_size=(64,64))
        img = image.img_to_array(img)
        img = np.expand_dims(img, axis=0)
        # normalize the image
        processed_image = np.array(img, dtype=float) / 255.0
        images.append(processed_image)
        
images = np.vstack(images)

# relative paths to the model and labels
model_path = os.path.join(Output, 'VGG_model.h5')
label_file_path = os.path.join(Output, 'labels')

# load the model and the label encoder
model = load_model(model_path)
lb = pickle.loads(open(label_file_path, rb).read())

# make a prediction on the image
images_data = []
filenames = []
for filename in os.listdir(image_path):    
    pred_result = model.predict(images)
    images_data.append(pred_result)
    filenames.append(filename)

#sorts attributes according to confidence score (how probable attribute exists)
top_k = []
pred = [] 
for i in range(len(images_data)):
            rank = images_data[i][0].argsort()[-len(images_data[i][0]):][::-1]
            top_k.append(rank)
            top = top_k[i][:15]
            print(filenames[i])
            for node_id in top:
                human_string = label_file_path[node_id]
                score = images_data[i][0][node_id]
                print('%s (score = %.5f)' % (human_string, score))

Topic predict image-classification classification python

Category Data Science


You are looping on a folder to predict each image -

for filename in os.listdir(image_path):    
    pred_result = model.predict(images)
    images_data.append(pred_result)
    filenames.append(filename)

But the argument of the predict function is not changing. Its a stacked value defined above as -

images = np.vstack(images)

This same prediction is being appended into images_data

Assuming your prediction is not failing, it means every prediction is the prediction on all the images stacked in the images_data.
So, for every iteration for i in range(len(images_data)):
This images_data[i][0] is returning you the 1st prediction only.

Changing to for i in range(len(images_data[0])): and images_data[i] should work


I can't tell but I'd look into these 3 options to tell what's wrong :

  • Image Loading is wrong ? check that each loaded image has different data in it
  • Model is wrong ? check that what is outputed by model.predict actually varies
  • Post Processing is wrong ?

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.