当前位置:   article > 正文

利用mnist数据集的demo来做识别单张图片数字_mnist.demo

mnist.demo

最近领导让我做图片识别,把这两天的工作记录一下吧,虽然中间做的磕磕碰碰,但是一个好的开始,加油!好了不灌鸡汤了,let's  show!

在做图片识别之前,需要对图片做处理,利用的是opencv(python 环境需要装)

比如我们要识别的电表的数字如下图:


下面是对该图片的做opencv处理,源代码如下:

  1. # coding=utf-8
  2. from __future__ import division #整数相除为浮点数
  3. import cv2
  4. import numpy as np
  5. import os
  6. img = cv2.imread('testset/img4.PNG')
  7. #cv2.imshow('Original', img)
  8. cv2.waitKey(0)
  9. #cv2.imwrite('save/img4.PNG',img)
  10. # 灰度处理
  11. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  12. #cv2.imshow('Gray', gray)
  13. cv2.waitKey(0)
  14. #cv2.imwrite('save/gray.PNG',gray)
  15. # 均值滤波
  16. # median = cv2.medianBlur(gray, 3)
  17. blur = cv2.blur(img, (4, 4))
  18. #cv2.imshow('Blur', blur)
  19. cv2.waitKey(0)
  20. #cv2.imwrite('save/blur.PNG',blur)
  21. # Canny边缘提取
  22. canny = cv2.Canny(blur, 300, 450)
  23. #cv2.imshow('Canny', canny)
  24. cv2.waitKey(0)
  25. #cv2.imwrite('save/canny.PNG',canny)
  26. # 二值处理
  27. #ret, thresh = cv2.threshold(canny, 90, 255, cv2.THRESH_BINARY)
  28. #kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
  29. #closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
  30. # 膨胀操作
  31. kernel = np.uint8(np.ones((7, 7)))
  32. dilate = cv2.dilate(canny, kernel)
  33. # 腐蚀操作
  34. erode = cv2.erode(dilate,(9,9))
  35. #cv2.imshow('Dilate', erode)
  36. cv2.waitKey(0)
  37. #cv2.imwrite('save/dilate.PNG',dilate)
  38. (image, cnts, _) = cv2.findContours(dilate.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  39. for index, c in enumerate(cnts):
  40. rect = cv2.minAreaRect(c)
  41. box = np.int0(cv2.boxPoints(rect))
  42. # draw a bounding box arounded the detected number and display the image
  43. cv2.drawContours(img, [box], -1, (0, 255, 0), 0)
  44. Xs = [i[0] for i in box]
  45. Ys = [i[1] for i in box]
  46. x1 = min(Xs)
  47. x2 = max(Xs)
  48. y1 = min(Ys)
  49. y2 = max(Ys)
  50. hight = y2 - y1
  51. width = x2 - x1
  52. cropImg = image[y1:y1+hight, x1:x1+width]
  53. cv2.imshow(str(i + 1), cropImg)
  54. ###### 按顺序保存图片
  55. for j in i:
  56. cv2.imwrite('save/%d.PNG' % i[0], cropImg)
  57. ######
  58. cv2.waitKey(0)
  59. #cv2.imshow('Image', img)
  60. cv2.waitKey(0)
  61. #cv2.imwrite('save/img.PNG',img)
  62. #图像统一预处理成28*28
  63. imgs=os.listdir('save')
  64. num = len(imgs)
  65. for index,i in enumerate(imgs):
  66. img=cv2.imread('save/'+i,0)
  67. #print img.shape
  68. width=img.shape[1]
  69. height=img.shape[0]
  70. fx=28/width
  71. fy=28/height
  72. res = cv2.resize(img, None, fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC) #图像缩放成28x28
  73. cv2.imwrite('save/%d.png' % (index), res)
处理后的结果如下: 需要说明一下,对图片数字的小数点,我们还没有做处理,在此先搁浅,以后写出来,后补!

         

下面就是我们的重头戏了,利用的是两层cnn做训练并识别图片,训练的模型是mnist的demo,在这里我们是保存了该训练的模型,talk is cheap ,show you my code!

  1. import tensorflow as tf
  2. import tensorflow.examples.tutorials.mnist.input_data as input_data
  3. import os
  4. MODEL_SAVE_PATH="model_data/"
  5. MODEL_NAME="save_net.ckpt"
  6. def weight_variable(shape):
  7. initial=tf.truncated_normal(shape,stddev=0.1)
  8. return tf.Variable(initial)
  9. def bias_variable(shape):
  10. initial=tf.constant(0.1,shape=shape)
  11. return tf.Variable(initial)
  12. def conv2d(x,W):
  13. return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME")
  14. def max_pool_2x2(x):
  15. return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
  16. with tf.Session() as sess:
  17. mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
  18. x = tf.placeholder(tf.float32, [None, 784])
  19. w_conv1=weight_variable([5,5,1,32])
  20. b_conv1=bias_variable([32])
  21. x_image=tf.reshape(x,[-1,28,28,1])
  22. y_ = tf.placeholder("float", [None, 10])
  23. h_conv1=tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)
  24. h_pool1=max_pool_2x2(h_conv1)
  25. w_conv2=weight_variable([5,5,32,64])
  26. b_conv2=bias_variable([64])
  27. h_conv2=tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2)
  28. h_pool2=max_pool_2x2(h_conv2)
  29. w_fc1=weight_variable([7*7*64,1024])
  30. b_fc1=bias_variable([1024])
  31. h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])
  32. h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,w_fc1)+b_fc1)
  33. keep_prob=tf.placeholder("float")
  34. h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
  35. w_fc2=weight_variable([1024,10])
  36. b_fc2=bias_variable([10])
  37. y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)
  38. cross_entropy=-tf.reduce_sum(y_*tf.log(y_conv))
  39. train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  40. saver = tf.train.Saver()
  41. correct_prediction=tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
  42. accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float"))
  43. sess.run(tf.global_variables_initializer())
  44. for i in range(2000):
  45. batch=mnist.train.next_batch(50)
  46. if i%100==0:
  47. train_accuracy=accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0})
  48. print("step %d,training accuracy %g" % (i,train_accuracy))
  49. train_step.run(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})
  50. print("test accuracy %g" % accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))
  51. saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), write_meta_graph=False)
