基于TensorFlow的手写数字识别 (图形界面使用的是pyqt5)

本文参考自:使用Tensorflow和MNIST识别自己手写的数字 ,因此标注了转载。
不同点在于增加了识别部分的部分注释,并且写了图形界面,另外,去掉了openCV处理图像的部分。

Tensorflow和MNIST简介

TensorFlow™ 是一个采用数据流图,用于数值计算的开源软件库。它是一个不严格的“神经网络”库,可以利用它提供的模块搭建大多数类型的神经网络。它可以基于CPU或GPU运行,可以自动使用GPU,无需编写分配程序。主要支持Python编写,但是官方说也有C++使用界面。

MNIST是一个巨大的手写数字数据集,被广泛应用于机器学习识别领域。MNIST有60000张训练集数据和10000张测试集数据,每一个训练元素都是28*28像素的手写数字图片。作为一个常见的数据集,MNIST经常被用来测试神经网络,也是比较基本的应用。

CNN算法

识别算法主要使用的是卷积神经网络算法(CNN)。
主要结构为:输入-卷积层-池化层-卷积层-池化层-全连接层-输出

卷积
卷积其实可以看做是提取特征的过程。如果不使用卷积的话,整个网络的输入量就是整张图片,处理就很困难。
卷积

假设图中绿色5*5矩阵为原图片,黄色的3*3矩阵就是我们的过滤器,即卷积核。将黄色矩阵和绿色矩阵被覆盖的部分进行卷积计算,即每个元素相乘求和,便可得到这一部分的特征值,即图中的卷积特征。
然后,向右滑动黄色的矩阵,便可继续求下一部分的卷积特征值。而滑动的距离就是步长。

池化
池化是用来把卷积结果进行压缩,进一步减少全连接时的连接数。
池化
池化有两种:
一种是最大池化,在选中区域中找最大的值作为抽样后的值;
一种是平均值池化,把选中的区域中的平均值作为抽样后的值。

实现过程

1.训练程序

主体和tensorflow教程上大致相同。值得注意的是其中的saver部分,将训练的权重和偏置保存下来,在评价程序中可以再次使用。
注意一定要等20000跑完,不然模型无法保存,在后来的程序中会报错。如果是cpu版本的TensorFlow可能会需要半小时以上…在开始测试的时候可以先降低迭代次数,但是这样可能会使识别率降低,最后要再改回20000跑一遍这个程序。

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)


sess = tf.InteractiveSession()


x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))


sess.run(tf.global_variables_initializer())

y = tf.matmul(x,W) + b

cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

for _ in range(1000):
  batch = mnist.train.next_batch(100)
  train_step.run(feed_dict={x: batch[0], y_: batch[1]})


correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

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(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=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, tf.float32))

saver = tf.train.Saver()  # defaults to saving all variables

sess.run(tf.global_variables_initializer())
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print("step %d, training accuracy %g"%(i, train_accuracy))

  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
saver.save(sess, 'C:/desktop/model.ckpt')  #保存模型参数,注意把这里改为自己的路径

