如题,训练模型时候输入的图片分辨率是28x28的,但是测试模型时用自己拍的图片分辨率会很大,然后没法放进模型里。有没有什么办法不改变训练集的图片分辨率,但是用自己拍的照片放进去也能测试。
现在用的是resize把图片改成28x28,但是分辨率太小会影响判断。
全部代码
import matplotlib.pyplot as plt
from keras.utils import to_categorical
from keras import models, layers, regularizers
from keras.optimizers import RMSprop
from keras.datasets import mnist
import tensorflow as tf
import os
import cv2
import dlib
import numpy as np
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
# 调用GPU
config=tf.compat.v1.ConfigProto(allow_soft_placement=True) ##:如果你指定的设备不存在,允许TF自动分配设备
config.gpu_options.allow_growth=True ##动态分配内存
sess=tf.compat.v1.Session(config=config)
# 加载数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28*28)).astype('float')
test_images = test_images.reshape((10000, 28*28)).astype('float')
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# 搭建神经网络
estimator = models.Sequential()
estimator.add(layers.Dense(units=128, activation='relu', input_shape=(28*28, ),
kernel_regularizer=regularizers.l1(0.0001)))
estimator.add(layers.Dropout(0.01))
estimator.add(layers.Dense(units=32, activation='relu',
kernel_regularizer=regularizers.l1(0.0001)))
estimator.add(layers.Dropout(0.01))
estimator.add(layers.Dense(units=10, activation='softmax'))
# 神经网络训练
estimator.compile(optimizer=RMSprop(learning_rate=0.001),loss='categorical_crossentropy', metrics=['accuracy'])
estimator.fit(train_images, train_labels, epochs=20, batch_size=128, verbose=2)
# 保存模型
estimator.save('./model.h5')
# 加载模型
estimator = tf.keras.models.load_model('./model.h5')
# 模型评估
test_loss, test_accuracy = estimator.evaluate(test_images, test_labels)
print("test_loss:", test_loss, "test_accuracy", test_accuracy)
# 图片测试
# # 一次测试一个文件
# img_path = "./num/"
# imagepaths = os.listdir(img_path) # 图像文件夹
# # 从图片集中一次读取图片
# for imagepath in imagepaths:
# im = cv2.imread(os.path.join(img_path, imagepath), 1)
# plt.imshow(im)
# plt.show()
# im = cv2.resize(im, (28, 28), interpolation=cv2.INTER_CUBIC)
# im2 = cv2.cvtColor(im, cv2.cv2.COLOR_BGR2GRAY)
# im2 = im2.reshape((1, 28 * 28)).astype('float')
# y_pre = estimator.predict(im2)
# # print(y_pre)
# y = np.argmax(np.array(y_pre))
# print(y)
# 摄像头测试
# # 打开摄像头
# cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
# # 打开cap
# cap.open(0)
# # 循环
# while cap.isOpened():
# # 获取画面
# flag, frame = cap.read()
# if not flag:
# print("Not Flag")
# break
# # 获取键盘上按下哪个键
# key_pressed = cv2.waitKey(100)
# # print('键盘上被按下的键是:', key_pressed)
# #
# fra = cv2.resize(frame, (28,28))
# im = cv2.cvtColor(fra, cv2.cv2.COLOR_BGR2GRAY)
# im = im.reshape((1, 28 * 28)).astype('float')
# y_pre = estimator.predict(im)
# y = np.argmax(np.array(y_pre))
# print(y)
# print(y)
# cv2.imshow("camera", frame)
# # 如果按下esc键,就退出循环
# if key_pressed == 27:
# break
#
# # 关闭摄像头
# cap.release()
# # 关闭图像窗口
# cv2.destroyAllWindows()