python tensorflow學(xué)習(xí)之識(shí)別單張圖片的實(shí)現(xiàn)的示例
假設(shè)我們已經(jīng)安裝好了tensorflow。
一般在安裝好tensorflow后,都會(huì)跑它的demo,而最常見的demo就是手寫數(shù)字識(shí)別的demo,也就是mnist數(shù)據(jù)集。
然而我們僅僅是跑了它的demo而已,可能很多人會(huì)有和我一樣的想法,如果拿來一張數(shù)字圖片,如何應(yīng)用我們訓(xùn)練的網(wǎng)絡(luò)模型來識(shí)別出來,下面我們就以mnist的demo來實(shí)現(xiàn)它。
1.訓(xùn)練模型
首先我們要訓(xùn)練好模型,并且把模型model.ckpt保存到指定文件夾
saver = tf.train.Saver() saver.save(sess, "model_data/model.ckpt")
將以上兩行代碼加入到訓(xùn)練的代碼中,訓(xùn)練完成后保存模型即可,如果這部分有問題,你可以百度查閱資料,tensorflow怎么保存訓(xùn)練模型,在這里我們就不羅嗦了。
2.測(cè)試模型
我們訓(xùn)練好模型后,將它保存在了model_data文件夾中,你會(huì)發(fā)現(xiàn)文件夾中出現(xiàn)了4個(gè)文件
然后,我們就可以對(duì)這個(gè)模型進(jìn)行測(cè)試了,將待檢測(cè)圖片放在images文件夾下,執(zhí)行
# -*- coding:utf-8 -*- import cv2 import tensorflow as tf import numpy as np from sys import path path.append('../..') from common import extract_mnist #初始化單個(gè)卷積核上的參數(shù) def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) #初始化單個(gè)卷積核上的偏置值 def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) #輸入特征x,用卷積核W進(jìn)行卷積運(yùn)算,strides為卷積核移動(dòng)步長(zhǎng), #padding表示是否需要補(bǔ)齊邊緣像素使輸出圖像大小不變 def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') #對(duì)x進(jìn)行最大池化操作,ksize進(jìn)行池化的范圍, def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') def main(): #定義會(huì)話 sess = tf.InteractiveSession() #聲明輸入圖片數(shù)據(jù),類別 x = tf.placeholder('float',[None,784]) x_img = tf.reshape(x , [-1,28,28,1]) W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) W_conv2 = weight_variable([5,5,32,64]) b_conv2 = bias_variable([64]) W_fc1 = weight_variable([7*7*64,1024]) b_fc1 = bias_variable([1024]) W_fc2 = weight_variable([1024,10]) b_fc2 = bias_variable([10]) saver = tf.train.Saver(write_version=tf.train.SaverDef.V1) saver.restore(sess , 'model_data/model.ckpt') #進(jìn)行卷積操作,并添加relu激活函數(shù) h_conv1 = tf.nn.relu(conv2d(x_img,W_conv1) + b_conv1) #進(jìn)行最大池化 h_pool1 = max_pool_2x2(h_conv1) #同理第二層卷積層 h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) #將卷積的產(chǎn)出展開 h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64]) #神經(jīng)網(wǎng)絡(luò)計(jì)算,并添加relu激活函數(shù) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1) #輸出層,使用softmax進(jìn)行多分類 y_conv=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2) # mnist_data_set = extract_mnist.MnistDataSet('../../data/') # x_img , y = mnist_data_set.next_train_batch(1) im = cv2.imread('images/888.jpg',cv2.IMREAD_GRAYSCALE).astype(np.float32) im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC) #圖片預(yù)處理 #img_gray = cv2.cvtColor(im , cv2.COLOR_BGR2GRAY).astype(np.float32) #數(shù)據(jù)從0~255轉(zhuǎn)為-0.5~0.5 img_gray = (im - (255 / 2.0)) / 255 #cv2.imshow('out',img_gray) #cv2.waitKey(0) x_img = np.reshape(img_gray , [-1 , 784]) print x_img output = sess.run(y_conv , feed_dict = {x:x_img}) print 'the y_con : ', '\n',output print 'the predict is : ', np.argmax(output) #關(guān)閉會(huì)話 sess.close() if __name__ == '__main__': main()
ok,貼一下效果圖
輸出:
最后再貼一個(gè)cifar10的,感覺我的輸入數(shù)據(jù)有點(diǎn)問題,因?yàn)橹苯幼xcifar10的數(shù)據(jù)測(cè)試是沒問題的,但是換成自己的圖片做預(yù)處理后輸入結(jié)果就有問題,(參考:cv2讀入的數(shù)據(jù)是BGR順序,PIL讀入的數(shù)據(jù)是RGB順序,cifar10的數(shù)據(jù)是RGB順序),哪位童鞋能指出來記得留言告訴我
# -*- coding:utf-8 -*- from sys import path import numpy as np import tensorflow as tf import time import cv2 from PIL import Image path.append('../..') from common import extract_cifar10 from common import inspect_image #初始化單個(gè)卷積核上的參數(shù) def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) #初始化單個(gè)卷積核上的偏置值 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 main(): #定義會(huì)話 sess = tf.InteractiveSession() #聲明輸入圖片數(shù)據(jù),類別 x = tf.placeholder('float',[None,32,32,3]) y_ = tf.placeholder('float',[None,10]) #第一層卷積層 W_conv1 = weight_variable([5, 5, 3, 64]) b_conv1 = bias_variable([64]) #進(jìn)行卷積操作,并添加relu激活函數(shù) conv1 = tf.nn.relu(conv2d(x,W_conv1) + b_conv1) # pool1 pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],padding='SAME', name='pool1') # norm1 norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,name='norm1') #第二層卷積層 W_conv2 = weight_variable([5,5,64,64]) b_conv2 = bias_variable([64]) conv2 = tf.nn.relu(conv2d(norm1,W_conv2) + b_conv2) # norm2 norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,name='norm2') # pool2 pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1],strides=[1, 2, 2, 1], padding='SAME', name='pool2') #全連接層 #權(quán)值參數(shù) W_fc1 = weight_variable([8*8*64,384]) #偏置值 b_fc1 = bias_variable([384]) #將卷積的產(chǎn)出展開 pool2_flat = tf.reshape(pool2,[-1,8*8*64]) #神經(jīng)網(wǎng)絡(luò)計(jì)算,并添加relu激活函數(shù) fc1 = tf.nn.relu(tf.matmul(pool2_flat,W_fc1) + b_fc1) #全連接第二層 #權(quán)值參數(shù) W_fc2 = weight_variable([384,192]) #偏置值 b_fc2 = bias_variable([192]) #神經(jīng)網(wǎng)絡(luò)計(jì)算,并添加relu激活函數(shù) fc2 = tf.nn.relu(tf.matmul(fc1,W_fc2) + b_fc2) #輸出層,使用softmax進(jìn)行多分類 W_fc2 = weight_variable([192,10]) b_fc2 = bias_variable([10]) y_conv=tf.maximum(tf.nn.softmax(tf.matmul(fc2, W_fc2) + b_fc2),1e-30) # saver = tf.train.Saver() saver.restore(sess , 'model_data/model.ckpt') #input im = Image.open('images/dog8.jpg') im.show() im = im.resize((32,32)) # r , g , b = im.split() # im = Image.merge("RGB" , (r,g,b)) print im.size , im.mode im = np.array(im).astype(np.float32) im = np.reshape(im , [-1,32*32*3]) im = (im - (255 / 2.0)) / 255 batch_xs = np.reshape(im , [-1,32,32,3]) #print batch_xs #獲取cifar10數(shù)據(jù) # cifar10_data_set = extract_cifar10.Cifar10DataSet('../../data/') # batch_xs, batch_ys = cifar10_data_set.next_train_batch(1) # print batch_ys output = sess.run(y_conv , feed_dict={x:batch_xs}) print output print 'the out put is :' , np.argmax(output) #關(guān)閉會(huì)話 sess.close() if __name__ == '__main__': main()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python使用TensorFlow進(jìn)行圖像處理的方法
- Python通過TensorFLow進(jìn)行線性模型訓(xùn)練原理與實(shí)現(xiàn)方法詳解
- Python Tensor FLow簡(jiǎn)單使用方法實(shí)例詳解
- Python tensorflow實(shí)現(xiàn)mnist手寫數(shù)字識(shí)別示例【非卷積與卷積實(shí)現(xiàn)】
- Python3.7安裝keras和TensorFlow的教程圖解
- python3讀取圖片并灰度化圖片的四種方法(OpenCV、PIL.Image、TensorFlow方法)總結(jié)
- python3.6.3安裝圖文教程 TensorFlow安裝配置方法
- python生成tensorflow輸入輸出的圖像格式的方法
- Python圖像處理之識(shí)別圖像中的文字(實(shí)例講解)
- Python基于Tensor FLow的圖像處理操作詳解
相關(guān)文章
pandas?dataframe?drop函數(shù)介紹
這篇文章主要介紹了pandas?dataframe?drop函數(shù)介紹,文章通圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09Python網(wǎng)絡(luò)編程基于多線程實(shí)現(xiàn)多用戶全雙工聊天功能示例
這篇文章主要介紹了Python網(wǎng)絡(luò)編程基于多線程實(shí)現(xiàn)多用戶全雙工聊天功能,結(jié)合實(shí)例形式分析了Python網(wǎng)絡(luò)編程中使用多線程進(jìn)行多用戶異步通信的原理與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-04-04Python學(xué)習(xí)之路之pycharm的第一個(gè)項(xiàng)目搭建過程
這篇文章主要介紹了Python學(xué)習(xí)之路之pycharm的第一個(gè)項(xiàng)目搭建過程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06python爬蟲系列網(wǎng)絡(luò)請(qǐng)求案例詳解
這篇文章主要介紹了【Python從零到壹】python爬蟲系列-網(wǎng)絡(luò)請(qǐng)求,從零開始學(xué)習(xí)Python網(wǎng)絡(luò)爬蟲,如何從中獲取需要的數(shù)據(jù)信息,現(xiàn)整理出零基礎(chǔ)如何學(xué)爬蟲技術(shù)以供學(xué)習(xí)2021-04-04使用Python將數(shù)組的元素導(dǎo)出到變量中(unpacking)
最近工作中遇到一個(gè)問題,需要利用Python將數(shù)組(list)或元組(tuple)中的元素導(dǎo)出到N個(gè)變量中,現(xiàn)在將我實(shí)現(xiàn)的方法分享給大家,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10Python編程實(shí)現(xiàn)的圖片識(shí)別功能示例
這篇文章主要介紹了Python編程實(shí)現(xiàn)的圖片識(shí)別功能,涉及Python PIL模塊的安裝與使用技巧,需要的朋友可以參考下2017-08-08