Python實(shí)現(xiàn)帶GUI界面的手寫數(shù)字識(shí)別
1.效果圖
有點(diǎn)low,輕噴


點(diǎn)擊選擇圖片會(huì)優(yōu)先從當(dāng)前目錄查找

2.數(shù)據(jù)集
這部分我是對(duì)MNIST數(shù)據(jù)集進(jìn)行處理保存
對(duì)應(yīng)代碼:
import tensorflow as tf
import matplotlib.pyplot as plt
import cv2
from PIL import Image
import numpy as np
from scipy import misc
(x_train_all,y_train_all),(x_test,y_test) = tf.keras.datasets.mnist.load_data()
x_valid,x_train = x_train_all[:5000],x_train_all[5000:]
y_valid,y_train = y_train_all[:5000],y_train_all[5000:]
print(x_valid.shape,y_valid.shape)
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)
#讀取單張圖片
def show_single_img(img_arr,len=100,path='/Users/zhangcaihui/Desktop/case/jpg/'):
for i in range(len):#我這種寫法會(huì)進(jìn)行覆蓋,只能保存10張照片,想保存更多的數(shù)據(jù)自己看著改
new_im = Image.fromarray(img_arr[i]) # 調(diào)用Image庫,數(shù)組歸一化
#new_im.show()
#plt.imshow(img_arr) # 顯示新圖片
label=y_train[i]
new_im.save(path+str(label)+'.jpg') # 保存圖片到本地
#顯示多張圖片
def show_imgs(n_rows,n_cols,x_data,y_data):
assert len(x_data) == len(y_data)
assert n_rows * n_cols < len(x_data)
plt.figure(figsize=(n_cols*1.4,n_rows*1.6))
for row in range(n_rows):
for col in range(n_cols):
index = n_cols * row + col
plt.subplot(n_rows,n_cols,index+1)
plt.imshow(x_data[index],cmap="binary",interpolation="nearest")
plt.axis("off")
plt.show()
#show_imgs(2,2,x_train,y_train)
show_single_img(x_train)
3.關(guān)于模型
我保存了了之前訓(xùn)練好的模型,用來加載預(yù)測(cè)
關(guān)于tensorflow下訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型:手把手教你,MNIST手寫數(shù)字識(shí)別
訓(xùn)練好的模型model.save(path)即可
4.關(guān)于GUI設(shè)計(jì)
1)排版
#ui_openimage.py
# -*- coding: utf-8 -*-
# from PyQt5 import QtCore, QtGui, QtWidgets
# from PyQt5.QtCore import Qt
import sys,time
from PyQt5 import QtGui, QtCore, QtWidgets
from 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, 750)
self.label_1 = QtWidgets.QLabel(Form)
self.label_1.setGeometry(QtCore.QRect(170, 130, 351, 251))
self.label_1.setObjectName("label_1")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(680, 140, 351, 251))
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,93,28))
self.btn_recognition.setObjectName("bnt_recognition")
#顯示時(shí)間按鈕
self.bnt_timeshow = QtWidgets.QPushButton(Form)
self.bnt_timeshow.setGeometry(QtCore.QRect(900,0,200,50))
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): #設(shè)置文本填充label、button
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "數(shù)字識(shí)別系統(tǒng)"))
self.label_1.setText(_translate("Form", "點(diǎn)擊下方按鈕"))
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", "選擇圖片"))
self.btn_recognition.setText(_translate("From","識(shí)別結(jié)果"))
self.bnt_timeshow.setText(_translate("Form","當(dāng)前時(shí)間"))
# 狀態(tài)條顯示時(shí)間模塊
def buttonClicked(self): # 動(dòng)態(tài)顯示時(shí)間
timer = QTimer(self)
timer.timeout.connect(self.showtime)
timer.start()
def showtime(self):
datetime = QDateTime.currentDateTime()
time_now = time.strftime('%Y-%m-%d %H:%M:%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):#窗口放置中央
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)直接運(yùn)行這個(gè)文件(調(diào)用1)
#ui_main.py
import random
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtGui import QPixmap
from ui_openimage import Ui_Form
import sys
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication
import os,sys
from PyQt5.QtCore import Qt
import tensorflow
from tensorflow.keras.models import load_model
from tensorflow.keras.datasets import mnist
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import tensorflow.keras.preprocessing.image as image
import matplotlib.pyplot as plt
import numpy as np
import cv2
import warnings
warnings.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, '打開多個(gè)圖片', 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為之前保存的模型路徑'''
path='/Users/zhangcaihui/PycharmProjects/py38_tf/DL_book_keras/save_the_model.h5'
model= load_model(path)
#防止不上傳數(shù)字照片而直接點(diǎn)擊識(shí)別
if self.img==None:
self.label_2.setText('請(qǐng)上傳照片!')
return
img = image.load_img(self.img, target_size=(28, 28))
img = img.convert('L')#轉(zhuǎn)灰度圖像
x = image.img_to_array(img)
#x = abs(255 - x)
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("手寫數(shù)字識(shí)別為:" + 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.缺點(diǎn)
界面low
只能識(shí)別單個(gè)數(shù)字
其實(shí)可以將多數(shù)字圖片進(jìn)行裁剪分割,這就涉及到制作數(shù)據(jù)集了
6.遺留問題
我自己手寫的數(shù)據(jù)照片處理成28281送入網(wǎng)絡(luò)預(yù)測(cè),識(shí)別結(jié)果紊亂。
反思:自己寫的數(shù)據(jù)是RGB,且一張幾KB,圖片預(yù)處理后,按28*28讀入失真太嚴(yán)重了,誰有好的方法可以聯(lián)系我?。?!
其他的水果識(shí)別系統(tǒng),手勢(shì)識(shí)別系統(tǒng)啊,改改直接套!
到此這篇關(guān)于Python實(shí)現(xiàn)帶GUI界面的手寫數(shù)字識(shí)別的文章就介紹到這了,更多相關(guān)Python手寫數(shù)字識(shí)別內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信