How to predict input image using trained model in Keras?

前端 未结 5 1390
刺人心
刺人心 2020-12-04 06:40

I\'m only beginning with keras and machine learning in general.

I trained a model to classify images from 2 classes and saved it using model.save(). Her

5条回答
  •  难免孤独
    2020-12-04 07:29

    You can use model.predict() to predict the class of a single image as follows [doc]:

    # load_model_sample.py
    from keras.models import load_model
    from keras.preprocessing import image
    import matplotlib.pyplot as plt
    import numpy as np
    import os
    
    
    def load_image(img_path, show=False):
    
        img = image.load_img(img_path, target_size=(150, 150))
        img_tensor = image.img_to_array(img)                    # (height, width, channels)
        img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
        img_tensor /= 255.                                      # imshow expects values in the range [0, 1]
    
        if show:
            plt.imshow(img_tensor[0])                           
            plt.axis('off')
            plt.show()
    
        return img_tensor
    
    
    if __name__ == "__main__":
    
        # load model
        model = load_model("model_aug.h5")
    
        # image path
        img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
        #img_path = '/media/data/dogscats/test1/19.jpg'      # cat
    
        # load a single image
        new_image = load_image(img_path)
    
        # check prediction
        pred = model.predict(new_image)
    

    In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).

提交回复
热议问题