tensorflow notes (Chapter VI)

Resume training, with the mnist_backward.py in tf.Session (lower) ckpt added that three sentences

11956727-49a939a33f456347.png
Pictures .png

Implement input handwriting recognition results output digital pictures

Code may be a case misaligned

mnist_app.py

#coding:utf-8
import tensorflow as tf
import numpy as np
from PIL import Image
import mnist_backward
import mnist_forward

def restore_model(testPicArr):
    with tf.Graph().as_default() as tg:
        x = tf.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE])
        y = mnist_forward.forward(x, None)
        preValue = tf.argmax(y, 1)
        variable_averages = tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)
        variables_to_restore = variable_averages.variables_to_restore()
        saver = tf.train.Saver(variables_to_restore)

        with tf.Session() as sess:
            ckpt = tf.train.get_checkpoint_state(mnist_backward.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
#预处理
def pre_pic(picName):
    img = Image.open(picName) #打开传入的图片
    reIm = img.resize((28,28), Image.ANTIALIAS)  #为符合shape,用消除锯齿的方法resize
    im_arr = np.array(reIm.convert('L')) #为符合颜色的要求,变成灰度图,并转化成矩阵的形式
    threshold = 50
    #模型要求输入的是黑底白字,我们输入的图片是白底黑字
    #反色
    for i in range(28):
        for j in range(28):
            im_arr[i][j] = 255 - im_arr[i][j]  #求得互补的反色
            if (im_arr[i][j] < threshold):  #给图片做二值化处理,让图片只有纯白色点和纯黑色点,可以滤掉手写数字图片中的噪声,留下图片主要特征
            #灰度图像二值化最常用的方法是阈值法,他利用图像中目标与背景的差异,把图像分别设置为两个不同的级别,选取一个合适的阈值,以确定某像素是目标还是背景,从而获得二值化的图像。
                im_arr[i][j] = 0 #纯黑色是0
            else: im_arr[i][j] = 255 #纯白色255

    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 = int(input("input the number of test pictures:") )#输入要识别几张图片,input函数可以实现从控制台读入数字
    for i in range(testNum):
        testPic = input("the path of test picture:") #给出识别图片的路径和名称,raw_input函数实现从控制台读入字符串
        testPicArr = pre_pic(testPic)
        preValue = restore_model(testPicArr)
        print "The prediction number is:", preValue

def main():
    application()

if __name__ == '__main__':
    main()      

Download the code and handwritten picture
of my own handwriting a 5, the results give me recognition as a 3, ooo, ooo ~

Reproduced in: https: //www.jianshu.com/p/da6c4e018111

Guess you like

Origin blog.csdn.net/weixin_33725722/article/details/91229053