在参考了一篇博客[https://blog.csdn.net/qq_38269418/article/details/78991649#commentsedit],是手写数字识别的内容,具体环境大家可以自己去配置以及去参考这个链接的博客去学习。
我在这里将整个识别的过程写成了一个GUI,采用的是pyqt5,只是实现了手写数字图片的识别。
下面是全部代码:
# -*- coding:utf-8 -*-
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PIL import Image
import tensorflow as tf
import matplotlib.pyplot as plt
class DigitalRecognition(QMainWindow):
def __init__(self):
super(DigitalRecognition, self).__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("手写数字识别")
self.resize(300,150)
_translate = QtCore.QCoreApplication.translate
self.button1=QPushButton("选择图片",self)
self.button1.move(35,100)
self.button1.resize(80,30)
self.button1.clicked.connect(self.select_image)
self.button2 = QPushButton("识别", self)
self.button2.move(150, 100)
self.button2.resize(80, 30)
self.button2.clicked.connect(self.recognition)
self.edit=QTextEdit(self)
self.edit.move(120,20)
self.edit.resize(150,80)
self.edit.setPlaceholderText(_translate("MainWindow", "结果显示"))
self.label=QLabel("待载入图片",self)
self.label.move(35,20)
self.label.resize(80,80)
self.label.setStyleSheet("QLabel{background:gray;}"
"QLabel{color:rgb(0,0,0,120);font-size:15px;font-weight:bold;font-family:宋体;}"
)
def select_image(self):
global fname
imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.png;;*.jpg;;All Files(*)")
jpg = QtGui.QPixmap(imgName).scaled(self.label.width(), self.label.height())
self.label.setPixmap(jpg)
fname = imgName
def recognition(self):
global fname
def imageprepare():
"""
This function returns the pixel values.
The imput is a png file location.
"""
file_name = str(fname) # 导入自己的图片地址
# in terminal 'mogrify -format png *.jpg' convert jpg to png
im = Image.open(file_name)
plt.imshow(im)
#plt.show()
im = im.convert('L')
tv = list(im.getdata()) # get pixel values
# normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
tva = [(255 - x) * 1.0 / 255.0 for x in tv]
#print(tva)
return tva
"""
This function returns the predicted integer.
The imput is the pixel values from the imageprepare() function.
"""
# Define the model (same as when creating the model file)
result = imageprepare()
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess, "这里写上你自己的model.ckpt的路径") # 这里使用了之前保存的模型参数
# print ("Model restored.")
prediction = tf.argmax(y_conv, 1)
predint = prediction.eval(feed_dict={
x: [result], keep_prob: 1.0}, session=sess)
print(h_conv2)
#print('识别结果:')
#print('识别的手写数字是>>>'+str(predint[0]))
self.edit.setText('识别的手写数字是>>>'+str(predint[0]))
if __name__=="__main__":
app=QApplication(sys.argv)
main=DigitalRecognition()
palette = QPalette()
pix5 = QPixmap("这里写上你自己的图片路径")#背景图
pix=pix5.scaled(main.width(),main.height())#自适应窗口大小
palette.setBrush(QPalette.Background, QBrush(pix))
main.setPalette(palette)
main.show()
sys.exit(app.exec_())
整体上我使用的绝对布局,不是用的qtdesigner画的 是手写的代码生成的。
定义了全局的路径
下面是运行效果:
识别情况:
参考博客:https://blog.csdn.net/qq_38269418/article/details/78991649#commentsedit
继续学习