我如何在此 resnet50 代码上使用函数或循环来预测多个图像(在一个文件夹中)的组件,而不仅仅是一个?

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?

如何对多个图像(在一个文件夹中)执行此操作并将它们放入 Dataframe 中?

这是分析一张图片的代码:

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)

这是输出:

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

如何对多个图像(在一个文件夹中)执行此操作并将它们放入 Dataframe 中?

首先,将分析图像的代码移动到一个函数中。您将 return 放在那里,而不是打印结果:

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)

然后,获取所需文件夹(例如当前目录)中的所有图像:

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

运行所有图片上的函数,得到结果:

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

此结果将是一个列表列表。然后你可以将它移动到 DataFrame。如果您想保留每个结果的图像名称,请改用字典。