深度學習之卷積神經網絡(CNN)的應用-驗證碼的生成與識別

                          驗證碼的生成與識別

                     本文系做者原創,轉載請註明出處:http://www.javashuo.com/article/p-wfufrieu-g.html html

目錄

1.驗證碼的製做

2.卷積神經網絡結構

3.訓練參數保存與使用

4.注意事項

5.代碼實現(python3.5)

6.運行結果以及分析

 

1.驗證碼的製做

深度學習一個必要的前提就是須要大量的訓練樣本數據,絕不誇張的說,訓練樣本數據的多少直接決定模型的預測準確度而本節的訓練樣本數據(驗證碼:字母和數字組成)經過調用Image模塊(圖像處理庫)中相關函數生成。python

安裝:pip install pillowgit

驗證碼生成步驟:隨機在字母和數字中選擇4個字符 -> 建立背景圖片 -> 添加噪聲 -> 字符扭曲算法

具體樣本以下所示:網絡

           

對於上圖的驗證碼,若是用傳統方式破解,其步驟通常是:session

圖片分割:採用分割算法分割出每個字符;app

字符識別:由分割出的每一個字符圖片,根據OCR光學字符識別出每一個字符圖片對應的字符;dom

難點在於:對於圖片字符有黏連(2個,3個,或者4個所有黏連),圖片是沒法徹底分割出來的,也就是說,即便分割出來了,字符識別基本上都是錯誤的,特別對於人眼都沒法分辨的驗證碼,用傳統的這種破解方法,成功率基本上是極其低的。ide

黏連驗證碼函數

     

 

人眼幾乎沒法分辨驗證碼

      

第一張是 0ymo or 0ynb ?第二張是 7e9l or 1e9l ?

對於以上傳統方法破解驗證碼的短板,咱們採用深度學習之卷積神經網絡來進行破解

2.卷積神經網絡結構

前向傳播組成:3個卷積層(3*3*1*32,3*3*32*64,3*3*64*64),3個池化層,4個dropout防過擬合層,2個全鏈接層((8*20*64,1024),(1024, MAX_CAPTCHA*CHAR_SET_LEN])),4個Relu激活函數。

反向傳播組成:計算損失(sigmoid交叉熵),計算梯度,目標預測,計算準確率,參數更新。

tensorboard生成結構圖(圖片可能不是很清楚,在圖片位置點擊鼠標右鍵->在新標籤頁面打開圖片,就能夠放縮圖片了。)

 

這裏特別要注意數據流的變化:

(?,60,160,1) + conv1->(?,60,160,32)+ relu ->(?,60,160,32) + pool1 ->(?,30,80,32) + dropout -> (?,30,80,32)

+ conv2->(?,30,80,64)  + relu ->(?,30,80,64) + pool2 ->(?,15,40,64) + dropout -> (?,15,40,64)

+ conv3->(?,15,40,64)  + relu ->(?,15,40,64) + pool3 ->(?,8,20,64) + dropout -> (?,8,20,64)

+ fc1 ->(?,1024) + relu ->(?,1024) + dropout ->(?,1024)

+ fc2 ->(?,MAX_CAPTCHA*CHAR_SET_LEN)

只要把握住一點,卷積過程跟全鏈接運算是不同的。

卷積過程:矩陣對應位置相乘再相加,要求相乘的兩個矩陣寬、高必須相同(好比大小都是m * n),獲得結果就是一個數值。

全鏈接(矩陣乘法):它要求第一個矩陣的列和第二個矩陣的行必須相同,好比矩陣A大小m * n,矩陣B大小n * k,紅色部分必須相同,獲得結果大小就是m * k

 

3.訓練參數保存與使用

參數保存:

tensorflow對於參數保存功能已幫咱們作好了,咱們只要直接使用就能夠了。使用也很簡單,就兩步,獲取保存對象,調用保存方法。

獲取保存對象:

 saver = tf.train.Saver()  

調用保存方法:

saver.save(sess, "./model/crack_capcha.model99", global_step=step)


global_step=step :在保存文件時,會統計運行了多少次。

參數使用:

獲取保存對象->獲取最後一次生成文件的路徑->導入參數到session會話中

