#导入库
import tensorflow.keras.applications.vgg19 as vgg19
import tensorflow.keras.preprocessing.image as imagepre
from torchvision import models
#加载预训练模型
model = vgg19.VGG19(weights = 'C:/Users/yeahamen/AppData/Local/Programs/Python/Python310/Lib/site-packages/keras/models/vgg19_weights_tf_dim_ordering_tf_kernels.h5',include_top=True)
#加载图片并转换为224*224大小
image = imagepre.load_img('71c3dd295fb538c930f414861c0216e.png',target_size=(224,224))
imagedata = imagepre.img_to_array(image)#图像转为数组
imagedata = imagedata.reshape((1,)+imagedata.shape)#把图片形状加一维形成1批次
imagedata = vgg19.preprocess_input(imagedata)#图像预处理
prediction = model.predict(imagedata)#模型预测
results = vgg19.decode_predictions(prediction,top=3)#选取概率值前三的结果展示
print(results)
上面这张图片是在网上随便找的,文件名为:v2-68fc9dc20b2c3e2d0791221e64700d19_b.jpg
代码运行结果:
最后的蓝色提示:"beagle"概率为0.69";"English_foxhound"概率为0.12089;"walker_houn-d"概率为0.09。
浏览器检索beagle结果:
浏览器检索English_foxhound结果:
你还可以尝试随机识别一个图片,模型会给出比较满意的结果。