Test of a single image for cat and dog training

The establishment of the training model for cat and dog training, the program code of the test of the prediction effect of the model on the entire prediction set can be found online or in some books, but there are not many classification test procedures for single or certain pictures, here is a reference Blog: https://blog.csdn.net/baidu_35113561/article/details/79371716 , my own summary is as follows.

Environment: Python+keras, backend: tensorflow
training set: download can be completed on https://www.kaggle.com/c/dogs-vs-cats/data , a total of 12500 pictures of cats and dogs (due to conditions Limited, I took 1000 cats and dogs for training, and the accuracy verification on the verification set reached 82%)).
The test procedure is as follows:

import cv2
import numpy as np
from keras.models import load_model
from keras.preprocessing.image import ImageDataGenerator

test_dir="D:/研究生/lx/cats-vs-dogs-datasets/000/"    # 加载图片目录

model=load_model('cats_and_dogs_small_1.h5')    # 加载模型参数


for i in range(10):
    print(str(i)+'.jpg')
    img=cv2.imread(str(i)+'.jpg')
    print(img.shape)
    img=cv2.resize(img,(150,150))
    print(img.shape)        # 读取图片并将大小统一至模型输入要求
# cv2.imshow("img",img)
# cv2.waitKey()
    img0 = (img.reshape(1,150,150,3).astype("float32"))/255    # 归一化
    predict = model.predict_classes(img0)
    if predict == 0:
        print('识别为:猫')
        image1=cv2.putText(img,'cat',(20,20),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),1,cv2.LINE_AA)
        cv2.imshow('result',image1)
        cv2.waitKey(10000)
    else:
        image2=cv2.putText(img, 'dog', (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
        print('识别为:狗')
        cv2.imshow('result',image2)
        cv2.waitKey(10000)

The running result is as shown in the figure.
operation result
I admit that some cats and dogs may be cute to you, but we still need to look at the classification results. It can be seen that seven of the 10 pictures have been classified normally, and the prediction accuracy rate is 70%. Although there is still some gap with the verification accuracy of the model during the training process, it is understandable considering the small sample size of the test set.

illustrate:

  1. The size of the picture during the test needs to be unified with the size of the training set when the model is built, otherwise an error will occur because the input picture does not meet the requirements of the model. Since the sample size of my model was unified to 150*150, the size of the picture was also adjusted accordingly during the test.
  2. Pixel values ​​(in the range 0-255) need to be scaled to the [0,1] interval because neural networks are good at handling small input values.

Guess you like

Origin blog.csdn.net/qq_38606680/article/details/90206851