利用mnist數(shù)據(jù)集的demo來做識(shí)別單張圖片數(shù)字

最近領(lǐng)導(dǎo)讓我做圖片識(shí)別拉盾,把這兩天的工作記錄一下吧,雖然中間做的磕磕碰碰,但是一個(gè)好的開始豁状,加油捉偏!好了不灌雞湯了,let's? show泻红!

在做圖片識(shí)別之前告私,需要對圖片做處理,利用的是opencv(python 環(huán)境需要裝)

比如我們要識(shí)別的電表的數(shù)字

下面是對該圖片的做opencv處理,源代碼如下:

# coding=utf-8

from __future__ import division? #整數(shù)相除為浮點(diǎn)數(shù)

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)

#圖像統(tǒng)一預(yù)處理成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)

處理后的結(jié)果如下:需要說明一下承桥,對圖片數(shù)字的小數(shù)點(diǎn)驻粟,我們還沒有做處理,在此先擱淺,以后寫出來蜀撑,后補(bǔ)挤巡!


下面就是我們的重頭戲了,利用的是兩層cnn做訓(xùn)練并識(shí)別圖片酷麦,訓(xùn)練的模型是mnist的demo,在這里我們是保存了該訓(xùn)練的模型矿卑,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)

接下來就是利用訓(xùn)練的模型來做識(shí)別了,plz see

# coding:utf-8

import tensorflow as tf

import numpy as np

import cv2

#初始化單個(gè)卷積核上的參數(shù)

def weight_variable(shape):

? ? initial = tf.truncated_normal(shape, stddev=0.1)

? ? return tf.Variable(initial)

#初始化單個(gè)卷積核上的偏置值

def bias_variable(shape):

? ? initial = tf.constant(0.1, shape=shape)

? ? return tf.Variable(initial)

#輸入特征x沃饶,用卷積核W進(jìn)行卷積運(yùn)算母廷,strides為卷積核移動(dòng)步長,

#padding表示是否需要補(bǔ)齊邊緣像素使輸出圖像大小不變

def conv2d(x, W):

? ? return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

#對x進(jìn)行最大池化操作糊肤,ksize進(jìn)行池化的范圍琴昆,

def max_pool_2x2(x):

? ? return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')

#

? ? # 定義會(huì)話

with tf.Session() as sess:

? ? #聲明輸入圖片數(shù)據(jù),類別

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

? ? #進(jìn)行卷積操作馆揉,并添加relu激活函數(shù)

? ? h_conv1 = tf.nn.relu(conv2d(x_img,W_conv1) + b_conv1)

? ? #進(jìn)行最大池化

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

? ? #將卷積的產(chǎn)出展開

? ? h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])

? ? #神經(jīng)網(wǎng)絡(luò)計(jì)算业舍,并添加relu激活函數(shù)

? ? 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訓(xùn)練好的保存的模型

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

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

? ? #輸出層,使用softmax進(jìn)行多分類

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

? ? # 圖片預(yù)處理

? ? # 數(shù)據(jù)從0~255轉(zhuǎn)為-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))

結(jié)果如下:

這里的數(shù)字識(shí)別大致過程差不多就這樣升酣,雖然表面看起來很完美舷暮,但是還有些數(shù)字沒有識(shí)別正確,我舉的例子數(shù)字是都識(shí)別出來了噩茄,但是其他的數(shù)字還有點(diǎn)問題下面,這里在隨后我解決了,再做補(bǔ)充吧绩聘。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末沥割,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子君纫,更是在濱河造成了極大的恐慌,老刑警劉巖芹彬,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蓄髓,死亡現(xiàn)場離奇詭異,居然都是意外死亡舒帮,警方通過查閱死者的電腦和手機(jī)会喝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來玩郊,“玉大人肢执,你說我怎么就攤上這事∫牒欤” “怎么了预茄?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我耻陕,道長拙徽,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任诗宣,我火速辦了婚禮膘怕,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘召庞。我一直安慰自己岛心,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布篮灼。 她就那樣靜靜地躺著忘古,像睡著了一般。 火紅的嫁衣襯著肌膚如雪穿稳。 梳的紋絲不亂的頭發(fā)上存皂,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天,我揣著相機(jī)與錄音逢艘,去河邊找鬼旦袋。 笑死,一個(gè)胖子當(dāng)著我的面吹牛它改,可吹牛的內(nèi)容都是我干的疤孕。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼央拖,長吁一口氣:“原來是場噩夢啊……” “哼祭阀!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起鲜戒,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤专控,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后遏餐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體伦腐,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年失都,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了柏蘑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,696評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡粹庞,死狀恐怖咳焚,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情庞溜,我是刑警寧澤革半,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響督惰,放射性物質(zhì)發(fā)生泄漏不傅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一赏胚、第九天 我趴在偏房一處隱蔽的房頂上張望访娶。 院中可真熱鬧,春花似錦觉阅、人聲如沸崖疤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽劫哼。三九已至,卻和暖如春割笙,著一層夾襖步出監(jiān)牢的瞬間权烧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工伤溉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留般码,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓乱顾,卻偏偏與公主長得像板祝,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子走净,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容