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})")
图像识别001
最新推荐文章于 2026-05-15 13:48:38 发布
本文介绍了如何在Python中使用Keras的VGG16模型进行图像预处理和物体识别,展示了加载预训练模型,处理图像并获取前三个可能类别和概率的过程。

1354

被折叠的 条评论
为什么被折叠?



