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



如何为多个图像(在一个文件夹内)做到这一点,并将它们放入一个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']

我怎么能做到这对多个图像(在一个文件夹内),并把它们放入一个数据框架?

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

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。如果您想保留每个结果的图像名称,请使用字典。

最新更新