首先,我们需要导入必要的库和模块:

import numpy as np
from keras.preprocessing import image
from keras.applications.vgg19 import VGG19, preprocess_input

然后,我们需要加载VGG19模型并进行预训练权重加载:

model = VGG19(weights='imagenet')

接下来,我们需要定义一个函数来预测图像的标签:

def predict_label(img_path):
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = model.predict(x)
    predicted_label = np.argmax(preds)
    label_mapping = ['cane', 'cavallo', 'elefante', 'farfalla', 'gallina', 'gatto', 'mucca', 'pecora', 'ragno', 'scoiattolo']
    predicted_label = label_mapping[predicted_label]
    return predicted_label

最后,我们可以使用该函数来预测数据集中的图像标签:

dataset_path = 'path_to_dataset_folder'
predictions = []

for label in label_mapping:
    label_folder = os.path.join(dataset_path, label)
    for img_file in os.listdir(label_folder):
        img_path = os.path.join(label_folder, img_file)
        predicted_label = predict_label(img_path)
        predictions.append((img_path, predicted_label))

以上代码将预测结果存储在predictions列表中,每个元素包含图像路径和预测的标签。你可以根据需要对预测结果进行进一步处理。

使用VGG19模型预测包含十类动物图片的数据集

原文地址: https://www.cveoy.top/t/topic/o9ph 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录