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

    在学习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、 增加保存训练好的网络模型功能,这样就可以减少训练网络需要的时间了

本文提供一份基于tensorflow.js的在线手写数字识别js文件,可以在浏览器中实现手写数字识别。 首先需要引入tensorflow.js的库文件: ```javascript <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.1/dist/tf.min.js"></script> ``` 然后定义一些变量,包括canvas和context: ```javascript var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var model; var xs; var ys; var isDrawing = false; ``` 接着定义一些函数,包括画布的初始化、开始绘制、结束绘制、清除画布等: ```javascript function initCanvas() { context.fillStyle = '#ffffff'; context.fillRect(0, 0, canvas.width, canvas.height); context.lineWidth = 10; context.lineJoin = 'round'; context.lineCap = 'round'; context.strokeStyle = '#000000'; } function startDrawing(event) { isDrawing = true; context.beginPath(); context.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop); } function endDrawing() { isDrawing = false; xs = tf.browser.fromPixels(canvas, 1) .resizeNearestNeighbor([28, 28]) .toFloat() .div(255.0); xs = xs.reshape([1, 784]); } function clearCanvas() { context.clearRect(0, 0, canvas.width, canvas.height); initCanvas(); } ``` 其中,startDrawing函数会在鼠标按下时调用,endDrawing函数会在鼠标松开时调用,清空画布的函数是clearCanvas。 最后是加载模型的函数: ```javascript async function loadModel() { model = await tf.loadLayersModel('http://localhost:8000/model.json'); } ``` loadModel函数会在页面加载时调用,用于加载我们预先训练好的模型。这里假设我们已经将模型文件放在本地的8000端口上。 最后是监听鼠标事件的代码: ```javascript canvas.addEventListener('mousedown', startDrawing); canvas.addEventListener('mousemove', function(event) { if (isDrawing) { context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop); context.stroke(); } }); canvas.addEventListener('mouseup', endDrawing); canvas.addEventListener('mouseout', endDrawing); ``` 这段代码会监听鼠标的mousedown、mousemove、mouseup和mouseout事件,调用相应的函数。 完整的代码如下: ```javascript var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var model; var xs; var ys; var isDrawing = false; async function loadModel() { model = await tf.loadLayersModel('http://localhost:8000/model.json'); } function initCanvas() { context.fillStyle = '#ffffff'; context.fillRect(0, 0, canvas.width, canvas.height); context.lineWidth = 10; context.lineJoin = 'round'; context.lineCap = 'round'; context.strokeStyle = '#000000'; } function startDrawing(event) { isDrawing = true; context.beginPath(); context.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop); } function endDrawing() { isDrawing = false; xs = tf.browser.fromPixels(canvas, 1) .resizeNearestNeighbor([28, 28]) .toFloat() .div(255.0); xs = xs.reshape([1, 784]); predict(); } function predict() { var result = model.predict(xs).dataSync(); var maxIndex = 0; for (var i = 1; i < result.length; i++) { if (result[i] > result[maxIndex]) { maxIndex = i; } } document.getElementById('result').innerText = maxIndex; } function clearCanvas() { context.clearRect(0, 0, canvas.width, canvas.height); initCanvas(); } loadModel(); initCanvas(); canvas.addEventListener('mousedown', startDrawing); canvas.addEventListener('mousemove', function(event) { if (isDrawing) { context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop); context.stroke(); } }); canvas.addEventListener('mouseup', endDrawing); canvas.addEventListener('mouseout', endDrawing); document.getElementById('clear').addEventListener('click', clearCanvas); ``` 其中,predict函数用于对手写数字进行预测,会在endDrawing函数中调用。我们使用了dataSync函数来获取预测结果,并找到其中最大的数字作为预测结果。最后,我们将预测结果显示在页面上的一个div中。 完整的HTML代码如下: ```html <!DOCTYPE html> <html> <head> <title>Online Handwritten Digit Recognition</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.1/dist/tf.min.js"></script> </head> <body> <canvas id="canvas" width="280" height="280" style="border: 1px solid #000000;"></canvas> <button id="clear">Clear</button> <div>Result: <span id="result"></span></div> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var model; var xs; var ys; var isDrawing = false; async function loadModel() { model = await tf.loadLayersModel('http://localhost:8000/model.json'); } function initCanvas() { context.fillStyle = '#ffffff'; context.fillRect(0, 0, canvas.width, canvas.height); context.lineWidth = 10; context.lineJoin = 'round'; context.lineCap = 'round'; context.strokeStyle = '#000000'; } function startDrawing(event) { isDrawing = true; context.beginPath(); context.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop); } function endDrawing() { isDrawing = false; xs = tf.browser.fromPixels(canvas, 1) .resizeNearestNeighbor([28, 28]) .toFloat() .div(255.0); xs = xs.reshape([1, 784]); predict(); } function predict() { var result = model.predict(xs).dataSync(); var maxIndex = 0; for (var i = 1; i < result.length; i++) { if (result[i] > result[maxIndex]) { maxIndex = i; } } document.getElementById('result').innerText = maxIndex; } function clearCanvas() { context.clearRect(0, 0, canvas.width, canvas.height); initCanvas(); } loadModel(); initCanvas(); canvas.addEventListener('mousedown', startDrawing); canvas.addEventListener('mousemove', function(event) { if (isDrawing) { context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop); context.stroke(); } }); canvas.addEventListener('mouseup', endDrawing); canvas.addEventListener('mouseout', endDrawing); document.getElementById('clear').addEventListener('click', clearCanvas); </script> </body> </html> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值