网络编程
位置:首页>> 网络编程>> Python编程>> 利用keras加载训练好的.H5文件,并实现预测图片

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

作者:Jaguar_95  发布时间:2021-01-18 21:18:57 

标签:keras,H5文件,预测图片

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


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)

来源:https://blog.csdn.net/Jaguar_95/article/details/82970754

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com