验证码进阶(TensorFlow--基于卷积神经网络的验证码识别)
本人的第一个深度学习实战项目,参考了网络上诸多牛人的代码,在此谢过,因时间久已,不记出处,就不一一列出,罪过罪过。
我的数据集是我用脚本在网页上扒的,标签是用之前写的验证码识别方法打的。大概用了4000+多张图训练。
我的数据集都经过处理了,降噪,二值化,最后裁剪为18*60的大小,详细见我之前的验证码简单识别那篇随笔。
#coding:utf-8
import tensorflow as tf
from PIL import Image
import os
import random
import numpy as np img_height = 18
img_width = 60
max_captcha = 4 #验证码长度
char_len =63 #用63个二进制数表示一个字符 def get_name_image():
all_image = os.listdir('D:\sctest')
random_file = random.randint(0,4000)
base = os.path.basename('D:\sctest\\' + all_image[random_file])
name = os.path.splitext(base)[0]
image = Image.open('D:\sctest\\' + all_image[random_file])
image = np.array(image)
return name,image、
#我的标签就是图片名
#标签转成向量
def name2vec(name):
vector = np.zeros(max_captcha*char_len)
def char2pos(c):
if c == '_':
k = 62
return k
k = ord(c) - 48
if k > 9:
k = ord(c) - 55
if k > 35:
k = ord(c) - 61
if k > 61:
raise ValueError('No Map')
return k for i, c in enumerate(name):
idx = i * char_len + char2pos(c)
vector[idx] = 1
return vector
#将向量装成名字,也就是输出结果,最后预测的时候用到
def vec2name(vec):
name = []
for i, c in enumerate(vec):
char_idx = c % char_len
if char_idx < 10:
char_code = char_idx + ord('')
elif char_idx < 36:
char_code = char_idx - 10 + ord('A')
elif char_idx < 62:
char_code = char_idx - 36 + ord('a')
elif char_idx == 62:
char_code = ord('_')
else:
raise ValueError('error')
name.append(chr(char_code))
return "".join(name) def get_next_batch(batch_size=64):
batch_x = np.zeros([batch_size, img_height*img_width])
batch_y = np.zeros([batch_size, max_captcha*char_len]) for i in range(batch_size):
name, image = get_name_image()
batch_x[i, :] = 1*(image.flatten())
batch_y[i, :] = name2vec(name)
return batch_x, batch_y
X = tf.placeholder(tf.float32,[None,img_width*img_height])
Y = tf.placeholder(tf.float32,[None,max_captcha*char_len])
keep_prob = tf.placeholder(tf.float32) #CNN
def crack_captcha_cnn(w_alpha=0.01,b_alpha=0.1):
x = tf.reshape(X, shape=[-1, img_height, img_width, 1])
w_c1 = tf.Variable(w_alpha * tf.random_normal([3,3, 1, 32]))
b_c1 = tf.Variable(b_alpha * tf.random_normal([32]))
conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))
conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
conv1 = tf.nn.dropout(conv1, keep_prob) w_c2 = tf.Variable(w_alpha * tf.random_normal([3, 3, 32, 64]))
b_c2 = tf.Variable(b_alpha * tf.random_normal([64 ]))
conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2))
conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
conv2 = tf.nn.dropout(conv2, keep_prob) w_c3 = tf.Variable(w_alpha * tf.random_normal([3,3, 64, 64]))
b_c3 = tf.Variable(b_alpha * tf.random_normal([64]))
conv3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3))
conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
conv3 = tf.nn.dropout(conv3, keep_prob) w_d = tf.Variable(w_alpha * tf.random_normal([3 * 8 * 64, 1024]))
b_d = tf.Variable(b_alpha * tf.random_normal([1024]))
dense = tf.reshape(conv3,[-1, w_d.get_shape().as_list()[0]])
dense = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d))
dense = tf.nn.dropout(dense, keep_prob) w_out = tf.Variable(w_alpha * tf.random_normal([1024, max_captcha * char_len]))
b_out = tf.Variable(b_alpha * tf.random_normal([max_captcha * char_len]))
out = tf.add(tf.matmul(dense, w_out), b_out)
return out #训练
def train_crack_captcha_cnn():
output = crack_captcha_cnn()
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss) predict = tf.reshape(output, [-1, max_captcha, char_len])
max_idx_p = tf.argmax(predict, 2)
max_idx_l = tf.argmax(tf.reshape(Y, [-1, max_captcha, char_len]), 2)
correct_pred = tf.equal(max_idx_p, max_idx_l)
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) step = 0
while True:
batch_x, batch_y = get_next_batch(64)
_, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.5})
print(step, loss_) # 每100 step计算一次准确率
if step % 100 == 0:
batch_x_test, batch_y_test = get_next_batch(100)
acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})
print(step, acc)
# acc大于0.9999保存模型退出
if acc > 0.9999:
saver.save(sess, "./crack_capcha.model", global_step=step)
break step += 1
train_crack_captcha_cnn() #训练完成后注释掉train_crack_captcha_cnn()方法,跑下面的预测方法,进行预测。
def crack_captcha():
output = crack_captcha_cnn() saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
n = 1
while n <= 100:
name, image = get_name_image()
image = 1 * (image.flatten())
predict = tf.argmax(tf.reshape(output, [-1, max_captcha, char_len]), 2)
name_list = sess.run(predict, feed_dict={X: [image], keep_prob: 1})
vec = name_list[0].tolist()
predict_text = vec2name(vec)
print("正确: {} 预测: {}".format(name, predict_text))
n += 1 crack_captcha()
跑了2800步,acc为1,又用1000多张图进行测试,有一张G,C识别错误。准确率在99.9%以上。
验证码进阶(TensorFlow--基于卷积神经网络的验证码识别)的更多相关文章
- 基于卷积神经网络的人脸识别项目_使用Tensorflow-gpu+dilib+sklearn
https://www.cnblogs.com/31415926535x/p/11001669.html 基于卷积神经网络的人脸识别项目_使用Tensorflow-gpu+dilib+sklearn ...
- Pytorch实现基于卷积神经网络的面部表情识别(详细步骤)
文章目录 一.项目背景 二.数据处理 1.标签与特征分离 2.数据可视化 3.训练集和测试集 三.模型搭建 四.模型训练 五.完整代码 一.项目背景数据集cnn_train.csv包含人类面部表情的图 ...
- 基于卷积神经网络的面部表情识别(Pytorch实现)----台大李宏毅机器学习作业3(HW3)
一.项目说明 给定数据集train.csv,要求使用卷积神经网络CNN,根据每个样本的面部图片判断出其表情.在本项目中,表情共分7类,分别为:(0)生气,(1)厌恶,(2)恐惧,(3)高兴,(4)难过 ...
- 深度学习项目——基于卷积神经网络(CNN)的人脸在线识别系统
基于卷积神经网络(CNN)的人脸在线识别系统 本设计研究人脸识别技术,基于卷积神经网络构建了一套人脸在线检测识别系统,系统将由以下几个部分构成: 制作人脸数据集.CNN神经网络模型训练.人脸检测.人脸 ...
- 使用TensorFlow的卷积神经网络识别自己的单个手写数字,填坑总结
折腾了几天,爬了大大小小若干的坑,特记录如下.代码在最后面. 环境: Python3.6.4 + TensorFlow 1.5.1 + Win7 64位 + I5 3570 CPU 方法: 先用MNI ...
- 基于卷积神经网络CNN的电影推荐系统
本项目使用文本卷积神经网络,并使用MovieLens数据集完成电影推荐的任务. 推荐系统在日常的网络应用中无处不在,比如网上购物.网上买书.新闻app.社交网络.音乐网站.电影网站等等等等,有人的地方 ...
- TensorFlow实现卷积神经网络
1 卷积神经网络简介 在介绍卷积神经网络(CNN)之前,我们需要了解全连接神经网络与卷积神经网络的区别,下面先看一下两者的结构,如下所示: 图1 全连接神经网络与卷积神经网络结构 虽然上图中显示的全连 ...
- 硕毕论文_基于 3D 卷积神经网络的行为识别算法研究
论文标题:基于 3D 卷积神经网络的行为识别算法研究 来源/作者机构情况: 中 国 地 质 大 学(北京),计算机学院,图像处理方向 解决问题/主要思想贡献: 1. 使用张量CP分解的原理, ...
- 【RS】Automatic recommendation technology for learning resources with convolutional neural network - 基于卷积神经网络的学习资源自动推荐技术
[论文标题]Automatic recommendation technology for learning resources with convolutional neural network ( ...
- 完全基于卷积神经网络的seq2seq
本文参考文献: Gehring J, Auli M, Grangier D, et al. Convolutional Sequence to Sequence Learning[J]. arXiv ...
随机推荐
- 从FCN到DeepLab
图像语义分割,简单而言就是给定一张图片,对图片上的每一个像素点分类. 图像语义分割,从FCN把深度学习引入这个任务,一个通用的框架事:前端使用FCN全卷积网络输出粗糙的label map,后端使用CR ...
- poi导入Excel,数字科学记数法转换
在这里分享一下使用poi 导入Excel时 把数字转换为科学记数法的解决方法: 就是使用DecimalFormat对 i 进行了格式化 结果为:
- ambari下 hive metastore 启动失败
由字符集引起的hive 元数据进程启动失败 解决方法新增 这2句话 reload(sys)sys.setdefaultencoding('utf8')
- [转]Nginx基本功能极速入门
原文链接:Nginx基本功能极速入门 | 叉叉哥的BLOG 本文主要介绍一些Nginx的最基本功能以及简单配置,但不包括Nginx的安装部署以及实现原理.废话不多,直接开始. 1.静态HTTP服务器 ...
- c++函数常用
isalnum 判断一个字符是否是字符类的数字或字母isalpha 判断一个字符是否是字母isblank 判断一个字符是否是空白字符(空格,水平制表符,TAB)iscntrl 判断一个控制符(ASCI ...
- XeLaTeX中文模板
XeLaTeX对中文的支持很友好,可以直接调用系统已安装字体进行文档的撰写.其中需要引用字体的名字,开始遇到了写问题,经常发现字体未引用,现在大概明白了. 引用字体的时候,如果不加中括号,就需要引用字 ...
- Defraggler磁盘碎片整理工具,让你的电脑读写速度更快
相信大家都听说过磁盘碎片整理吧,所谓磁盘碎片,通俗的来说,就是指计算机中的各种文件最开始在磁盘中存储的时候地址都是连在一起的,但是随着文件 的多次读写,或者说多次的移动复制等操作,这些文件在磁盘中的地 ...
- 【Unity与23种设计模式】迭代器模式(Iterator)
GoF中定义: "在不知道集合内部细节的情况下,提供一个按序方法存取一个对象集合体的每一个单元." 迭代器模式由于经常使用到 已经被现代程序设计语言纳为标准语句或收录到标准函数库中 ...
- hidden symbol `pthread_atfork'
gcc交叉编译时发生这种错误 /.. .../voice_demo: hidden symbol `pthread_atfork' in /opt/gcc-linaro-aarch64-linux-g ...
- mysql 数据库基本命令语句
mysql mariadb 客户端连接 mysql -uroot -p; 客户端退出exit 或 \q 显示所有数据库show databases;show schemas; 创建数据库create ...