python tensorflow学习之识别单张图片的实现的示例
作者:我拿buff 发布时间:2023-06-30 21:11:32
标签:python,tensorflow,识别图片
假设我们已经安装好了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个文件
然后,我们就可以对这个模型进行测试了,将待检测图片放在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,贴一下效果图
输出:
最后再贴一个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()
来源:http://blog.csdn.net/gaohuazhao/article/details/72886450
0
投稿
猜你喜欢
- 是的,我在这里要说:注册表单将死(好拗口啊,但是不知道怎么翻译更恰当)。回想一下,当你想享受一个网站服务的时候,碰到的第一件事是什么?一个表
- 上一次,我们谈到在ASP中如何利用“正则表达式”对象来实现各种数据的校验,文中描述了正则表达式对象的强大功能,接下来,我们来看看有关“正则表
- 其实这个问题落伍谈了n次了其中care4也说了两次所以如果你有问题最好先搜索一下 说不定问题早有人解决了http://www.im286.c
- 网页制作中用到的特效字,你一定是用图象处理软件制作的吧!告诉你,不用图象处理软件,我也能做出漂亮的特效字来,你看,阴影字我就是这样做出来的。
- 一、读者指引读者指引帮助你掌握本文的梗概。以免你看了大半才明白这编文章不适合你,给你造成视觉污染。如果你正在用ASP+XML写一些程序,或者
- 在输入框里面预设一段提示文字,当焦点在输入框的时候清空这段文字,这在目前来说已经不是什么新鲜事了。淘宝的搜索框就用到了这样一种设计:这种设计
- 耦合两个或以上的体系或两种运动形式间相互作用而彼此影响以至于联合起来的现象。在软件工程中,对象之间的耦合度就是对象之间的依赖性,对象之间的耦
- 到目前为止,我们连接的都是两张不同的表,那么能不能对一张表进行自我连接呢?答案是肯定的。有没有必要对一张表进行自我连接呢?答案也是肯定的。
- 在SQL Server 中,如果给表的一个字段设置了默认值,就会在系统表sysobjects中生成一个默认约束。如果想删除这个设置了默认值的
- 现在很多以内容为核心的网站上都在文章底部添加了社会化分享按钮,能让浏览用户在发现一篇有价值的文章时,可以通过社会化网络快速分享给自己的好友,
- 类的定义 类定义有三种基本方法,1、创建并能返回特定类型的对象的函数(工厂函数),例如:function Co(){ var o = new
- 在Google Chrome浏览器出来之前,我一直使用FireFox,因为FireFox的插件非常丰富,更因为FireFox有强大的Fire
- 先来看看什么是书签查找: 当优化器所选择的非聚簇索引只包含查询请求的一部分字段时,就需要一个查找(lookup)来检索其他字段来满足请求。对
- 当变量维数加大时很难想象是怎样按不同维度求和的,高清楚一个,其他的应该就很清楚了,什么都不说了,上例子,例子一看便明白…..a=range(
- 上周在去杭州betacafe的路上,有幸和绿人网梁宁和饭统网李耀东、千鸟一道,在出租车上聊起了地理和历史,其中有一个共同的观点是说,人们对事
- SQL Server数据库查询速度慢的原因有很多,常见的有以下几种:1、没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷)
- PDOStatement::closeCursorPDOStatement::closeCursor — 关闭游标,使语句能再次被执行。(P
- 原理 采集程序实际上是通过了XML中的XMLHTTP组件调用其它网站上的网页。比如新闻采集程序,很多都是调用了sina的新闻网页,并且对其中
- 在MySQL经历了2008年Sun的收购和2009年Oracle收购Sun的过程中,基本处于停滞发展的情况,在可以预见的未来,MySQL是肯
- 由 John Resig 的 How JavaScript Timers Work 可以知道,现有的 JavaScript 引擎是单线程处理