深度学习与TensorFlow实战(七)全连接网络基础—真实图片输出手写数字识别准确率

本节会涉及一些简单的图像处理操作,具体的可以看我写的OpenCV图像处理博文,是用C++写,但本节用的是Python里面PIL 图像处理库,只是语言不一样,本质原理是一样的。以后有时间我会写一个系列关于OpenCV图像处理Python版的。
关于PIL操作可以参考博文:https://www.jianshu.com/p/e8d058767dfa

输入真实图片,输出预测结果
深度学习与TensorFlow实战(七)全连接网络基础—真实图片输出手写数字识别准确率_第1张图片

网络输入:一组数组(784个像素点)
深度学习与TensorFlow实战(七)全连接网络基础—真实图片输出手写数字识别准确率_第2张图片

像素点:0-1之间的浮点数(越接近0越黑,越接近1越白)

网络输出:一维数组(十个可能性概率),数组中最大的那个元素对应的索引号就是预测结果。

关键处理:

def application():  
   testNum =input("input the number of test pictures:")     
   for i in range(testNum):
       testPic =input("the path of test picture:")         
       testPicArr = pre_pic(testPic)         
       preValue = restore_model(testPicArr)         
       print ("Theprediction number is:",preValue)  

注解: 任务分成两个函数完成

1)testPicArr =pre_pic(testPic)对手写数字图片做预处理

2)preValue =restore_model(testPicArr) 将符合神经网络输入要求的图片喂给复现的神经网络模型,输出预测值

代码如下:

import tensorflow as tf
import numpy as np
from PIL import Image
import fb_mnist


def restore_model(testPicArr):
    # 利用tf.Graph()复现之前定义的计算图
    with tf.Graph().as_default() as g:
        x = tf.placeholder(tf.float32, shape=[None, fb_mnist.INPUT_NODE])
        y = fb_mnist.forward(x, None)
        # 得到概率最大的预测值
        preValue = tf.argmax(y, 1)

        # 实例化具有滑动平均的saver对象
        variable_averages = tf.train.ExponentialMovingAverage(fb_mnist.MOVING_AVERAGE_DECAY)
        variable_restore = variable_averages.variables_to_restore()
        saver = tf.train.Saver(variable_restore)

        with tf.Session() as sess:
            ckpt = tf.train.get_checkpoint_state(fb_mnist.MODEL_SAVE_PATH)
            if ckpt and ckpt.model_checkpoint_path:
                saver.restore(sess, ckpt.model_checkpoint_path)

                preValue = sess.run(preValue, feed_dict={x: testPicArr})
                return preValue
            else:
                print("No checkpoint file found")
                return -1


# 预处理,包括resize,转变灰度图,二值化
def pre_pic(picName):
    img = Image.open(picName)
    reIm = img.resize((28, 28), Image.ANTIALIAS)
    im_arr = np.array(reIm.convert('L'))  # 转灰度
    # 对图片做二值化处理,去除噪声
    threshlod = 50  # 阈值大小
    # 模型是要求是黑底白字,但输入的图片是白底黑字,所以要对每个像素点的值改为255减去原值得到互补的反色
    for i in range(28):
        for j in range(28):
            im_arr[i][j] = 255 - im_arr[i][j]
            if (im_arr[i][j] < threshlod):
                im_arr[i][j] = 0
            else:
                im_arr[i][j] = 255
    # 把图片形状拉成1行784列,并把值变为浮点型(因为要求像素点是0-1之间的浮点数)
    nm_arr = im_arr.reshape([1, 784])
    nm_arr = nm_arr.astype(np.float32)
    img_ready = np.multiply(nm_arr, 1.0 / 255.0)
    return img_ready


# 输入几张要识别的图片
def application():
    testNum = input("input the number of test pictures:")
    for i in range(int(testNum)):
        # 图片的路径和名称
        testPic = input("the path of test picture:")
        # 图片预处理
        testPicArr = pre_pic(testPic)
        preValue = restore_model(testPicArr)
        print("the prediction number is:", preValue)


def main():
    application()


if __name__ == '__main__':
    main()

首先要运行上一节里面的fb_mnist.py文件和test_mnist.py文件,最后运行上面文件代码,得到结果:
深度学习与TensorFlow实战(七)全连接网络基础—真实图片输出手写数字识别准确率_第3张图片
深度学习与TensorFlow实战(七)全连接网络基础—真实图片输出手写数字识别准确率_第4张图片
有一张数字8识别错了,应该是我训练的轮数少了,准备率还不高。

未完待续………………………………………………(缺:tfrecords:是一种二进制文件,可先将图片和标签制作成该格式的文件。使用tfrecords进行数据读取,会提高内存利用率。暂时用不到,以后用到再来补充)

你可能感兴趣的:(深度学习与TensorFlow实战(七)全连接网络基础—真实图片输出手写数字识别准确率)