獲取保存對象與參數保存是同樣的。

獲取最後一次生成文件的路徑:在參數保存時會生成一個checkpoint文件(個人是在model文件下),裏面會記錄最後一次生成文件的文件名。model文件

checkpoint內容

導入參數到session會話中:首先要開啓session會話,而後調用保存對象的restore方法便可。

 saver.restore(sess, checkpoint.model_checkpoint_path)

4.注意事項

 1. 在session調用run方法時,必定不能遺漏某個操做結果對應的參數賦值,這表述比較繞口,咱們來看下面的例子。

 

 _, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})  

X:輸入數據,Y:標籤數據,keep_prob:防過擬合機率因子(超參),這些參數在獲取損失函數loss,計算梯度optimizer時被用到,

在tensorflow的CNN中只是做爲佔位符處理的,因此在session調用run方法時,必定要對這些參數賦值,並用feed_dict做爲字典參數傳入,注意大小寫也要相同。

 

2. 在訓練前須要將文本轉爲向量,在預測判斷是否準確時須要將向量轉爲文本字符串。

這裏的樣例總長度63:數字10個(0-9),小寫字母26(a-z),大寫字母26(A-Z),'_':若是不夠4個字符,用來補齊。

向量長度範圍:字符4*(10 + 26 + 26 + 1) = 252

文本轉向量:經過某種規則(char2pos),計算字符數值,而後根據該字符在4個字符中的位置,計算向量索引

 

idx = i * CHAR_SET_LEN + char2pos(c)

向量轉文本:跟文本轉向量操做相反(vec2text)

 

5.代碼實現(python3.5)

在letterAndNumber.py文件中,train = 0 表示訓練,1表示預測。

 

在訓練時,採用的batch_size = 64,每訓練100次計算一次準確率,若是準確率大於0.8,就將參數保存到model文件中,準確率大於0.9,在保存參數的同時結束訓練。

在預測時,隨機採用100幅圖片,觀察其準確率;另外,對於以前展現的黏連驗證碼,人眼不能較好分辨的驗證碼,單獨進行識別。

letterAndNumber.py

 

  1 import numpy as np  
  2 import tensorflow as tf
  3 from captcha.image import ImageCaptcha
  4 import numpy as np  
  5 import matplotlib.pyplot as plt  
  6 from PIL import Image  
  7 import random   
  8 
  9 number = ['0','1','2','3','4','5','6','7','8','9']  
 10 alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
 11 ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
 12 
 13 def random_captcha_text(char_set=number+alphabet+ALPHABET, captcha_size=4):
 14 #def random_captcha_text(char_set=number, captcha_size=4):
 15     captcha_text = []  
 16     for i in range(captcha_size):  
 17         c = random.choice(char_set)  
 18         captcha_text.append(c)  
 19     return captcha_text  
 20    
 21 
 22 def gen_captcha_text_and_image(i = 0):
 23     # 建立圖像實例對象
 24     image = ImageCaptcha()  
 25     # 隨機選擇4個字符
 26     captcha_text = random_captcha_text()
 27     # array 轉化爲 string
 28     captcha_text = ''.join(captcha_text)  
 29     # 生成驗證碼
 30     captcha = image.generate(captcha_text)
 31     if i%100 == 0 :
 32         image.write(captcha_text, "./generateImage/" + captcha_text + '.jpg')
 33    
 34     captcha_image = Image.open(captcha)  
 35     captcha_image = np.array(captcha_image)  
 36     return captcha_text, captcha_image  
 37 
 38 def convert2gray(img):  
 39     if len(img.shape) > 2:  
 40         gray = np.mean(img, -1)  
 41         # 上面的轉法較快,正規轉法以下  
 42         # r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]  
 43         # gray = 0.2989 * r + 0.5870 * g + 0.1140 * b  
 44         return gray  
 45     else:  
 46         return img  
 47 
 48    
 49 # 文本轉向量
 50 def text2vec(text):  
 51     text_len = len(text)  
 52     if text_len > MAX_CAPTCHA:  
 53         raise ValueError('驗證碼最長4個字符')  
 54    
 55     vector = np.zeros(MAX_CAPTCHA*CHAR_SET_LEN)  
 56 
 57     def char2pos(c):  
 58         if c =='_':  
 59             k = 62  
 60             return k  
 61         k = ord(c)-48  
 62         if k > 9:  
 63             k = ord(c) - 55  
 64             if k > 35:  
 65                 k = ord(c) - 61  
 66                 if k > 61:  
 67                     raise ValueError('No Map')   
 68         return k  
 69 
 70     for i, c in enumerate(text):  
 71         #idx = i * CHAR_SET_LEN + int(c)
 72         idx = i * CHAR_SET_LEN + char2pos(c)
 73         vector[idx] = 1  
 74     return vector  
 75 # 向量轉回文本  
 76 def vec2text(vec):
 77     char_pos = vec[0]
 78     text=[]
 79     for i, c in enumerate(char_pos):  
 80         char_at_pos = i #c/63  
 81         char_idx = c % CHAR_SET_LEN  
 82         if char_idx < 10:  
 83             char_code = char_idx + ord('0')  
 84         elif char_idx <36:  
 85             char_code = char_idx - 10 + ord('A')  
 86         elif char_idx < 62:  
 87             char_code = char_idx-  36 + ord('a')  
 88         elif char_idx == 62:  
 89             char_code = ord('_')  
 90         else:  
 91             raise ValueError('error')  
 92         text.append(chr(char_code)) 
 93     """
 94     text=[]
 95     char_pos = vec.nonzero()[0]
 96     for i, c in enumerate(char_pos):  
 97         number = i % 10
 98         text.append(str(number)) 
 99     """
