tensorflow筆記(第六章)

斷點(diǎn)續(xù)訓(xùn),在mnist_backward.py中的with tf.Session()下加入ckpt的那三句話

圖片.png

實(shí)現(xiàn)輸入手寫數(shù)字圖片輸出識別結(jié)果

代碼可能存在未對齊的情況

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
#預(yù)處理
def pre_pic(picName):
    img = Image.open(picName) #打開傳入的圖片
    reIm = img.resize((28,28), Image.ANTIALIAS)  #為符合shape,用消除鋸齒的方法resize
    im_arr = np.array(reIm.convert('L')) #為符合顏色的要求,變成灰度圖,并轉(zhuǎn)化成矩陣的形式
    threshold = 50
    #模型要求輸入的是黑底白字,我們輸入的圖片是白底黑字
    #反色
    for i in range(28):
        for j in range(28):
            im_arr[i][j] = 255 - im_arr[i][j]  #求得互補(bǔ)的反色
            if (im_arr[i][j] < threshold):  #給圖片做二值化處理,讓圖片只有純白色點(diǎn)和純黑色點(diǎn),可以濾掉手寫數(shù)字圖片中的噪聲,留下圖片主要特征
            #灰度圖像二值化最常用的方法是閾值法,他利用圖像中目標(biāo)與背景的差異,把圖像分別設(shè)置為兩個不同的級別,選取一個合適的閾值,以確定某像素是目標(biāo)還是背景,從而獲得二值化的圖像。
                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函數(shù)可以實(shí)現(xiàn)從控制臺讀入數(shù)字
    for i in range(testNum):
        testPic = input("the path of test picture:") #給出識別圖片的路徑和名稱,raw_input函數(shù)實(shí)現(xiàn)從控制臺讀入字符串
        testPicArr = pre_pic(testPic)
        preValue = restore_model(testPicArr)
        print "The prediction number is:", preValue

def main():
    application()

if __name__ == '__main__':
    main()      

代碼及手寫圖片下載地址
我自己手寫了一個5,結(jié)果給我識別成3了,嗚嗚嗚~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容