验证码的生成与识别
本文系作者原创,转载请注明出处:https://www.cnblogs.com/further-further-further/p/10755361.html
目录
1.验证码的制作
2.卷积神经网络结构
3.训练参数保存与使用
4.注意事项
5.代码实现(python3.5)
6.运行结果以及分析
1.验证码的制作
深度学习一个必要的前提就是需要大量的训练样本数据,毫不夸张的说,训练样本数据的多少直接决定模型的预测准确度。而本节的训练样本数据(验证码:字母和数字组成)通过调用Image模块(图像处理库)中相关函数生成。
安装:pip install pillow
验证码生成步骤:随机在字母和数字中选择4个字符 -> 创建背景图片 -> 添加噪声 -> 字符扭曲
具体样本如下所示:
对于上图的验证码,如果用传统方式破解,其步骤一般是:
图片分割:采用分割算法分割出每一个字符;
字符识别:由分割出的每个字符图片,根据OCR光学字符识别出每个字符图片对应的字符;
难点在于:对于图片字符有黏连(2个,3个,或者4个全部黏连),图片是无法完全分割出来的,也就是说,即使分割出来了,字符识别基本上都是错误的,特别对于人眼都无法分辨的验证码,用传统的这种破解方法,成功率基本上是极其低的。
黏连验证码
人眼几乎无法分辨验证码
第一张是 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 337View Code
captchaIdentify.py
1 import tensorflow as tf 2 from captcha.image import ImageCaptcha 3 import numpy as np 4 import matplotlib.pyplot as plt 5 from PIL import Image 6 import random 7 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 captcha_text = [] 15 for i in range(captcha_size): 16 c = random.choice(char_set) 17 captcha_text.append(c) 18 return captcha_text 19 20 21 def gen_captcha_text_and_image(): 22 image = ImageCaptcha() 23 24 captcha_text = random_captcha_text() 25 captcha_text = ''.join(captcha_text) 26 27 captcha = image.generate(captcha_text) 28 #image.write(captcha_text, captcha_text + '.jpg') 29 30 captcha_image = Image.open(captcha) 31 captcha_image = np.array(captcha_image) 32 return captcha_text, captcha_image 33 if __name__ == '__main__': 34 text, image = gen_captcha_text_and_image() 35 36 f = plt.figure() 37 ax = f.add_subplot(111) 38 ax.text(0.1, 0.9,text, ha='center', va='center', transform=ax.transAxes) 39 plt.imshow(image) 40 41 plt.show()View Code
6.运行结果以及分析
随机采用100幅图片,运行结果如下:
黏连验证码
运行结果
人眼较难识别验证码
运行结果
结果分析:随机选取100张验证码测试,准确率有73%,这个准确率在同类型的验证码中已经比较可观了。当然,可以在训练时将测试准确率继续提高,比如0.95或更高,这样,在预测时的准确率应该还会有提升的,大家有兴趣的话可以试试。
不要让懒惰占据你的大脑,不要让妥协拖垮了你的人生。青春就是一张票,能不能赶上时代的快车,你的步伐就掌握在你的脚下。