Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize handwritten digit recognition with GUI Interface by Python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how Python realizes handwritten digit recognition with GUI interface. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Effect picture

A little low, light spray

Clicking to select a picture will give priority to finding it from the current directory

two。 Data set

In this part, I process and save the MNIST data set.

Corresponding code:

Import tensorflow as tfimport matplotlib.pyplot as pltimport cv2from PIL import Imageimport numpy as npfrom scipy import misc [: 5000], print (x_train.shape valid.shape.shape) print (x_train.shape) Y_train.shape) print (xroomtest.shaperecoverychildtest.shape) # read a single picture def show_single_img (img_arr,len=100,path='/Users/zhangcaihui/Desktop/case/jpg/'): for i in range (len): # I will overwrite it in this way. Only 10 photos can be saved. If you want to save more data, look at new_im = Image.fromarray (img_ arr [I]) # call the Image library. Array normalization # new_im.show () # plt.imshow (img_arr) # display new pictures label=y_ pictures [I] new_im.save (path+str (label) + '.jpg') # Save pictures to local # display multiple pictures def show_imgs Y_data): assert len (x_data) = = len (y_data) assert nymphrows* n_cols < len (x_data) plt.figure (figsize= (nasty cols1.4coverrowswriting 1.6)) for row in range (n_rows): for col in range (n_cols): index = nymphcols * row + col plt.subplot Index+1) plt.imshow (xdata [index], cmap= "binary", interpolation= "nearest") plt.axis ("off") plt.show () # show_imgs. About the model

I saved the previously trained model and used it to load the prediction

About the training neural network model under tensorflow: hand-in-hand teaches you, MNIST handwritten digit recognition

The trained model model.save (path) will be fine.

4. About GUI Design

1) typesetting

# ui_openimage.py#-*-coding: utf-8-*-# from PyQt5 import QtCore, QtGui, QtWidgets# from PyQt5.QtCore import Qtimport sys,timefrom PyQt5 import QtGui, QtCore, QtWidgetsfrom PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class Ui_Form (object): def setupUi (self, Form): Form.setObjectName ("Form") Form.resize (1144 Self.label_1 = QtWidgets.QLabel (Form) self.label_1.setGeometry (QtCore.QRect (170130351,251) self.label_1.setObjectName ("label_1") self.label_2 = QtWidgets.QLabel (Form) self.label_2.setGeometry (QtCore.QRect (680,140,351) Self.label_2.setObjectName ("label_2") self.btn_image = QtWidgets.QPushButton (Form) self.btn_image.setGeometry (QtCore.QRect (270,560,93) 28) self.btn_image.setObjectName ("btn_image") self.btn_recognition = QtWidgets.QPushButton (Form) self.btn_recognition.setGeometry (QtCore.QRect (680, 560 and 93 (28)) self.btn_recognition.setObjectName ("bnt_recognition") # display time button self.bnt_timeshow = QtWidgets.QPushButton (Form) self.bnt_timeshow.setGeometry (QtCore.QRect (900) Self.bnt_timeshow.setObjectName ("bnt_timeshow") self.retranslateUi (Form) self.btn_image.clicked.connect (self.slot_open_image) self.btn_recognition.clicked.connect (self.slot_output_digital) self.bnt_timeshow.clicked.connect (self.buttonClicked) self.center () QtCore.QMetaObject.connectSlotsByName (Form) def retranslateUi (self) Form): # set text fill label, button _ translate = QtCore.QCoreApplication.translate Form.setWindowTitle (_ translate ("Form", "digit recognition system")) self.label_1.setText (_ translate ("Form", "Click the button below")) self.label_1.setStyleSheet ('font:50px ') self.label_2.setText (_ translate ("Form", "0,9")) self.label_2.setStyleSheet (' font:50px ') self.btn_image.setText (_ translate ("Form", "Select picture")) self.btn_recognition.setText (_ translate ("From", "recognition result")) self.bnt_timeshow.setText (_ translate ("Form") ("current time")) # status bar display time module def buttonClicked (self): # dynamic display time timer = QTimer (self) timer.timeout.connect (self.showtime) timer.start () def showtime (self): datetime = QDateTime.currentDateTime () time_now = time.strftime ('% Y-%m-%d% HGV% MGV% S' Time.localtime () # self.statusBar (). ShowMessage (time_now) # self.bnt_timeshow.setFont (QtGui.QFont (). SetPointSize (100)) self.bnt_timeshow.setText (time_now) def center (self): # place the window in the center screen = QDesktopWidget (). ScreenGeometry () size = self.geometry () self.move ((screen.width ()-size.width ()) / 2 (screen.height ()-size.height ()) / 2) def keyPressEvent (self, e): if e.key () = = Qt.Key_Escape: self.close ()

2) run this file directly (call 1)

# ui_main.pyimport randomfrom PyQt5.QtWidgets import QFileDialogfrom PyQt5.QtGui import QPixmapfrom ui_openimage import Ui_Formimport sysfrom PyQt5 import QtWidgets, QtGuifrom PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplicationimport os,sysfrom PyQt5.QtCore import Qtimport tensorflowfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.datasets import mnistfrom tensorflow.keras import modelsfrom tensorflow.keras import layersfrom tensorflow.keras.utils import to_categoricalimport tensorflow.keras.preprocessing.image as imageimport matplotlib.pyplot as pltimport numpy as npimport cv2import warningswarnings.filterwarnings ("ignore") class window (QtWidgets.QMainWindow Ui_Form): def _ init__ (self): super (window, self). _ _ init__ () self.cwd = os.getcwd () self.setupUi (self) self.labels = self.label_1 self.img=None def slot_open_image (self): file, filetype = QFileDialog.getOpenFileName (self, 'Open multiple pictures', self.cwd, "* .jpg, * .png, * .JPG" * .JPEG, All Files (*) ") jpg = QtGui.QPixmap (file) .scaled (self.labels.width ()) Self.labels.height () self.labels.setPixmap (jpg) self.img=file def slot_output_digital (self):''path is the previously saved model path' 'path='/Users/zhangcaihui/PycharmProjects/py38_tf/DL_book_keras/save_the_model.h6' model= load_model (path) # to prevent direct uploading of digital photos Click to identify if self.img==None: self.label_2.setText ('Please upload photos!') Return img = image.load_img (self.img, target_size= (28,28)) img = img.convert ('L') # convert grayscale image x = image.img_to_array (img) # x = abs (255x) x = np.expand_dims (x Axis=0) print (x.shape) x = x / 255.0 prediction = model.predict (x) print (prediction) output = np.argmax (prediction) Axis=1) print ("handwritten numeral recognition is:" + str (output [0])) self.label_2.setText (str (output [0])) if _ name__ = "_ _ main__": app = QtWidgets.QApplication (sys.argv) my = window () my.show () sys.exit (app.exec_ ()) 5. Shortcoming

Interface low

Only a single number can be recognized

In fact, multi-digital images can be cropped and segmented, which involves making data sets.

6. Remaining problems

My own handwritten data photos were processed into 28281 and sent to the network for prediction, and the recognition results were disordered.

Reflection: the data I wrote is RGB, and a few KB, after the picture pre-processing, press 28x28 to read the distortion is too serious, who has a good way to contact me!

Other fruit recognition systems, gesture recognition systems, ah, change the direct set!

Thank you for reading! This is the end of the article on "how to realize handwritten digit recognition with GUI interface in Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report