Search code examples
pythonimagedataframekerasresnet

How can I use a function or loop on this resnet50 code to predict the components of multiple images (within a folder), instead of just one?


How can I do this for multiple images (within a folder) and put them into a Dataframe?

This is the code for analysing one image:

import numpy as np
from keras.preprocessing import image
from keras.applications import resnet50

import warnings
warnings.filterwarnings('ignore')

# Load Keras' ResNet50 model that was pre-trained against the ImageNet database
model = resnet50.ResNet50()

# Load the image file, resizing it to 224x224 pixels (required by this model)
img = image.load_img("rgotunechair10.jpg", target_size=(224, 224))

# Convert the image to a numpy array
x = image.img_to_array(img)

# Add a forth dimension since Keras expects a list of images
x = np.expand_dims(x, axis=0)

# Scale the input image to the range used in the trained network
x = resnet50.preprocess_input(x)

# Run the image through the deep neural network to make a prediction
predictions = model.predict(x)

# Look up the names of the predicted classes. Index zero is the results for the first image.
predicted_classes = resnet50.decode_predictions(predictions, top=9)

image_components = []
for x,y,z in predicted_classes[0]:
    image_components.append(y)
    
print(image_components)

This is the output:

['desktop_computer', 'desk', 'monitor', 'space_bar', 'computer_keyboard', 'typewriter_keyboard', 'screen', 'notebook', 'television']

How can I do this for multiple images (within a folder) and put them into a Dataframe?


Solution

  • First of all, move the code for analyzing the image to a function. Instead of printing the result, you will return it there:

    import numpy as np
    from keras.preprocessing import image
    from keras.applications import resnet50
    
    import warnings
    warnings.filterwarnings('ignore')
    
    def run_resnet50(image_name):
    
        # Load Keras' ResNet50 model that was pre-trained against the ImageNet database
        model = resnet50.ResNet50()
    
        # Load the image file, resizing it to 224x224 pixels (required by this model)
        img = image.load_img(image_name, target_size=(224, 224))
    
        # Convert the image to a numpy array
        x = image.img_to_array(img)
    
        # Add a forth dimension since Keras expects a list of images
        x = np.expand_dims(x, axis=0)
    
        # Scale the input image to the range used in the trained network
        x = resnet50.preprocess_input(x)
    
        # Run the image through the deep neural network to make a prediction
        predictions = model.predict(x)
    
        # Look up the names of the predicted classes. Index zero is the results for the first image.
        predicted_classes = resnet50.decode_predictions(predictions, top=9)
    
        image_components = []
        for x,y,z in predicted_classes[0]:
            image_components.append(y)
    
        return(image_components)
    

    Then, get all images inside the desired folder (for instance, the current directory):

    images_path = '.'
    images = [f for f in os.listdir(images_path) if f.endswith('.jpg')]
    

    Run the function on all images, get the result:

    result = [run_resnet50(img_name) for img_name in images]
    

    This result will be a list of lists. Then you could just move it to a DataFrame. If you want to keep the image name for each result, use a dictionary instead.