目次
1. 説明
この記事では、前の記事でトレーニングしたモデルをテストします。1 つ目は、トレーニングされたモデルを再ロードし、次に opencv を使用して画像をロードし、最後にロードされた画像をモデルに送信して結果を表示することです。
2. cifar10のCNNモデルテスト
2.1 関連ライブラリのインポート
ここに必要なサードパーティ ライブラリ (cv2 など) をインポートします。そうでない場合は、自分でダウンロードする必要があります。自分でダウンロードする場合は、ダウンロードを高速化するために、通常、ソースをミラーリングすることをお勧めします。
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
from keras.datasets import cifar10
2.2 データとモデルのロード
cifar10 データセットをロードし、トレーニング済みモデルをロードして、最終結果表示用の cifar10 データセットのリストを作成します。
# cifar10数据集列表
class_names = ["airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"]
# 加载fashion数据
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# 加载cnn_cifar10_4.h5文件,重新生成模型对象
recons_model = keras.models.load_model('cnn_cifar10_4.h5')
2.3 画像を保存するパスを設定する
データセットの特定のデータを画像の形式で保存すると、テストの視覚化に便利です。
ここで画像の保存場所を設定すると、画像を保存しやすくなります。
# 创建图片保存路径
test_file_path = os.path.join(sys.path[0], 'imgs', 'test1000.png')
# 存储测试数据的任意一个
Image.fromarray(x_test[1000]).save(test_file_path)
上記のコードを記述した後、次のように、コードの現在のパスに画像を保存するための imgs フォルダーを作成する必要があります。
上記のコードを実行すると、次のように、imgs ファイル内にもう 1 つの画像が見つかります (以下で何度もテストしています)。
2.4 画像をロードする
cv2 を使用して画像を読み込みます。opencv ライブラリ、つまり cv2 を使用して画像を読み取る場合、画像は 3 チャネルであり、トレーニング済みモデルは 3 チャネルであるため、単一チャネルだけではなく 3 チャネルになります。 . ここと前ではグレースケール画像が異なります。
# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(32,32)
test_img = cv2.resize(test_img, (32, 32))
2.5 画像の前処理
画像の前処理、つまり形状の正規化と変更は、予測のためにトレーニングされたモデルへの画像の入力を容易にするためのものです。
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 32, 32, 3)
2.6 画像の予測
トレーニング済みモデルに画像を入力し、予測を行います。
予測結果は10個の確率値なので処理が必要ですが、np.argmax()は予測値である確率値の最大値の通し番号です。
# 预测
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])
print('test.png的所属类别:', class_names[class_id])
2.7 画像を表示する
予想画像を表示し、画像上に予想数字を表示します。
次の 5 行のコードは、ウィンドウの作成、ウィンドウ サイズの設定、画像の表示、画像の停止、メモリのクリアを行っています。
# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500) # 自己设定窗口图片的大小
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()
3. コードを完成させて結果を表示する
以下は完全なコードと結果を示す図です。
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
from keras.datasets import cifar10
# cifar10数据集列表
class_names = ["airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"]
# 加载fashion数据
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# 加载cnn_cifar10_4.h5文件,重新生成模型对象
recons_model = keras.models.load_model('cnn_cifar10_4.h5')
# 创建图片保存路径
test_file_path = os.path.join(sys.path[0], 'imgs', 'test1000.png')
# 存储测试数据的任意一个
Image.fromarray(x_test[1000]).save(test_file_path)
# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(32,32)
test_img = cv2.resize(test_img, (32, 32))
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 32, 32, 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])
print('test.png的所属类别:', class_names[class_id])
# # 显示
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 [==============================] - 0s 173ms/step
test.png的预测概率: [[5.1407650e-08 1.3184264e-07 1.4382408e-05 3.0730411e-03 6.6092167e-07
9.9690622e-01 3.4352513e-07 4.4902617e-06 5.1169474e-07 1.9515875e-07]]
test.png的预测概率: 0.9969062
test.png的所属类别: dog
4. 完全なコードと複数の画像を使用したテスト結果
より多くの画像をテストするために、複数のテストを実行するループが導入され、効果が向上します。
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
# cifar10数据集列表
class_names = ["airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"]
# 加载mnist数据
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# 加载cnn_fashion.h5文件,重新生成模型对象
recons_model = keras.models.load_model('cnn_cifar10_4.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(sys.path[0], 'imgs', path1)
# 存储测试数据的任意一个
num = int(input("input the test picture num:"))
Image.fromarray(x_test[num]).save(test_file_path)
# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(28,28)
test_img = cv2.resize(test_img, (32, 32))
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 32, 32, 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])
print('test.png的所属类别:', class_names[class_id])
# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500) # 自己设定窗口图片的大小
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()
input the number of test picture :2
input the test picture path:90.jpg
input the test picture num:1
1/1 [==============================] - 0s 149ms/step
test.png的预测概率: [[1.5192369e-05 1.2153896e-03 4.3699760e-10 8.3202184e-07 6.7535249e-09
2.5758654e-10 2.1669943e-07 7.0233480e-12 9.9875784e-01 1.0427103e-05]]
test.png的预测概率: 0.99875784
test.png的所属类别: ship
input the test picture path:91.jpg
input the test picture num:3
1/1 [==============================] - 0s 144ms/step
test.png的预测概率: [[9.3968987e-01 7.0652168e-06 8.8076144e-03 3.7453551e-04 2.6135262e-02
9.9803242e-07 9.7372030e-08 1.5685426e-07 2.4942497e-02 4.1973537e-05]]
test.png的预测概率: 0.9396899
test.png的所属类别: airplane