python tensorflow學習之識別單張圖片的實現(xiàn)的示例
假設我們已經(jīng)安裝好了tensorflow。
一般在安裝好tensorflow后,都會跑它的demo,而最常見的demo就是手寫數(shù)字識別的demo,也就是mnist數(shù)據(jù)集。
然而我們僅僅是跑了它的demo而已,可能很多人會有和我一樣的想法,如果拿來一張數(shù)字圖片,如何應用我們訓練的網(wǎng)絡模型來識別出來,下面我們就以mnist的demo來實現(xiàn)它。
1.訓練模型
首先我們要訓練好模型,并且把模型model.ckpt保存到指定文件夾
saver = tf.train.Saver() saver.save(sess, "model_data/model.ckpt")
將以上兩行代碼加入到訓練的代碼中,訓練完成后保存模型即可,如果這部分有問題,你可以百度查閱資料,tensorflow怎么保存訓練模型,在這里我們就不羅嗦了。
2.測試模型
我們訓練好模型后,將它保存在了model_data文件夾中,你會發(fā)現(xiàn)文件夾中出現(xiàn)了4個文件

然后,我們就可以對這個模型進行測試了,將待檢測圖片放在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
#初始化單個卷積核上的參數(shù)
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
#初始化單個卷積核上的偏置值
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
#輸入特征x,用卷積核W進行卷積運算,strides為卷積核移動步長,
#padding表示是否需要補齊邊緣像素使輸出圖像大小不變
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
#對x進行最大池化操作,ksize進行池化的范圍,
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():
#定義會話
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')
#進行卷積操作,并添加relu激活函數(shù)
h_conv1 = tf.nn.relu(conv2d(x_img,W_conv1) + b_conv1)
#進行最大池化
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)
#將卷積的產出展開
h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
#神經(jīng)網(wǎng)絡計算,并添加relu激活函數(shù)
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1)
#輸出層,使用softmax進行多分類
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)
#圖片預處理
#img_gray = cv2.cvtColor(im , cv2.COLOR_BGR2GRAY).astype(np.float32)
#數(shù)據(jù)從0~255轉為-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)
#關閉會話
sess.close()
if __name__ == '__main__':
main()
ok,貼一下效果圖

輸出:

最后再貼一個cifar10的,感覺我的輸入數(shù)據(jù)有點問題,因為直接讀cifar10的數(shù)據(jù)測試是沒問題的,但是換成自己的圖片做預處理后輸入結果就有問題,(參考: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
#初始化單個卷積核上的參數(shù)
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
#初始化單個卷積核上的偏置值
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():
#定義會話
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])
#進行卷積操作,并添加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')
#全連接層
#權值參數(shù)
W_fc1 = weight_variable([8*8*64,384])
#偏置值
b_fc1 = bias_variable([384])
#將卷積的產出展開
pool2_flat = tf.reshape(pool2,[-1,8*8*64])
#神經(jīng)網(wǎng)絡計算,并添加relu激活函數(shù)
fc1 = tf.nn.relu(tf.matmul(pool2_flat,W_fc1) + b_fc1)
#全連接第二層
#權值參數(shù)
W_fc2 = weight_variable([384,192])
#偏置值
b_fc2 = bias_variable([192])
#神經(jīng)網(wǎng)絡計算,并添加relu激活函數(shù)
fc2 = tf.nn.relu(tf.matmul(fc1,W_fc2) + b_fc2)
#輸出層,使用softmax進行多分類
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)
#關閉會話
sess.close()
if __name__ == '__main__':
main()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- python使用TensorFlow進行圖像處理的方法
- Python通過TensorFLow進行線性模型訓練原理與實現(xiàn)方法詳解
- Python Tensor FLow簡單使用方法實例詳解
- Python tensorflow實現(xiàn)mnist手寫數(shù)字識別示例【非卷積與卷積實現(xiàn)】
- Python3.7安裝keras和TensorFlow的教程圖解
- python3讀取圖片并灰度化圖片的四種方法(OpenCV、PIL.Image、TensorFlow方法)總結
- python3.6.3安裝圖文教程 TensorFlow安裝配置方法
- python生成tensorflow輸入輸出的圖像格式的方法
- Python圖像處理之識別圖像中的文字(實例講解)
- Python基于Tensor FLow的圖像處理操作詳解
相關文章
使用Python實現(xiàn)搖號系統(tǒng)的詳細步驟
這篇文章主要介紹了如何使用Python構建一個簡單的搖號系統(tǒng),包括需求分析、技術棧、實現(xiàn)步驟和完整代碼示例,該系統(tǒng)能夠從用戶輸入的參與者名單中隨機抽取指定數(shù)量的中獎者,并將結果展示給用戶以及記錄到日志文件中,需要的朋友可以參考下2024-11-11
Anaconda多環(huán)境多版本python配置操作方法
下面小編就為大家?guī)硪黄狝naconda多環(huán)境多版本python配置操作方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
Python中的random.uniform()函數(shù)教程與實例解析
今天小編就為大家分享一篇關于Python中的random.uniform()函數(shù)教程與實例解析,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03

