tensorFlow(六)应用-基于CNN破解验证码
TensorFlow基础见前博客
简介
步骤简介
generate_captcha.py- 利用 Captcha 库生成验证码;captcha_model.py- CNN 模型;train_captcha.py- 训练 CNN 模型;predict_captcha.py- 识别验证码。
数据学习
安装 captcha 库
pip install captcha
获取训练数据
#-*- coding:utf-8 -*-
from captcha.image import ImageCaptcha
from PIL import Image
import numpy as np
import random
import string class generateCaptcha():
def __init__(self,
width = 160,#验证码图片的宽
height = 60,#验证码图片的高
char_num = 4,#验证码字符个数
characters = string.digits + string.ascii_uppercase + string.ascii_lowercase):#验证码组成,数字+大写字母+小写字母
self.width = width
self.height = height
self.char_num = char_num
self.characters = characters
self.classes = len(characters) def gen_captcha(self,batch_size = 50):
X = np.zeros([batch_size,self.height,self.width,1])
img = np.zeros((self.height,self.width),dtype=np.uint8)
Y = np.zeros([batch_size,self.char_num,self.classes])
image = ImageCaptcha(width = self.width,height = self.height) while True:
for i in range(batch_size):
captcha_str = ''.join(random.sample(self.characters,self.char_num))
img = image.generate_image(captcha_str).convert('L')
img = np.array(img.getdata())
X[i] = np.reshape(img,[self.height,self.width,1])/255.0
for j,ch in enumerate(captcha_str):
Y[i,j,self.characters.find(ch)] = 1
Y = np.reshape(Y,(batch_size,self.char_num*self.classes))
yield X,Y def decode_captcha(self,y):
y = np.reshape(y,(len(y),self.char_num,self.classes))
return ''.join(self.characters[x] for x in np.argmax(y,axis = 2)[0,:]) def get_parameter(self):
return self.width,self.height,self.char_num,self.characters,self.classes def gen_test_captcha(self):
image = ImageCaptcha(width = self.width,height = self.height)
captcha_str = ''.join(random.sample(self.characters,self.char_num))
img = image.generate_image(captcha_str)
img.save(captcha_str + '.jpg') X = np.zeros([1,self.height,self.width,1])
Y = np.zeros([1,self.char_num,self.classes])
img = img.convert('L')
img = np.array(img.getdata())
X[0] = np.reshape(img,[self.height,self.width,1])/255.0
for j,ch in enumerate(captcha_str):
Y[0,j,self.characters.find(ch)] = 1
Y = np.reshape(Y,(1,self.char_num*self.classes))
return X,Y
理解训练数据
- X:一个 mini-batch 的训练数据,其 shape 为 [ batch_size, height, width, 1 ],batch_size 表示每批次多少个训练数据,height 表示验证码图片的高,width 表示验证码图片的宽,1 表示图片的通道。
- Y:X 中每个训练数据属于哪一类验证码,其形状为 [ batch_size, class ] ,对验证码中每个字符进行 One-Hot 编码,所以 class 大小为 4*62。
- 获取验证码和对应的分类
cd /home/ubuntu;
python
from generate_captcha import generateCaptcha
g = generateCaptcha()
X,Y = g.gen_test_captcha()
- 查看训练数据
X.shape
Y.shape
可以在 /home/ubuntu目录下查看生成的验证码,jpg 格式的图片可以点击查看。
模型学习
CNN 模型

