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

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

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

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

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

# coding=utf-8

from __future__ import division  #整数相除为浮点数

import cv2

import numpy as np

import os

img = cv2.imread('testset/img4.PNG')

#cv2.imshow('Original', img)

cv2.waitKey(0)

#cv2.imwrite('save/img4.PNG',img)

# 灰度处理

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#cv2.imshow('Gray', gray)

cv2.waitKey(0)

#cv2.imwrite('save/gray.PNG',gray)

# 均值滤波

# median = cv2.medianBlur(gray, 3)

blur = cv2.blur(img, (4, 4))

#cv2.imshow('Blur', blur)

cv2.waitKey(0)

#cv2.imwrite('save/blur.PNG',blur)

# Canny边缘提取

canny = cv2.Canny(blur, 300, 450)

#cv2.imshow('Canny', canny)

cv2.waitKey(0)

#cv2.imwrite('save/canny.PNG',canny)

# 二值处理

#ret, thresh = cv2.threshold(canny, 90, 255, cv2.THRESH_BINARY)

#kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))

#closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# 膨胀操作

kernel = np.uint8(np.ones((7, 7)))

dilate = cv2.dilate(canny, kernel)

# 腐蚀操作

erode = cv2.erode(dilate,(9,9))

#cv2.imshow('Dilate', erode)

cv2.waitKey(0)

#cv2.imwrite('save/dilate.PNG',dilate)

(image, cnts, _) = cv2.findContours(dilate.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for index, c in enumerate(cnts):

    rect = cv2.minAreaRect(c)

    box = np.int0(cv2.boxPoints(rect))

    # draw a bounding box arounded the detected number and display the image

    cv2.drawContours(img, [box], -1, (0, 255, 0), 0)

    Xs = [i[0] for i in box]

    Ys = [i[1] for i in box]

    x1 = min(Xs)

    x2 = max(Xs)

    y1 = min(Ys)

    y2 = max(Ys)

    hight = y2 - y1

    width = x2 - x1

    cropImg = image[y1:y1+hight, x1:x1+width]

    cv2.imshow(str(i + 1), cropImg)

    ######    按顺序保存图片

    for j in i:

        cv2.imwrite('save/%d.PNG' % i[0], cropImg)

    ######

    cv2.waitKey(0)

#cv2.imshow('Image', img)

cv2.waitKey(0)

#cv2.imwrite('save/img.PNG',img)

#图像统一预处理成28*28

imgs=os.listdir('save')

num = len(imgs)

for index,i in enumerate(imgs):

    img=cv2.imread('save/'+i,0)

    #print img.shape

    width=img.shape[1]

    height=img.shape[0]

    fx=28/width

    fy=28/height

    res = cv2.resize(img, None, fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC) #图像缩放成28x28

    cv2.imwrite('save/%d.png' % (index), res)

处理后的结果如下:需要说明一下,对图片数字的小数点,我们还没有做处理,在此先搁浅,以后写出来,后补!


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

import tensorflow as tf

import tensorflow.examples.tutorials.mnist.input_data as input_data

import os

MODEL_SAVE_PATH="model_data/"

MODEL_NAME="save_net.ckpt"

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')

with tf.Session() as sess:

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

    x = tf.placeholder(tf.float32, [None, 784])

    w_conv1=weight_variable([5,5,1,32])

    b_conv1=bias_variable([32])

    x_image=tf.reshape(x,[-1,28,28,1])

    y_ = tf.placeholder("float", [None, 10])

    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("float")

    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_sum(y_*tf.log(y_conv))

    train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

    saver = tf.train.Saver()

    correct_prediction=tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))

    accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float"))

    sess.run(tf.global_variables_initializer())

    for i in range(2000):

        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}))

    saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), write_meta_graph=False)

接下来就是利用训练的模型来做识别了,plz see

# coding:utf-8

import tensorflow as tf

import numpy as np

import cv2

#初始化单个卷积核上的参数

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')

#

    # 定义会话

with tf.Session() as sess:

    #声明输入图片数据,类别

    x = tf.placeholder(tf.float32,[None,784])

    x_img = tf.reshape(x , [-1,28,28,1])

    W_conv1 = weight_variable([5, 5, 1, 32])

    b_conv1 = bias_variable([32])

    #进行卷积操作,并添加relu激活函数

    h_conv1 = tf.nn.relu(conv2d(x_img,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])

    #神经网络计算,并添加relu激活函数

    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])

    # 引用mnist训练好的保存的模型

    saver = tf.train.Saver(write_version=tf.train.SaverDef.V1)

    saver.restore(sess, 'model_data/save_net.ckpt')

    #输出层,使用softmax进行多分类

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

    im = cv2.imread('save/img4_4.png', cv2.IMREAD_GRAYSCALE)

    im = cv2.resize(im, (28, 28), interpolation=cv2.INTER_CUBIC)

    img = cv2.GaussianBlur(im, (3, 3), 0)

    # 图片预处理

    # 数据从0~255转为-0.5~0.5

    img_gray = (im - (255 / 2.0)) / 255

    # img_gray = (im)/255

    # for i in range(28):

    #    for j in range(28):

    #        if img_gray[i][j]<=0.5:

    #            img_gray[i][j]=0

    #        else:

    #            img_gray[i][j]=1

    cv2.imshow('out',img_gray)

    cv2.waitKey(0)

    x_img = np.reshape(img_gray, [-1, 784])

    output = sess.run(y_conv , feed_dict = {x:x_img})

    print('the y_con :  ', '\n',output)

    print('the predict is : ', np.argmax(output))

结果如下:

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容