接下来就是利用训练的模型来做识别了,plz see

  1. # coding:utf-8
  2. import tensorflow as tf
  3. import numpy as np
  4. import cv2
  5. #初始化单个卷积核上的参数
  6. def weight_variable(shape):
  7. initial = tf.truncated_normal(shape, stddev=0.1)
  8. return tf.Variable(initial)
  9. #初始化单个卷积核上的偏置值
  10. def bias_variable(shape):
  11. initial = tf.constant(0.1, shape=shape)
  12. return tf.Variable(initial)
  13. #输入特征x,用卷积核W进行卷积运算,strides为卷积核移动步长,
  14. #padding表示是否需要补齐边缘像素使输出图像大小不变
  15. def conv2d(x, W):
  16. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  17. #对x进行最大池化操作,ksize进行池化的范围,
  18. def max_pool_2x2(x):
  19. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
  20. #
  21. # 定义会话
  22. with tf.Session() as sess:
  23. #声明输入图片数据,类别
  24. x = tf.placeholder(tf.float32,[None,784])
  25. x_img = tf.reshape(x , [-1,28,28,1])
  26. W_conv1 = weight_variable([5, 5, 1, 32])
  27. b_conv1 = bias_variable([32])
  28. #进行卷积操作,并添加relu激活函数
  29. h_conv1 = tf.nn.relu(conv2d(x_img,W_conv1) + b_conv1)
  30. #进行最大池化
  31. h_pool1 = max_pool_2x2(h_conv1)
  32. W_conv2 = weight_variable([5,5,32,64])
  33. b_conv2 = bias_variable([64])
  34. # 同理第二层卷积层
  35. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
  36. h_pool2 = max_pool_2x2(h_conv2)
  37. W_fc1 = weight_variable([7*7*64,1024])
  38. b_fc1 = bias_variable([1024])
  39. #将卷积的产出展开
  40. h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
  41. #神经网络计算,并添加relu激活函数
  42. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1)
  43. keep_prob = tf.placeholder(tf.float32)
  44. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  45. W_fc2 = weight_variable([1024,10])
  46. b_fc2 = bias_variable([10])
  47. # 引用mnist训练好的保存的模型
  48. saver = tf.train.Saver(write_version=tf.train.SaverDef.V1)
  49. saver.restore(sess, 'model_data/save_net.ckpt')
  50. #输出层,使用softmax进行多分类
  51. y_conv=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)
  52. im = cv2.imread('save/img4_4.png', cv2.IMREAD_GRAYSCALE)
  53. im = cv2.resize(im, (28, 28), interpolation=cv2.INTER_CUBIC)
  54. img = cv2.GaussianBlur(im, (3, 3), 0)
  55. # 图片预处理
  56. # 数据从0~255转为-0.5~0.5
  57. img_gray = (im - (255 / 2.0)) / 255
  58. # img_gray = (im)/255
  59. # for i in range(28):
  60. # for j in range(28):
  61. # if img_gray[i][j]<=0.5:
  62. # img_gray[i][j]=0
  63. # else:
  64. # img_gray[i][j]=1
  65. cv2.imshow('out',img_gray)
  66. cv2.waitKey(0)
  67. x_img = np.reshape(img_gray, [-1, 784])
  68. output = sess.run(y_conv , feed_dict = {x:x_img})
  69. print('the y_con : ', '\n',output)
  70. print('the predict is : ', np.argmax(output))

结果如下:








这里的数字识别大致过程差不多就这样,虽然表面看起来很完美,但是还有些数字没有识别正确,我举的例子数字是都识别出来了,但是其他的数字还有点问题,这里在随后我解决了,再做补充吧。你get 到了吗?


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/148793
推荐阅读
相关标签
  

闽ICP备14008679号