当前位置:首页 » python教程 » 正文

利用keras加载训练好的.H5文件,并实现预测图片

看: 855次  时间:2020-10-25  分类 : python教程

我就废话不多说了,直接上代码吧!

import matplotlib
matplotlib.use('Agg')
import os
from keras.models import load_model
import numpy as np
from PIL import Image
import cv2
#加载模型h5文件
model = load_model("C:\\python\\python3_projects\\cat_dog\\cats_dogs_fifty_thousand.h5")
model.summary()
#规范化图片大小和像素值
def get_inputs(src=[]):
  pre_x = []
  for s in src:
    input = cv2.imread(s)
    input = cv2.resize(input, (150, 150))
    input = cv2.cvtColor(input, cv2.COLOR_BGR2RGB)
    pre_x.append(input) # input一张图片
  pre_x = np.array(pre_x) / 255.0
  return pre_x
#要预测的图片保存在这里
predict_dir = 'C:\python\python3_projects\cat_dog\pics'
#这个路径下有两个文件,分别是cat和dog
test = os.listdir(predict_dir)
#打印后:['cat', 'dog']
print(test)
#新建一个列表保存预测图片的地址
images = []
#获取每张图片的地址,并保存在列表images中
for testpath in test:
  for fn in os.listdir(os.path.join(predict_dir, testpath)):
    if fn.endswith('jpg'):
      fd = os.path.join(predict_dir, testpath, fn)
      print(fd)
      images.append(fd)
#调用函数,规范化图片
pre_x = get_inputs(images)
#预测
pre_y = model.predict(pre_x)
print(pre_y)

以上这篇利用keras加载训练好的.H5文件,并实现预测图片就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:numpy  matplotlib  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!