Python and Deep Learning (12): CNN and Cats and Dogs War II

1. Description

This article is to test the model trained in the previous article Cats and Dogs War. The first is to reload the trained model, then use opencv to load the picture, and finally send the loaded picture to the model and display the result.

2. CNN model test of cat and dog war

2.1 Import related libraries

Import the required third-party library here, such as cv2. If not, you need to download it yourself. When you download it yourself, it is generally recommended to mirror the source, so that the download is fast.

from tensorflow import keras
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw  # PIL就是pillow包(保存图像)
import numpy as np
# 导入tensorflow
import tensorflow as tf
# 导入keras
from tensorflow import keras

2.2 Load the model

Also load the trained model, there is no need to load the data here, because the data is self-made.

# 加载my_cnn_cat_dog_3.h5文件,重新生成模型对象
recons_model = keras.models.load_model('my_cnn_cat_dog_3.h5')

2.3 Set the path to save the picture

Save a certain data of the data set in the form of a picture, which is convenient for the visualization of the test. Here, the test set has been divided before, so just set the picture path.
Set the storage location of the picture here, so that the picture can be stored conveniently.

# 创建图片保存路径
test_file_path = os.path.join('dog-cats', 'test', '1.jpg')
# 加载本地test.png图像
image = cv2.imread(test_file_path)

The above code is to test 1.jpg in the test folder. If you want to test other ones, you only need to change it to x.jpg.
insert image description here

2.4 Load pictures

Use cv2 to load the picture. When using the opencv library, that is, cv2 to read the picture, the picture is three-channel, and the trained model is three-channel, so it is not only a single channel, but three channels. Here and before Grayscale images are different.

# 复制图片
test_img = image.copy()
# 将图片大小转换成(150,150)
test_img = cv2.resize(test_img, (150,150))

2.5 Image preprocessing

Preprocessing the picture, that is, normalizing and changing the shape, is to facilitate the input of the picture to the trained model for prediction. So change the shape to 150 150 3 here, the previous 1 is the number of samples, so it is (1,150,150,3).

# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 150,150, 3)

2.6 Predicting pictures

Input the picture to the trained model and make predictions.
Because it is a binary classification, the predicted result is a probability value, so it needs to be processed. If it is greater than 0.5, it is a dog, and if it is less than 0.5, it is a cat.

# 预测
y_pre_pro = recons_model.predict(new_test_img, verbose=1)
# 哪一类
class_id = np.argmax(y_pre_pro, axis=1)[0]
print('test.png的预测概率:', y_pre_pro)
print('test.png的预测概率:', y_pre_pro[0, class_id])
if y_pre_pro[0, class_id] > 0.5:
    print('png的所属类别:', 'dog')
else:
    print('png的所属类别:', 'cat')

2.7 Display pictures

Display the predicted picture, and display the predicted number on the picture.
The following 5 lines of code are to create the window, set the window size, display the picture, stay the picture, and clear the memory.

# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500)  # 自己设定窗口图片的大小
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()

3. Complete code and display results

Below is the complete code and a picture showing the result.

from tensorflow import keras
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw  # PIL就是pillow包(保存图像)
import numpy as np
# 导入tensorflow
import tensorflow as tf
# 导入keras
from tensorflow import keras


# 加载my_cnn_cat_dog_3.h5文件,重新生成模型对象
recons_model = keras.models.load_model('my_cnn_cat_dog_3.h5')
# 创建图片保存路径
test_file_path = os.path.join('dog-cats', 'test', '1.jpg')
# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(150,150)
test_img = cv2.resize(test_img, (150,150))
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 150,150, 3)
# 预测
y_pre_pro = recons_model.predict(new_test_img, verbose=1)
# 哪一类
class_id = np.argmax(y_pre_pro, axis=1)[0]
print('test.png的预测概率:', y_pre_pro)
print('test.png的预测概率:', y_pre_pro[0, class_id])
if y_pre_pro[0, class_id] > 0.5:
    print('png的所属类别:', 'dog')
else:
    print('png的所属类别:', 'cat')
# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500)  # 自己设定窗口图片的大小
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()

To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
1/1 [==============================] - 3s 3s/step
test.png的预测概率: [[0.999939]]
test.png的预测概率: 0.999939
png的所属类别: dog

insert image description here

4. The complete code and results of testing with multiple pictures

In order to test more pictures, a loop is introduced to perform multiple tests, and the effect is better.

from tensorflow import keras
from keras.datasets import cifar10
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw  # PIL就是pillow包(保存图像)
import numpy as np

# 加载my_cnn_cat_dog_3.h5文件,重新生成模型对象
recons_model = keras.models.load_model('my_cnn_cat_dog_3.h5')

prepicture = int(input("input the number of test picture :"))
for i in range(prepicture):
    path1 = input("input the test picture path:")
    # 创建图片保存路径
    test_file_path = os.path.join('dog-cats', 'test', path1)
    # 加载本地test.png图像
    image = cv2.imread(test_file_path)
    # 复制图片
    test_img = image.copy()
    # 将图片大小转换成(150,150)
    test_img = cv2.resize(test_img, (150, 150))
    # 预处理: 归一化 + reshape
    new_test_img = (test_img / 255.0).reshape(1, 150, 150, 3)
    # 预测
    y_pre_pro = recons_model.predict(new_test_img, verbose=1)
    # 哪一类数字
    class_id = np.argmax(y_pre_pro, axis=1)[0]
    print('test.png的预测概率:', y_pre_pro)
    print('test.png的预测概率:', y_pre_pro[0, class_id])
    if y_pre_pro[0, class_id] > 0.5:
        print('png的所属类别:', 'dog')
    else:
        print('png的所属类别:', 'cat')
    # # 显示
    cv2.namedWindow('img', 0)
    cv2.resizeWindow('img', 500, 500)  # 自己设定窗口图片的大小
    cv2.imshow('img', image)
    cv2.waitKey()
    cv2.destroyAllWindows()

To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
input the number of test picture :2
input the test picture path:2.jpg
1/1 [==============================] - 2s 2s/step
test.png的预测概率: [[0.99774814]]
test.png的预测概率: 0.99774814
png的所属类别: dog

insert image description here

input the test picture path:3.jpg
1/1 [==============================] - 0s 87ms/step
test.png的预测概率: [[0.9999783]]
test.png的预测概率: 0.9999783
png的所属类别: dog

insert image description here

Guess you like

Origin blog.csdn.net/qq_47598782/article/details/132031652