设为首页收藏本站

安徽论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 12347|回复: 0

Python实现带GUI界面的手写数字识别

[复制链接]

85

主题

0

回帖

267

积分

中级会员

Rank: 3Rank: 3

积分
267
发表于 2022-3-26 11:01:17 | 显示全部楼层 |阅读模式
网站内容均来自网络,本站只提供信息平台,如有侵权请联系删除,谢谢!
目录


1.效果图

有点low,轻喷


点击选择图片会优先从当前目录查找


2.数据集

这部分我是对MNIST数据集进行处理保存
对应代码:
  1. import tensorflow as tf
  2. import matplotlib.pyplot as plt
  3. import cv2
  4. from PIL import Image
  5. import numpy as np
  6. from scipy import misc
  7. (x_train_all,y_train_all),(x_test,y_test) = tf.keras.datasets.mnist.load_data()
  8. x_valid,x_train = x_train_all[:5000],x_train_all[5000:]
  9. y_valid,y_train = y_train_all[:5000],y_train_all[5000:]
  10. print(x_valid.shape,y_valid.shape)
  11. print(x_train.shape,y_train.shape)
  12. print(x_test.shape,y_test.shape)
  13. #读取单张图片
  14. def show_single_img(img_arr,len=100,path='/Users/zhangcaihui/Desktop/case/jpg/'):
  15.     for i in range(len):#我这种写法会进行覆盖,只能保存10张照片,想保存更多的数据自己看着改
  16.         new_im = Image.fromarray(img_arr[i])  # 调用Image库,数组归一化
  17.         #new_im.show()
  18.         #plt.imshow(img_arr)  # 显示新图片
  19.         label=y_train[i]
  20.         new_im.save(path+str(label)+'.jpg')  # 保存图片到本地

  21. #显示多张图片
  22. def show_imgs(n_rows,n_cols,x_data,y_data):
  23.     assert len(x_data) == len(y_data)
  24.     assert n_rows * n_cols < len(x_data)
  25.     plt.figure(figsize=(n_cols*1.4,n_rows*1.6))
  26.     for row in range(n_rows):
  27.         for col in range(n_cols):
  28.             index = n_cols * row + col
  29.             plt.subplot(n_rows,n_cols,index+1)
  30.             plt.imshow(x_data[index],cmap="binary",interpolation="nearest")
  31.             plt.axis("off")
  32.     plt.show()
  33. #show_imgs(2,2,x_train,y_train)
  34. show_single_img(x_train)
复制代码
3.关于模型

我保存了了之前训练好的模型,用来加载预测
关于tensorflow下训练神经网络模型:手把手教你,MNIST手写数字识别
训练好的模型model.save(path)即可

4.关于GUI设计

1)排版
  1. #ui_openimage.py
  2. # -*- coding: utf-8 -*-
  3. # from PyQt5 import QtCore, QtGui, QtWidgets
  4. # from PyQt5.QtCore import Qt
  5. import sys,time
  6. from PyQt5 import QtGui, QtCore, QtWidgets
  7. from PyQt5.QtWidgets import *
  8. from PyQt5.QtCore import *
  9. from PyQt5.QtGui import *

  10. class Ui_Form(object):
  11.     def setupUi(self, Form):
  12.         Form.setObjectName("Form")
  13.         Form.resize(1144, 750)
  14.         self.label_1 = QtWidgets.QLabel(Form)
  15.         self.label_1.setGeometry(QtCore.QRect(170, 130, 351, 251))
  16.         self.label_1.setObjectName("label_1")
  17.         self.label_2 = QtWidgets.QLabel(Form)
  18.         self.label_2.setGeometry(QtCore.QRect(680, 140, 351, 251))
  19.         self.label_2.setObjectName("label_2")
  20.         self.btn_image = QtWidgets.QPushButton(Form)
  21.         self.btn_image.setGeometry(QtCore.QRect(270, 560, 93, 28))
  22.         self.btn_image.setObjectName("btn_image")
  23.         self.btn_recognition = QtWidgets.QPushButton(Form)
  24.         self.btn_recognition.setGeometry(QtCore.QRect(680,560,93,28))
  25.         self.btn_recognition.setObjectName("bnt_recognition")
  26.         #显示时间按钮
  27.         self.bnt_timeshow = QtWidgets.QPushButton(Form)
  28.         self.bnt_timeshow.setGeometry(QtCore.QRect(900,0,200,50))
  29.         self.bnt_timeshow.setObjectName("bnt_timeshow")
  30.         self.retranslateUi(Form)
  31.         self.btn_image.clicked.connect(self.slot_open_image)
  32.         self.btn_recognition.clicked.connect(self.slot_output_digital)
  33.         self.bnt_timeshow.clicked.connect(self.buttonClicked)
  34.         self.center()
  35.         QtCore.QMetaObject.connectSlotsByName(Form)

  36.     def retranslateUi(self, Form): #设置文本填充label、button
  37.         _translate = QtCore.QCoreApplication.translate
  38.         Form.setWindowTitle(_translate("Form", "数字识别系统"))
  39.         self.label_1.setText(_translate("Form", "点击下方按钮"))
  40.         self.label_1.setStyleSheet('font:50px;')
  41.         self.label_2.setText(_translate("Form", "0~9"))
  42.         self.label_2.setStyleSheet('font:50px;')
  43.         self.btn_image.setText(_translate("Form", "选择图片"))
  44.         self.btn_recognition.setText(_translate("From","识别结果"))
  45.         self.bnt_timeshow.setText(_translate("Form","当前时间"))

  46.     # 状态条显示时间模块
  47.     def buttonClicked(self):  # 动态显示时间
  48.         timer = QTimer(self)
  49.         timer.timeout.connect(self.showtime)
  50.         timer.start()
  51.     def showtime(self):
  52.         datetime = QDateTime.currentDateTime()
  53.         time_now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  54.         #self.statusBar().showMessage(time_now)
  55.         #self.bnt_timeshow.setFont(QtGui.QFont().setPointSize(100))
  56.         self.bnt_timeshow.setText(time_now)

  57.     def center(self):#窗口放置中央
  58.         screen = QDesktopWidget().screenGeometry()
  59.         size = self.geometry()
  60.         self.move((screen.width() - size.width()) / 2,
  61.                     (screen.height() - size.height()) / 2)


  62.     def keyPressEvent(self, e):
  63.         if e.key() == Qt.Key_Escape:
  64.             self.close()
