(1)下载MNIST数据集; (2)采用深度学习网络,训练手写数字识别模型; 编写GUI界面,输入测试数字图片,调用识别模型,输出识别结果。代码
时间: 2024-02-26 07:51:34 浏览: 159
好的,以下是实现手写数字识别的Python代码:
```python
# 导入必要的库
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
# 下载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# 构建深度学习网络
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=10, batch_size=32, verbose=1, validation_data=(x_test, y_test))
# 创建GUI界面
root = Tk()
root.title('手写数字识别')
root.geometry('400x400')
# 加载图像
def load_img():
path = filedialog.askopenfilename()
img = Image.open(path).resize((28, 28))
img = ImageTk.PhotoImage(img)
label_img.config(image=img)
label_img.image = img
predict_img(img)
# 预测图像
def predict_img(img):
img_arr = np.array(img)
img_arr = img_arr[:, :, :1]
img_arr = img_arr.astype('float32') / 255
pred = model.predict(np.array([img_arr]))
result = np.argmax(pred)
label_result.config(text='识别结果:{}'.format(result))
# 显示图像
label_img = Label(root)
label_img.pack()
# 加载图像按钮
btn_load = Button(root, text='加载图像', command=load_img)
btn_load.pack()
# 识别结果标签
label_result = Label(root, text='识别结果:')
label_result.pack()
# 运行界面
root.mainloop()
```
这个代码中,首先下载MNIST数据集并进行数据预处理,然后构建一个卷积神经网络,训练模型,并用Tkinter创建一个GUI界面。当用户点击“加载图像”按钮时,程序调用预测函数对图像进行预测,并将结果显示在GUI界面上。希望这个代码对你有帮助!
阅读全文