python tensorflow学习之识别单张图片的实现的示例


Posted in Python onFebruary 09, 2018

假设我们已经安装好了tensorflow。

一般在安装好tensorflow后,都会跑它的demo,而最常见的demo就是手写数字识别的demo,也就是mnist数据集。

然而我们仅仅是跑了它的demo而已,可能很多人会有和我一样的想法,如果拿来一张数字图片,如何应用我们训练的网络模型来识别出来,下面我们就以mnist的demo来实现它。

1.训练模型

首先我们要训练好模型,并且把模型model.ckpt保存到指定文件夹

saver = tf.train.Saver()   
saver.save(sess, "model_data/model.ckpt")

将以上两行代码加入到训练的代码中,训练完成后保存模型即可,如果这部分有问题,你可以百度查阅资料,tensorflow怎么保存训练模型,在这里我们就不罗嗦了。

2.测试模型

我们训练好模型后,将它保存在了model_data文件夹中,你会发现文件夹中出现了4个文件

python tensorflow学习之识别单张图片的实现的示例

然后,我们就可以对这个模型进行测试了,将待检测图片放在images文件夹下,执行

# -*- coding:utf-8 -*-  
import cv2 
import tensorflow as tf 
import numpy as np 
from sys import path 
path.append('../..') 
from common import extract_mnist 
 
#初始化单个卷积核上的参数 
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() 
   
  #声明输入图片数据,类别 
  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激活函数 
  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]) 
  #神经网络计算,并添加relu激活函数 
  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) 
  #数据从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,贴一下效果图

python tensorflow学习之识别单张图片的实现的示例

输出:

python tensorflow学习之识别单张图片的实现的示例

最后再贴一个cifar10的,感觉我的输入数据有点问题,因为直接读cifar10的数据测试是没问题的,但是换成自己的图片做预处理后输入结果就有问题,(参考:cv2读入的数据是BGR顺序,PIL读入的数据是RGB顺序,cifar10的数据是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 
 
 
#初始化单个卷积核上的参数 
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() 
   
  #声明输入图片数据,类别 
  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激活函数 
  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') 
 
  #全连接层 
  #权值参数 
  W_fc1 = weight_variable([8*8*64,384]) 
  #偏置值 
  b_fc1 = bias_variable([384]) 
  #将卷积的产出展开 
  pool2_flat = tf.reshape(pool2,[-1,8*8*64]) 
  #神经网络计算,并添加relu激活函数 
  fc1 = tf.nn.relu(tf.matmul(pool2_flat,W_fc1) + b_fc1) 
   
  #全连接第二层 
  #权值参数 
  W_fc2 = weight_variable([384,192]) 
  #偏置值 
  b_fc2 = bias_variable([192]) 
  #神经网络计算,并添加relu激活函数 
  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数据 
  # 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 相关文章推荐
Python使用MD5加密字符串示例
Aug 22 Python
python操作ie登陆土豆网的方法
May 09 Python
Python 专题四 文件基础知识
Mar 20 Python
PyCharm代码格式调整方法
May 23 Python
基于scrapy的redis安装和配置方法
Jun 13 Python
Django添加favicon.ico图标的示例代码
Aug 07 Python
python  创建一个保留重复值的列表的补码
Oct 15 Python
Python函数和模块的使用总结
May 20 Python
Django项目创建到启动详解(最全最详细)
Sep 07 Python
Django Path转换器自定义及正则代码实例
May 29 Python
python 检测nginx服务邮件报警的脚本
Dec 31 Python
Python Pytorch查询图像的特征从集合或数据库中查找图像
Apr 09 Python
python删除服务器文件代码示例
Feb 09 #Python
详解Python使用tensorflow入门指南
Feb 09 #Python
python编程测试电脑开启最大线程数实例代码
Feb 09 #Python
Python实现对一个函数应用多个装饰器的方法示例
Feb 09 #Python
Python+PIL实现支付宝AR红包
Feb 09 #Python
Python 实现12306登录功能实例代码
Feb 09 #Python
Python多层装饰器用法实例分析
Feb 09 #Python
You might like
剖析 PHP 中的输出缓冲
2006/12/21 PHP
Drupal7连接多个数据库及常见问题解决
2014/03/02 PHP
Laravel使用原生sql语句并调用的方法
2019/10/09 PHP
jQuery bind事件使用详解
2011/05/05 Javascript
关于jQuery $.isNumeric vs. $.isNaN vs. isNaN
2013/04/15 Javascript
jquery中通过父级查找进行定位示例
2013/06/28 Javascript
JQuery的ready函数与JS的onload的区别详解
2013/11/21 Javascript
AngularJS模块管理问题的非常规处理方法
2015/04/29 Javascript
jQuery实现在列表的首行添加数据
2015/05/19 Javascript
AngularJS表格详解及示例代码
2016/08/17 Javascript
JavaScript利用闭包实现模块化
2017/01/13 Javascript
微信小程序新增的拖动组件movable-view使用教程
2017/05/20 Javascript
实例分析js事件循环机制
2017/12/13 Javascript
JS基于递归实现网页版计算器的方法分析
2017/12/20 Javascript
axios 处理 302 状态码的解决方法
2018/04/10 Javascript
如何构建 vue-ssr 项目的方法步骤
2020/08/04 Javascript
vue实现前端列表多条件筛选
2020/10/26 Javascript
在Python中操作时间之mktime()方法的使用教程
2015/05/22 Python
Python遍历文件夹和读写文件的实现方法
2017/05/10 Python
Python中的取模运算方法
2018/11/10 Python
Python面向对象之类的内置attr属性示例
2018/12/14 Python
使用k8s部署Django项目的方法步骤
2019/01/14 Python
使用python itchat包爬取微信好友头像形成矩形头像集的方法
2019/02/21 Python
python中的句柄操作的方法示例
2019/06/20 Python
Keras-多输入多输出实例(多任务)
2020/06/22 Python
详解canvas drawImage()方法绘制图片不显示的问题
2018/10/08 HTML / CSS
HTML5新控件之日期和时间选择输入的实现代码
2018/09/13 HTML / CSS
html5将图片转换成base64的实例代码
2016/09/21 HTML / CSS
Office DEPOT法国官网:欧迪办公用品采购
2018/01/03 全球购物
将时尚融入珠宝:Adornmonde
2019/10/17 全球购物
自动化专业毕业生自荐信
2013/11/01 职场文书
车工岗位职责
2013/11/26 职场文书
社区领导班子四风问题原因分析及整改措施
2014/09/28 职场文书
销售经理工作检讨书
2015/02/19 职场文书
导游词之上海杜莎夫人蜡像馆
2019/11/22 职场文书
用Python编写简单的gRPC服务的详细过程
2021/07/04 Python