100     return "".join(text)  
101    
102 """
103 #向量(大小MAX_CAPTCHA*CHAR_SET_LEN)用0,1編碼 每63個編碼一個字符,這樣順利有,字符也有 
104 vec = text2vec("F5Sd") 
105 text = vec2text(vec) 
106 print(text)  # F5Sd 
107 vec = text2vec("SFd5") 
108 text = vec2text(vec) 
109 print(text)  # SFd5 
110 """  
111    
112 # 生成一個訓練batch  
113 def get_next_batch(batch_size=128):
114     batch_x = np.zeros([batch_size, IMAGE_HEIGHT*IMAGE_WIDTH])  
115     batch_y = np.zeros([batch_size, MAX_CAPTCHA*CHAR_SET_LEN])  
116    
117     # 有時生成圖像大小不是(60, 160, 3)  
118     def wrap_gen_captcha_text_and_image(i):
119         while True:  
120             text, image = gen_captcha_text_and_image(i)
121             if image.shape == (60, 160, 3):  
122                 return text, image  
123    
124     for i in range(batch_size):  
125         text, image = wrap_gen_captcha_text_and_image(i)
126         image = convert2gray(image)  
127    
128         batch_x[i,:] = image.flatten() / 255 # (image.flatten()-128)/128  mean爲0  
129         batch_y[i,:] = text2vec(text)  
130    
131     return batch_x, batch_y  
132    
133 
134    
135 # 定義CNN  
136 def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1):  
137     x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])  
138    
139     #w_c1_alpha = np.sqrt(2.0/(IMAGE_HEIGHT*IMAGE_WIDTH)) #  
140     #w_c2_alpha = np.sqrt(2.0/(3*3*32))   
141     #w_c3_alpha = np.sqrt(2.0/(3*3*64))   
142     #w_d1_alpha = np.sqrt(2.0/(8*32*64))  
143     #out_alpha = np.sqrt(2.0/1024)  
144    
145     # 3 conv layer  
146     w_c1 = tf.Variable(w_alpha*tf.random_normal([3, 3, 1, 32]))  
147     b_c1 = tf.Variable(b_alpha*tf.random_normal([32]))
148     # 卷積 + Relu激活函數
149     conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))  
150     # 池化
151     conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
152     # dropout 防止過擬合
153     conv1 = tf.nn.dropout(conv1, rate = 1 - keep_prob)
154    
155     w_c2 = tf.Variable(w_alpha*tf.random_normal([3, 3, 32, 64]))  
156     b_c2 = tf.Variable(b_alpha*tf.random_normal([64]))
157     # 卷積 + Relu激活函數
158     conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2))
159     # 池化
160     conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
161     # dropout 防止過擬合
162     conv2 = tf.nn.dropout(conv2, rate = 1 - keep_prob)
163    
164     w_c3 = tf.Variable(w_alpha*tf.random_normal([3, 3, 64, 64]))  
165     b_c3 = tf.Variable(b_alpha*tf.random_normal([64]))
166     # 卷積 + Relu激活函數
167     conv3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3))
168     # 池化
169     conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
170     # dropout 防止過擬合
171     conv3 = tf.nn.dropout(conv3, rate = 1 - keep_prob)
172    
173     # Fully connected layer  
174     w_d = tf.Variable(w_alpha*tf.random_normal([8*20*64, 1024]))  
175     b_d = tf.Variable(b_alpha*tf.random_normal([1024]))  
176     dense = tf.reshape(conv3, [-1, w_d.get_shape().as_list()[0]])
177     # 全鏈接 + Relu
178     dense = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d))  
179     dense = tf.nn.dropout(dense, rate = 1 - keep_prob)
180    
181     w_out = tf.Variable(w_alpha*tf.random_normal([1024, MAX_CAPTCHA*CHAR_SET_LEN]))  
182     b_out = tf.Variable(b_alpha*tf.random_normal([MAX_CAPTCHA*CHAR_SET_LEN]))
183     # 全鏈接
184     out = tf.add(tf.matmul(dense, w_out), b_out)   
185     return out  
186    
187 # 訓練  
188 def train_crack_captcha_cnn():  
189     output = crack_captcha_cnn()
190     # 計算損失
191     loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits= output, labels= Y))
192     # 計算梯度
193     optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
194     # 目標預測
195     predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])
196     # 目標預測最大值
197     max_idx_p = tf.argmax(predict, 2)
198     # 真實標籤最大值
199     max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)  
200     correct_pred = tf.equal(max_idx_p, max_idx_l)
201     # 準確率
202     accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))  
203    
204     saver = tf.train.Saver()  
205     with tf.Session() as sess:
206         # 打印tensorboard流程圖
207         tf.summary.FileWriter("./tensorboard/", sess.graph)
208         sess.run(tf.global_variables_initializer())  
209    
210         step = 0  
211         while True:  
212             batch_x, batch_y = get_next_batch(64)
213             _, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})  
214             print(step, loss_)  
215               
216             # 每100 step計算一次準確率  
217             if step % 100 == 0:
218                 batch_x_test, batch_y_test = get_next_batch(100)  
219                 acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})  
220                 print(step, acc)  
221                 # 若是準確率大於80%,保存模型,完成訓練
222                 if acc > 0.90:
223                     saver.save(sess, "./model/crack_capcha.model99", global_step=step)
224                     break
225                 if acc > 0.80:
226                     saver.save(sess, "./model/crack_capcha.model88", global_step=step)
227 
228             step += 1  
229 def crack_captcha(captcha_image, output):
230 
231     saver = tf.train.Saver()
232 
233     with tf.Session() as sess:
234         sess.run(tf.initialize_all_variables())
235         # 獲取訓練後的參數
236         checkpoint = tf.train.get_checkpoint_state("model")
237         if checkpoint and checkpoint.model_checkpoint_path:
238            saver.restore(sess, checkpoint.model_checkpoint_path)
239            print("Successfully loaded:", checkpoint.model_checkpoint_path)
240         else:
241            print("Could not find old network weights")
242 
243         predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)  
244         text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1})
245         #text = text_list[0].tolist()
246         text = vec2text(text_list)
247         return text 
248 if __name__ == '__main__':
249     train = 0  # 0: 訓練  1: 預測
250     if train == 0:
251         number = ['0','1','2','3','4','5','6','7','8','9']  
252         alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
253         ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
254         
255         text, image = gen_captcha_text_and_image()  
256         print("驗證碼圖像channel:", image.shape)  # (60, 160, 3)  
257         # 圖像大小  
258         IMAGE_HEIGHT = 60  
259         IMAGE_WIDTH = 160  
260         MAX_CAPTCHA = len(text)  
261         print("驗證碼文本最長字符數", MAX_CAPTCHA)
262         # 文本轉向量  
263         char_set = number + alphabet + ALPHABET + ['_']  # 若是驗證碼長度小於4, '_'用來補齊
264         #char_set = number
265         CHAR_SET_LEN = len(char_set)
266         # placeholder佔位符,做用域:整個頁面,不須要聲明時初始化
267         X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT*IMAGE_WIDTH])
268         Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA*CHAR_SET_LEN])  
269         keep_prob = tf.placeholder(tf.float32) # dropout 
270         
271         train_crack_captcha_cnn()
272     # 預測時須要將訓練的變量初始化,且只能初始化一次。
273     if train == 1:
274         # 天然計數
275         step = 0
276         # 正確預測計數
277         rightCnt = 0
278         # 設置測試次數
279         count = 100
280         number = ['0','1','2','3','4','5','6','7','8','9']
281         alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
282         ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
283 
284         IMAGE_HEIGHT = 60
285         IMAGE_WIDTH = 160
286 
287         char_set = number + alphabet + ALPHABET + ['_']
288         CHAR_SET_LEN = len(char_set)
289         MAX_CAPTCHA = 4  # len(text)
290         # placeholder佔位符,做用域:整個頁面,不須要聲明時初始化
291         X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT*IMAGE_WIDTH])
292         Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA*CHAR_SET_LEN])
293         keep_prob = tf.placeholder(tf.float32) # dropout
294         output = crack_captcha_cnn()
295 
296         saver = tf.train.Saver()
297         with tf.Session() as sess:
298             sess.run(tf.global_variables_initializer())
299             # 獲取訓練後參數路徑
300             checkpoint = tf.train.get_checkpoint_state("model")
301             if checkpoint and checkpoint.model_checkpoint_path:
302                 saver.restore(sess, checkpoint.model_checkpoint_path)
303                 print("Successfully loaded:", checkpoint.model_checkpoint_path)
304             else:
305                 print("Could not find old network weights.")
306 
307             while True:
308                 # image = Image.open("D:/Project/python/myProject/CNN/tensorflow/captchaIdentify/11/0sHB.jpg")
309                 # image = np.array(image)
310                 # text = '0sHB'
311                 text, image = gen_captcha_text_and_image()
312                 # f = plt.figure()
313                 # ax = f.add_subplot(111)
314                 # ax.text(0.1, 0.9,text, ha='center', va='center', transform=ax.transAxes)
315                 # plt.imshow(image)
316                 #
317                 # plt.show()
318 
319                 image = convert2gray(image)
320                 image = image.flatten() / 255
321                 predict = tf.math.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
322                 text_list = sess.run(predict, feed_dict= { X: [image], keep_prob : 1})
323                 predict_text = vec2text(text_list)
324                 predict_text = crack_captcha(image, output)
325                 # predict_text_list = [str(x) for x in predict_text]
326                 # predict_text_new = ''.join(predict_text_list)
327                 print("step:{} 真實值: {}  預測: {}  預測結果: {}".format(str(step), text, predict_text, "正確" if text.lower()==predict_text.lower() else "錯誤"))
328                 if text.lower()==predict_text.lower():
329                     rightCnt += 1
330                 if step == count - 1:
331                     print("測試總數: {} 測試準確率: {}".format(str(count), str(rightCnt/count)))
332                     break
333                 step += 1
334     
335     
336     
337     
View Code

6.運行結果以及分析

隨機採用100幅圖片,運行結果以下:

 

黏連驗證碼

   

 

運行結果

 

人眼較難識別驗證碼

      

 

運行結果

 

結果分析:隨機選取100張驗證碼測試,準確率有73%,這個準確率在同類型的驗證碼中已經比較可觀了。固然,能夠在訓練時將測試準確率繼續提升,好比0.95或更高,這樣,在預測時的準確率應該還會有提高的,你們有興趣的話能夠試試。

 

不要讓懶惰佔據你的大腦,不要讓妥協拖垮了你的人生。青春就是一張票,能不能遇上時代的快車,你的步伐就掌握在你的腳下。

相關文章
相關標籤/搜索