复制代码
2)直接运行这个文件(调用1)
  1. #ui_main.py
  2. import random

  3. from PyQt5.QtWidgets import QFileDialog
  4. from PyQt5.QtGui import QPixmap
  5. from ui_openimage import Ui_Form
  6. import sys
  7. from PyQt5 import QtWidgets, QtGui
  8. from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication
  9. import os,sys
  10. from PyQt5.QtCore import Qt

  11. import tensorflow
  12. from tensorflow.keras.models import load_model
  13. from tensorflow.keras.datasets import mnist
  14. from tensorflow.keras import models
  15. from tensorflow.keras import layers
  16. from tensorflow.keras.utils import to_categorical
  17. import tensorflow.keras.preprocessing.image as image
  18. import matplotlib.pyplot as plt
  19. import numpy as np
  20. import cv2
  21. import warnings
  22. warnings.filterwarnings("ignore")
  23. class window(QtWidgets.QMainWindow,Ui_Form):
  24.     def __init__(self):
  25.         super(window, self).__init__()
  26.         self.cwd = os.getcwd()
  27.         self.setupUi(self)
  28.         self.labels = self.label_1
  29.         self.img=None
  30.     def slot_open_image(self):
  31.         file, filetype = QFileDialog.getOpenFileName(self, '打开多个图片', self.cwd, "*.jpg, *.png, *.JPG, *.JPEG, All Files(*)")
  32.         jpg = QtGui.QPixmap(file).scaled(self.labels.width(), self.labels.height())
  33.         self.labels.setPixmap(jpg)
  34.         self.img=file

  35.     def slot_output_digital(self):
  36.             '''path为之前保存的模型路径'''
  37.         path='/Users/zhangcaihui/PycharmProjects/py38_tf/DL_book_keras/save_the_model.h5'
  38.         model= load_model(path)
  39.         #防止不上传数字照片而直接点击识别
  40.         if self.img==None:
  41.             self.label_2.setText('请上传照片!')
  42.             return
  43.         img = image.load_img(self.img, target_size=(28, 28))
  44.         img = img.convert('L')#转灰度图像
  45.         x = image.img_to_array(img)
  46.         #x = abs(255 - x)
  47.         x = np.expand_dims(x, axis=0)
  48.         print(x.shape)
  49.         x = x / 255.0
  50.         prediction = model.predict(x)
  51.         print(prediction)
  52.         output = np.argmax(prediction, axis=1)
  53.         print("手写数字识别为:" + str(output[0]))
  54.         self.label_2.setText(str(output[0]))

  55. if __name__ == "__main__":
  56.   app = QtWidgets.QApplication(sys.argv)
  57.   my = window()
  58.   my.show()
  59.   sys.exit(app.exec_())
复制代码
5.缺点

界面low
只能识别单个数字
其实可以将多数字图片进行裁剪分割,这就涉及到制作数据集了

6.遗留问题

我自己手写的数据照片处理成28281送入网络预测,识别结果紊乱。
反思:自己写的数据是RGB,且一张几KB,图片预处理后,按28*28读入失真太严重了,谁有好的方法可以联系我!!!
其他的水果识别系统,手势识别系统啊,改改直接套!
到此这篇关于Python实现带GUI界面的手写数字识别的文章就介绍到这了,更多相关Python手写数字识别内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
                                                        
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
免责声明
1. 本论坛所提供的信息均来自网络,本网站只提供平台服务,所有账号发表的言论与本网站无关。
2. 其他单位或个人在使用、转载或引用本文时,必须事先获得该帖子作者和本人的同意。
3. 本帖部分内容转载自其他媒体,但并不代表本人赞同其观点和对其真实性负责。
4. 如有侵权,请立即联系,本网站将及时删除相关内容。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表