from keras.preprocessing import image
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
import numpy as np
import tensorflow as tf
# 加载预训练的VGG16模型,这里设置include_top=True表示加载完整模型,包括全连接层
model = VGG16(weights='imagenet', include_top=True)
# 加载图像并进行预处理
img_path = 'mao001.jpeg' # 替换为你的图像路径
img = tf.keras.preprocessing.image.load_img(img_path, target_size=(224, 224)) # 适配VGG16的输入尺寸
x = tf.keras.preprocessing.image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
# 进行物体识别
preds = model.predict(x)
decoded_preds = decode_predictions(preds, top=3)[0] # 解码预测结果,获取前3个可能的类别和概率
# 输出识别结果
print("Predictions:")
for i, (imagenetID, label, score) in enumerate(decoded_preds):
print(f"{i + 1}: {label} ({score:.2f})")