# -*- coding: utf-8 -*
import tensorflow as tf
import math class captchaModel():
def __init__(self,
width = 160,
height = 60,
char_num = 4,
classes = 62):
self.width = width
self.height = height
self.char_num = char_num
self.classes = classes def conv2d(self,x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(self,x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME') def weight_variable(self,shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial) def bias_variable(self,shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial) def create_model(self,x_images,keep_prob):
#first layer
w_conv1 = self.weight_variable([5, 5, 1, 32])
b_conv1 = self.bias_variable([32])
h_conv1 = tf.nn.relu(tf.nn.bias_add(self.conv2d(x_images, w_conv1), b_conv1))
h_pool1 = self.max_pool_2x2(h_conv1)
h_dropout1 = tf.nn.dropout(h_pool1,keep_prob)
conv_width = math.ceil(self.width/2)
conv_height = math.ceil(self.height/2) #second layer
w_conv2 = self.weight_variable([5, 5, 32, 64])
b_conv2 = self.bias_variable([64])
h_conv2 = tf.nn.relu(tf.nn.bias_add(self.conv2d(h_dropout1, w_conv2), b_conv2))
h_pool2 = self.max_pool_2x2(h_conv2)
h_dropout2 = tf.nn.dropout(h_pool2,keep_prob)
conv_width = math.ceil(conv_width/2)
conv_height = math.ceil(conv_height/2) #third layer
w_conv3 = self.weight_variable([5, 5, 64, 64])
b_conv3 = self.bias_variable([64])
h_conv3 = tf.nn.relu(tf.nn.bias_add(self.conv2d(h_dropout2, w_conv3), b_conv3))
h_pool3 = self.max_pool_2x2(h_conv3)
h_dropout3 = tf.nn.dropout(h_pool3,keep_prob)
conv_width = math.ceil(conv_width/2)
conv_height = math.ceil(conv_height/2) #first fully layer
conv_width = int(conv_width)
conv_height = int(conv_height)
w_fc1 = self.weight_variable([64*conv_width*conv_height,1024])
b_fc1 = self.bias_variable([1024])
h_dropout3_flat = tf.reshape(h_dropout3,[-1,64*conv_width*conv_height])
h_fc1 = tf.nn.relu(tf.nn.bias_add(tf.matmul(h_dropout3_flat, w_fc1), b_fc1))
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) #second fully layer
w_fc2 = self.weight_variable([1024,self.char_num*self.classes])
b_fc2 = self.bias_variable([self.char_num*self.classes])
y_conv = tf.add(tf.matmul(h_fc1_drop, w_fc2), b_fc2) return y_conv
训练 CNN 模型
示例代码:
#-*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
import string
import generate_captcha
import captcha_model if __name__ == '__main__':
captcha = generate_captcha.generateCaptcha()
width,height,char_num,characters,classes = captcha.get_parameter() x = tf.placeholder(tf.float32, [None, height,width,1])
y_ = tf.placeholder(tf.float32, [None, char_num*classes])
keep_prob = tf.placeholder(tf.float32) model = captcha_model.captchaModel(width,height,char_num,classes)
y_conv = model.create_model(x,keep_prob)
cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_,logits=y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) predict = tf.reshape(y_conv, [-1,char_num, classes])
real = tf.reshape(y_,[-1,char_num, classes])
correct_prediction = tf.equal(tf.argmax(predict,2), tf.argmax(real,2))
correct_prediction = tf.cast(correct_prediction, tf.float32)
accuracy = tf.reduce_mean(correct_prediction) saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
step = 1
while True:
batch_x,batch_y = next(captcha.gen_captcha(64))
_,loss = sess.run([train_step,cross_entropy],feed_dict={x: batch_x, y_: batch_y, keep_prob: 0.75})
print ('step:%d,loss:%f' % (step,loss))
if step % 100 == 0:
batch_x_test,batch_y_test = next(captcha.gen_captcha(100))
acc = sess.run(accuracy, feed_dict={x: batch_x_test, y_: batch_y_test, keep_prob: 1.})
print ('###############################################step:%d,accuracy:%f' % (step,acc))
if acc > 0.99:
saver.save(sess,"./capcha_model.ckpt")
break
step += 1
然后执行:
cd /home/ubuntu;
python train_captcha.py
执行结果:
step:75193,loss:0.010931
step:75194,loss:0.012859
step:75195,loss:0.008747
step:75196,loss:0.009147
step:75197,loss:0.009351
step:75198,loss:0.009746
step:75199,loss:0.010014
step:75200,loss:0.009024
###############################################step:75200,accuracy:0.992500
使用训练好的模型:
train_captcha.py 文件中 if acc > 0.99: 代码行的准确度节省训练时间(比如将 0.99 为 0.01),体验训练过程;我们已经通过长时间的训练得到了一个训练好的模型,可以通过如下命令将训练集下载到本地。wget http://tensorflow-1253902462.cosgz.myqcloud.com/captcha/capcha_model.zip
unzip -o capcha_model.zip
识别验证码
测试数据集:
wget 命令获取:wget http://tensorflow-1253902462.cosgz.myqcloud.com/captcha/captcha.zip
unzip -q captcha.zip
然后执行:
cd /home/ubuntu;
python predict_captcha.py captcha/0hWn.jpg
执行结果:
0hWn
tensorFlow(六)应用-基于CNN破解验证码的更多相关文章
- TensorFlow - 深度学习破解验证码 实验
TensorFlow - 深度学习破解验证码 简介:验证码主要用于防刷,传统的验证码识别算法一般需要把验证码分割为单个字符,然后逐个识别,如果字符之间相互重叠,传统的算法就然并卵了,本文采用cnn对验 ...
- 基于CNN的人群密度图估计方法简述
人群计数的方法分为传统的视频和图像人群计数算法以及基于深度学习的人群计数算法,深度学习方法由于能够方便高效地提取高层特征而获得优越的性能是传统方法无法比拟的.本文简单了秒速了近几年,基于单张图像利用C ...
- CNN大战验证码
介绍 爬虫江湖,风云再起.自从有了爬虫,也就有了反爬虫:自从有了反爬虫,也就有了反反爬虫. 反爬虫界的一大利器,就是验证码(CAPTCHA),各种各样的验证码让人眼花缭乱,也让很多人在爬虫的过 ...
- tensorflow笔记:多层CNN代码分析
tensorflow笔记系列: (一) tensorflow笔记:流程,概念和简单代码注释 (二) tensorflow笔记:多层CNN代码分析 (三) tensorflow笔记:多层LSTM代码分析 ...
- TensorFlow系列专题(十三): CNN最全原理剖析(续)
目录: 前言 卷积层(余下部分) 卷积的基本结构 卷积层 什么是卷积 滑动步长和零填充 池化层 卷积神经网络的基本结构 总结 参考文献 一.前言 上一篇我们一直说到了CNN[1]卷积层的特性,今天 ...
- SQL Server 2008空间数据应用系列六:基于SQLCRL的空间数据可编程性
原文:SQL Server 2008空间数据应用系列六:基于SQLCRL的空间数据可编程性 友情提示,您阅读本篇博文的先决条件如下: 1.本文示例基于Microsoft SQL Server 2008 ...
- cvpr2017:branchout——基于CNN的在线集成跟踪
1.引言 2017年CVPR上有不少关于跟踪的paper.CF方面最引人瞩目的应该是ECO了,CNN方面也有一些新的进展.Branchout是一个基于CNN用bagging集成的在线跟踪方法. con ...
- LSF-SCNN:一种基于 CNN 的短文本表达模型及相似度计算的全新优化模型
欢迎大家前往腾讯云社区,获取更多腾讯海量技术实践干货哦~ 本篇文章是我在读期间,对自然语言处理中的文本相似度问题研究取得的一点小成果.如果你对自然语言处理 (natural language proc ...
- 实验楼Python破解验证码
本人大二,因为Python结业考试项目,又想要学习机器学习方向,但是由于接触时间不长,选择了实验楼的Python破解验证码这个项目作为我的项目, 我在原来的基础上加了一些代码用于完善,并且对功能如何实 ...
随机推荐
- 《linux就该这么学》第七节课:文件的各种权限以及linux分区命名规则
笔记 (借鉴请改动) 5.3:文件特殊权限 SUID 临时拥有文件所有者的权限(基本上只是执行权限) SGID 临时拥有文件所有组的权限,在目录中创建文件自动继承该目录的用户组. SBIT 粘滞 ...
- git----------如何创建develop分支和工作流,以及如何将develop上的代码合并到master分支上
1.点击sourceTree 右上角的git工作流,或弹出一个弹出框,无需修改任何东西直接点击确认就可以创建develop. . 2.这里有两个分支了,当前高亮的就是你当前处在的分支.此时develo ...
- 让hive的表注释和字段注释支持中文
此处用的数据库类型为mysql.发现hive在初始化创建这些表的时候,大部分字段的字符集给设置成了latin1,然后collation设成了latin1_bin. 但是我们在hive中创建表时,表注释 ...
- 5.Python3程序结构
5.1顺序结构 一条语句一条语句顺序的执行. 5.2选择结构 条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: 5.2. ...
- 解决IDEA无法安装插件的问题
进入2018年以来,在IDEA插件中心中,安装插件经常安装失败,报连接超时的错误.如下: 我们发现连接IDEA的插件中心使用的是https的链接,我们在浏览器中使用https访问插件中心并不能访问. ...
- 史上最全的PHP常用函数大全,不看看你就out了(还会不断更新哦!)
纪录了PHP的一些常用函数和函数代码!不要错过了哦. PHP的一些常用函数usleep() 函数延迟代码执行若干微秒.unpack() 函数从二进制字符串对数据进行解包.uniqid() 函数基于以微 ...
- 颜色扩展类--ColorExtensions
/// <summary> /// 颜色扩展类 /// </summary> public static class ColorExtensions { /// <sum ...
- ethtools命令详解
1 概述 ethtool 是用于查询及设置网卡参数的命令. 2 命令详解 2.1 命令格式 (1) 语法 ethtool [ -a | -c | -g | -i | -d | -k | -r | -S ...
- Python Redis 发布订阅
发布者:服务器 订阅者:Dashboad和数据处理 频道主逻辑 import redis class RedisHelper: def __init__(self): # 链接服务端 self.__c ...
- hbot固件配置
又入了一台打印机,171到手,本来之前有更好的,无奈别人下手太快,只剩这台了. 175x135x180的样子. 创客的板,还带16g的闪迪内存卡,看到那会儿感觉赚大了! 拿到的时候不少螺丝松的,有的打 ...