python tensorflow學(xué)習(xí)之識(shí)別單張圖片的實(shí)現(xiàn)的示例
假設(shè)我們已經(jīng)安裝好了tensorflow。
一般在安裝好tensorflow后,都會(huì)跑它的demo,而最常見的demo就是手寫數(shù)字識(shí)別的demo,也就是mnist數(shù)據(jù)集。
然而我們僅僅是跑了它的demo而已,可能很多人會(huì)有和我一樣的想法,如果拿來(lái)一張數(shù)字圖片,如何應(yīng)用我們訓(xùn)練的網(wǎng)絡(luò)模型來(lái)識(shí)別出來(lái),下面我們就以mnist的demo來(lái)實(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)練完成后保存模型即可,如果這部分有問(wè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的,感覺(jué)我的輸入數(shù)據(jù)有點(diǎn)問(wèn)題,因?yàn)橹苯幼xcifar10的數(shù)據(jù)測(cè)試是沒(méi)問(wèn)題的,但是換成自己的圖片做預(yù)處理后輸入結(jié)果就有問(wèn)題,(參考:cv2讀入的數(shù)據(jù)是BGR順序,PIL讀入的數(shù)據(jù)是RGB順序,cifar10的數(shù)據(jù)是RGB順序),哪位童鞋能指出來(lái)記得留言告訴我
# -*- 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通過(guò)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)文章
使用Python實(shí)現(xiàn)搖號(hào)系統(tǒng)的詳細(xì)步驟
這篇文章主要介紹了如何使用Python構(gòu)建一個(gè)簡(jiǎn)單的搖號(hào)系統(tǒng),包括需求分析、技術(shù)棧、實(shí)現(xiàn)步驟和完整代碼示例,該系統(tǒng)能夠從用戶輸入的參與者名單中隨機(jī)抽取指定數(shù)量的中獎(jiǎng)?wù)?并將結(jié)果展示給用戶以及記錄到日志文件中,需要的朋友可以參考下2024-11-11
Anaconda多環(huán)境多版本python配置操作方法
下面小編就為大家?guī)?lái)一篇Anaconda多環(huán)境多版本python配置操作方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09
Python設(shè)計(jì)模式結(jié)構(gòu)型代理模式
這篇文章主要介紹了Python設(shè)計(jì)模式結(jié)構(gòu)型代理模式,代理模式即Proxy?Pattern,為其他對(duì)象提供一種代理以控制對(duì)這個(gè)對(duì)象的訪問(wèn),下文內(nèi)容詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-02-02
跟老齊學(xué)Python之?dāng)?shù)據(jù)類型總結(jié)
前面已經(jīng)洋洋灑灑地介紹了不少數(shù)據(jù)類型。不能再不顧一切地向前沖了,應(yīng)當(dāng)總結(jié)一下。這樣讓看官能夠從總體上對(duì)這些數(shù)據(jù)類型有所了解,如果能夠有一覽眾山小的感覺(jué),就太好了。2014-09-09
Python中的random.uniform()函數(shù)教程與實(shí)例解析
今天小編就為大家分享一篇關(guān)于Python中的random.uniform()函數(shù)教程與實(shí)例解析,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03

