keras的基本用法(五)——图像predict

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要介绍Keras的一些基本用法,主要是根据已有模型预测图像的类别,以ResNet50为例。

  • Demo
import numpy as np
from keras.layers import Dense
from keras.models import Model
from keras.preprocessing import image
from keras.applications.resnet50 import ResNet50

# 使用ResNet的结构,不包括最后一层
base_model = ResNet50(include_top = False, pooling = 'avg')

# 定义网络结构最后一层
predictions = Dense(3, activation='softmax')(base_model.output)

# 定义模型
model = Model(inputs=base_model.input, outputs=predictions)

# 加载训练好的模型
model.load_weights('./weights.h5')

image_path = './lena.jpg'

# 加载图像
img = image.load_img(image_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)

# 输出预测概率
print 'Predicted:', preds
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容