目次
1. 説明
この記事では、前の記事でトレーニングしたモデルをテストします。1 つ目は、トレーニングされたモデルを再ロードし、次に opencv を使用して画像をロードし、最後にロードされた画像をモデルに送信して結果を表示することです。
2. 手書き数字認識のANNモデルテスト
2.1 関連ライブラリのインポート
cv2 などの必要なサードパーティ ライブラリをここでインポートします。そうでない場合は、自分でダウンロードする必要があります。
from tensorflow import keras
# 引入内置手写体数据集mnist
from keras.datasets import mnist
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw # PIL就是pillow包(保存图像)
import numpy as np
2.2 データとモデルのロード
MNIST データセットをロードし、トレーニングされたモデルをロードします。
# 加载mnist数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 加载ann_mnist.h5文件,重新生成模型对象, 等价于之前训练好的ann_model
recons_model = keras.models.load_model('ann_mnist.h5')
2.3 画像を保存するパスを設定する
データセットの特定のデータを画像の形式で保存すると、テストの視覚化に便利です。
ここで画像の保存場所を設定します。
# 创建图片保存路径
test_file_path = os.path.join(sys.path[0], 'imgs', 'test1.png')
# 存储测试数据的任意一个
Image.fromarray(x_test[1]).save(test_file_path)
上記のコードを記述した後、次のように、画像を保存するためにコードの現在のパスの下に imgs フォルダーを作成する必要があります。
上記のコードを実行すると、次のように、imgs ファイル内にもう 1 つの画像が見つかります (以下で何度もテストしています)。
2.4 画像をロードする
cv2 を使用して画像をロードします。以下のコードの最後の行が 1 つのチャネルを使用する理由は、opencv ライブラリ、つまり cv2 を使用して画像を読み取る場合、画像は 3 チャネルであり、トレーニングされたモデルは 1 つのチャネルであるためです。チャネルなので、シングルチャネルが使用されます。
# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(28,28)
test_img = cv2.resize(test_img, (28, 28))
# 取单通道值
test_img = test_img[:, :, 0]
2.5 画像の前処理
画像の前処理、つまり形状の正規化と変更は、予測のためにトレーニングされたモデルへの画像の入力を容易にするためのものです。
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 784)
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_id)
class_id = str(class_id)
2.7 画像を表示する
予想画像を表示し、画像上に予想数字を表示します。
次の 6 行のコードは、ウィンドウの作成、ウィンドウのサイズの設定、数値の表示、画像の表示、画像の停止、メモリのクリアです。
# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500) # 自己设定窗口图片的大小
cv2.putText(image, class_id, (2, 5), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 0.2, (255, 0, 0), 1)
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()
3. コードを完成させて結果を表示する
以下は完全なコードと結果を示す図です。
from tensorflow import keras
# 引入内置手写体数据集mnist
from keras.datasets import mnist
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw # PIL就是pillow包(保存图像)
import numpy as np
# 加载mnist数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 加载ann_mnist.h5文件,重新生成模型对象, 等价于之前训练好的ann_model
recons_model = keras.models.load_model('ann_mnist.h5')
# 创建图片保存路径
test_file_path = os.path.join(sys.path[0], 'imgs', 'test1.png')
# 存储测试数据的任意一个
Image.fromarray(x_test[1]).save(test_file_path)
# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(28,28)
test_img = cv2.resize(test_img, (28, 28))
# 取单通道值
test_img = test_img[:, :, 0]
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 784)
# 预测
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_id)
class_id = str(class_id)
# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500) # 自己设定窗口图片的大小
cv2.putText(image, class_id, (2, 5), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 0.2, (255, 0, 0), 1)
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()
4. 完全なコードと複数の画像を使用したテスト結果
より多くの画像をテストするために、複数のテストを実行するループが導入され、効果が向上します。
# python练习
# 重新学习时间:2023/4/30 23:45
from tensorflow import keras
# 引入内置手写体数据集mnist
from keras.datasets import mnist
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw # PIL就是pillow包(保存图像)
import numpy as np
# 加载mnist数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 加载ann_mnist.h5文件,重新生成模型对象, 等价于之前训练好的ann_model
recons_model = keras.models.load_model('ann_mnist.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, (28, 28))
# 取单通道值
test_img = test_img[:, :, 0]
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 784)
# 预测
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_id)
class_id = str(class_id)
# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500) # 自己设定窗口图片的大小
cv2.putText(image, class_id, (2, 5), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 0.2, (255, 0, 0), 1)
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()
次のテスト ピクチャの番号は、実際の値の番号ではなく、データ セット内のデータのシリアル番号 (0 ~ 59999) を指します。
2023-07-18 21:24:54.034234: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
input the number of test picture :5
input the test picture path:61.jpg
input the test picture num:1
1/1 [==============================] - 0s 212ms/step
test.png的预测概率: [[6.7599565e-11 5.6974045e-08 9.9999976e-01 1.4167172e-08 4.2876313e-14
8.5433702e-17 9.8270281e-12 2.0837895e-07 2.0044362e-13 3.8371804e-15]]
test.png的预测概率: 0.99999976
test.png的所属类别/手写体数字: 2
input the test picture path:62.jpg
input the test picture num:2
1/1 [==============================] - 0s 25ms/step
test.png的预测概率: [[2.95021305e-08 9.99796808e-01 5.78483643e-08 1.15721946e-07
1.02379022e-06 1.07751411e-07 1.75613415e-04 1.84143373e-05
7.72468411e-06 8.39250518e-08]]
test.png的预测概率: 0.9997968
test.png的所属类别/手写体数字: 1
input the test picture path:63.jpg
input the test picture num:3
1/1 [==============================] - 0s 26ms/step
test.png的预测概率: [[9.9962425e-01 7.8167646e-11 6.5924123e-06 9.7057705e-07 2.3867991e-11
3.1169588e-04 5.6094854e-05 9.8954046e-11 1.0871034e-08 3.3060348e-07]]
test.png的预测概率: 0.99962425
test.png的所属类别/手写体数字: 0
input the test picture path:64.jpg
input the test picture num:4
1/1 [==============================] - 0s 30ms/step
test.png的预测概率: [[1.3954380e-09 5.2584750e-07 7.7287673e-08 2.3394799e-08 9.9983513e-01
4.9446136e-10 1.9493827e-06 4.0978726e-08 3.1354301e-07 1.6186526e-04]]
test.png的预测概率: 0.99983513
test.png的所属类别/手写体数字: 4
input the test picture path:65.jpg
input the test picture num:5
1/1 [==============================] - 0s 47ms/step
test.png的预测概率: [[4.70661676e-10 9.99986053e-01 5.76763526e-10 1.16811161e-09
5.13054097e-08 5.98078254e-10 1.21732055e-05 1.10577037e-06
5.98011809e-07 1.74244752e-09]]
test.png的预测概率: 0.99998605
test.png的所属类别/手写体数字: 1