import matplotlib.pyplot as plt
# 导入VGG16模型
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
import numpy as np
model = VGG16(weights="imagenet", include_top=True)
img_path = "image/man.jpg"
img = image.load_img(img_path, target_size=(224, 224)) # 读取图片并将尺寸转换为(224 x 224)
x = image.img_to_array(img) # 将读取的图片转化成
x = np.expand_dims(x, axis=0) # 转换为张量size为(1, 224, 224, 3)
x = preprocess_input(x)
features = model.predict(x) # 预测,取得features,维度为(1, 1000)
# 取得前5个最可能的类别及概率
pred = decode_predictions(features, top=5)[0]
# 整理预测结果
values = []
bar_label = []
for element in pred:
values.append(element[2])
bar_label.append(element[1])
def percent(value):
return "%.2f" % (value * 100)
# 绘图
fig = plt.figure("预测结果")
ax = fig.add_subplot(111)
plt.ylabel("probability")
plt.bar(range(len(values)), values, tick_label=bar_label, width=0.5, fc="g")
plt.title("top-5")
for a, b in zip(range(len(values)), values):
plt.text(a, b + 0.0005, percent(b), ha='center', va='bottom', fontsize=7)
print(percent(b))
plt.show()
深度学习VGG16模型应用
最新推荐文章于 2025-08-17 12:41:09 发布

1481

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



