欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Keras CNN 训练数据(三):预测

程序员文章站 2022-05-19 08:55:16
...

预测代码如下所示:

from keras.models import load_model  #加载模型
import matplotlib.image as processimage  #预处理图片库
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

class Prediction(object):
    #初始化函数
    def __init__(self, ModuleFile, PredictFile, DogType, Width=100, Height=100):
        self.ModuleFile = ModuleFile
        self.PredictFile = PredictFile
        self.DogType = DogType
        self.Width = Width
        self.Height = Height
        
    #预测
    def Predict(self):
        #引入model
        model = load_model(self.ModuleFile)
        
        #处理照片格式和尺寸
        img_open = Image.open(self.PredictFile)
        conv_RGB = img_open.convert('RGB')
        new_img = conv_RGB.resize((self.Width, self.Height), Image.BILINEAR)
        new_img.save(self.PredictFile)
        
        #处理图片shape
        image = processimage.imread(self.PredictFile)
        image_to_array = np.array(image)/255.0
        image_to_array = image_to_array.reshape(-1,100,100,3)
        print('Image reshaped')
        
        #预测照片
        prediction = model.predict(image_to_array)
        Fine_Pred = [result.argmax() for result in prediction][0]
        print(prediction)
        
    #概率读取
        count = 0
        for i in prediction[0]:
            percent = '%.2f%%' % (i*100)
            print(self.DogType[count], '', percent)
            count += 1
        
DogType = ['哈士奇','德国牧羊犬']
# 实例化类
Pred = Prediction(PredictFile='Pred_img/1.jpg',
                  ModuleFile='dogfinder.h5',
                  DogType = DogType)
Pred.Predict()

运行结果如下:

Keras CNN 训练数据(三):预测