您的位置:首页 > 其它

TensorFlow实时识别手写数字(数字通过鼠标输入)

2017-05-15 21:15 417 查看
    在学习TensorFlow教程的的手写数字识别时,感觉受益匪浅,但是教程上的例子对于我这种刚入门的人来说不够直接,冲击力也不足。于是自己加上了用鼠标绘画数字,并用训练好的网络模型来识别的功能。下面给出程序与说明:

程序:

import numpy as np
import cv2
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

sess = tf.InteractiveSession()

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 max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
x_image = tf.reshape(x, [-1,28,28,1])

W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

tf.global_variables_initializer().run()

for i in range(20000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
## the above is the standard tutorial

## follow is edited myself
drawing = False
ix, iy = -1, -1

def draw_digit(event, x, y, flags, param):
global ix, iy, drawing

if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.circle(img, (x, y), 1, (255), -1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False

img = np.zeros((28,28), np.uint8)
cv2.namedWindow('Image')
cv2.setMouseCallback('Image', draw_digit)

while(1):
img = np.zeros((28,28), np.uint8)
while(1):
cv2.imshow('Image', img)
k = cv2.waitKey(1) & 0xFF
if k == 10: #Enter key
cv2.imwrite('1.png', img)
break

flatten = img.flatten()/255.0

y_input = np.zeros((1,10))
input_image = np.zeros((1,784))
input_image[0] = flatten

prediction = tf.argmax(y_conv, 1)
print sess.run(prediction, feed_dict = {x:input_image, y_:y_input,keep_prob: 1.0})

j = cv2.waitKey(1) & 0xFF
if j == 17: #Enter key
break
将程序保存为 xxx.py文件,在Linux终端运行python xxx.py, 等待网络训练完毕之后,在桌面上回出现如下的窗口(该窗口很小)



用鼠标在窗口内画数字,示例如下:




等等(每次输入一个数字)

这时按下Enter键,在终端就会出现网络预测之后的数字,只要画的不是太不像,准确度还是很高的。

如果已经按过了Enter键,再按下Esc键就会退出程序。

程序说明:

1、网络训练与教程一模一样

2、鼠标画数字是调用opencv的库实现的,这里将窗口大小定义为28 * 28,绘画的图定义为单通道的灰度图,来适应MNISIT的数据格式。

3、关于程序中的一些解释:

     1) 当网络训练时,是run Ada这个优化的来执行训练的,此优化器在训练过程中会优化权重W和偏置b的值,loss决定什么时候停止训练

     2) 当识别自己用鼠标画出的数字时,是run prediction这个节点,因为TensorFlow会自动的推算prediction这个节点运行的依赖节点,这些依赖节点明显不包括优化器。所以在识别过程中用得到的W和b是训练完毕之后的值,所以可以正确识别。

     3) prediction中的y_input的值是可以随便取值的,只要其类型是[None, 10]即可,因为要给节点中的 y_conv feed值,否则执行时会报错

注:此程序未来改进地方

1、 扩大窗口的大小,在程序中使用图片压缩功能,将大图片压缩到28 * 28

2、 增加保存训练好的网络模型功能,这样就可以减少训练网络需要的时间了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息