print("test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

2.图形界面类

我是使用 QtDesigner进行的界面设计(尽管非常丑),可以自主选择图片路径并在界面上显示,点击开始识别,显示识别结果。
最后效果:
图形界面效果
代码如下:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'first.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(370, 499)
        font = QtGui.QFont()
        font.setFamily("黑体")
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 30, 201, 21))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.confirmButton = QtWidgets.QPushButton(self.centralwidget)
        self.confirmButton.setGeometry(QtCore.QRect(220, 30, 41, 23))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.confirmButton.setFont(font)
        self.confirmButton.setObjectName("confirmButton")
        self.labelImage = QtWidgets.QLabel(self.centralwidget)
        self.labelImage.setGeometry(QtCore.QRect(40, 90, 271, 271))
        self.labelImage.setText("")
        self.labelImage.setObjectName("labelImage")
        self.result = QtWidgets.QLabel(self.centralwidget)
        self.result.setGeometry(QtCore.QRect(180, 400, 111, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.result.setFont(font)
        self.result.setObjectName("result")
        self.start = QtWidgets.QPushButton(self.centralwidget)
        self.start.setGeometry(QtCore.QRect(60, 400, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.start.setFont(font)
        self.start.setObjectName("start")
        # MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 370, 23))
        self.menubar.setObjectName("menubar")
        # MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        # MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.confirmButton.clicked.connect(MainWindow.openImage)
        self.start.clicked.connect(MainWindow.startRecognize)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "请选择需要识别的图片路径:"))
        self.confirmButton.setText(_translate("MainWindow", "选择"))
        self.result.setText(_translate("MainWindow", "识别结果:"))
        self.start.setText(_translate("MainWindow", "开始识别"))

3.继承图形界面类并编写槽函数,实现识别

值得注意的是由于没有写处理图片的代码,因此选择图片时只能选择28*28像素的图片(自己事先处理过)才可以进行识别。(预处理的原因是训练集中的图片是28*28二值化的,要和训练集中的图片格式保持一致才能识别)

import sys

from first import Ui_MainWindow
from PIL import Image, ImageFilter
import tensorflow as tf
import matplotlib.pyplot as plt
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QFileDialog


class mywindow(QtWidgets.QWidget, Ui_MainWindow):

    x = tf.placeholder(tf.float32, [None, 784])  # placeholder:tensorflow中保存数据,第一个参数是要保存的数据类型,大多数是tensorflow中的float32数据类型,后面的参数就是要保存数据的结构,比如要保存一个1×2的矩阵,则struct=[1 2]
    W = tf.Variable(tf.zeros([784, 10]))  # zeros:产生全零数组 Variable:可以是任何类型和形状的Tensor(张量)
    b = tf.Variable(tf.zeros([10]))

    def __init__(self):
        super(mywindow, self).__init__()
        self.setupUi(self)
        self.imgName = ""  # 成员变量需要初始化


    # 槽函数打开图片
    def openImage(self):

        # 打开文件路径
        # 设置文件扩展名过滤,注意用双分号间隔
        self.imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", " *.png;;*.jpg;;*.jpeg;;*.bmp;;All Files (*)")
        print(self.imgName) # imgName就是图片的路径,为了之后在识别的时候也可以用,写成了self.imgName,self代表创建的实例本身
        # 利用qlabel显示图片
        png = QtGui.QPixmap(self.imgName).scaled(self.labelImage.width(), self.labelImage.height())
        self.labelImage.setPixmap(png)

    def weight_variable(self, shape):
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial)

    def bias_variable(self, shape):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)

    def conv2d(self, x, W):
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

    def max_pool_2x2(self, x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    # 槽函数开始识别
    def startRecognize(self):
        im = Image.open(self.imgName).convert('L')  # 将当前的图像转换为新的模式,并产生新的图像作为返回值。L是指灰色图像。1是非黑即白
        im.save("number/sample.png")  # 经过测试后的图片命名为sample并保存该文件夹下
        # plt.imshow(im)
        # plt.show()  # 用于显示图片,需要关掉图片才能往下走
        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]  # 这里得到的是处理之后的一个list,反映了每个像素点的值,用于描述图像
        # print(tva)

        W_conv1 = self.weight_variable([5, 5, 1, 32])
        b_conv1 = self.bias_variable([32])

        x_image = tf.reshape(self.x, [-1, 28, 28, 1])  # tf.reshape():解决输入图像的维数不符合的情况
        h_conv1 = tf.nn.relu(self.conv2d(x_image, W_conv1) + b_conv1)  # 计算激活函数,将矩阵中的非最大值置零
        h_pool1 = self.max_pool_2x2(h_conv1)

        W_conv2 = self.weight_variable([5, 5, 32, 64])
        b_conv2 = self.bias_variable([64])

        h_conv2 = tf.nn.relu(self.conv2d(h_pool1, W_conv2) + b_conv2)
        h_pool2 = self.max_pool_2x2(h_conv2)

        W_fc1 = self.weight_variable([7 * 7 * 64, 1024])
        b_fc1 = self.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(tf.float32)
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

        W_fc2 = self.weight_variable([1024, 10])
        b_fc2 = self.bias_variable([10])

        y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

        init_op = tf.initialize_all_variables()

        saver = tf.train.Saver()
        with tf.Session() as sess:# with…as用于代替传统的try…finally语法 session用于运行图表
            sess.run(init_op)
            saver.restore(sess, "C:/desktop/model.ckpt")  # 这里使用了之前保存的模型参数
            # print ("Model restored.")

            prediction = tf.argmax(y_conv, 1)
            predint = prediction.eval(feed_dict={self.x: [tva], keep_prob: 1.0}, session=sess)
            # print(h_conv2)

            print('recognize result:')
            print(predint[0])
            self.result.setText("识别结果:"+str(predint[0]))


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    myshow = mywindow()
    myshow.show()

    sys.exit(app.exec_())
  • 4
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值