验证码进阶(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 ...
随机推荐
- JQuery AJAX 全局设置
现在需要给每个请求都加一个请求头,挨个修改太麻烦.可以用如下方式: $.ajaxSettings.beforeSend= function(request) { request.setRequestH ...
- 【经验随笔】Java程序远程调试定位特定运行环境上出现的问题
Java后台程序远程调试 第一步:在JVM的启动参数中增加-Xdebug -Xrunjdwp:transport=dt_socket,address=6688,server=y,suspend=n 第 ...
- Vue2.0 demo:百度百聘第三方web客户端
github地址:https://github.com/axel10/baipin_vue 项目地址:https://vcollection.org/baipin/ 官方的百度百聘客户端存在翻页时过滤 ...
- python—day02
python的版本与基本类型... 第一: 讲了计算机的基础的补充,讲解了什么是操作系统,计算机硬件,应用程序之间的关系: 操作系统是一个能协调管理计算机软件与硬件的软件程序: 能帮我们发送指令集到C ...
- VS快速注释
注释:Ctrl+k + Ctrl+c 去注释:Ctrl+k + Ctrl +u
- 关于“应用程序无法启动,因为应用程序的并行配置不正确。请参阅应用程序事件日志,或使用命令行sxstrace.exe工具”问题的解决方法
今天打开QQ管家加速版的时候突然出现了这个错误,百度了下说是系统缺少Microsoft Visual C++ 20XX(运行库),下载这个安装即可解决问题.
- 关于Android SDK Manager更新速度慢的解决方法
因为我的C盘比较小,android sdk安装在c盘那么他下载的东西也会默认在c盘.所以我选择安装在其他的盘.而且我发现android sdk manager可以开多个窗口,这样的话如果每个窗口都很慢 ...
- Ambari Log Search
文章作者:luxianghao 文章来源:http://www.cnblogs.com/luxianghao/p/8630195.html 转载请注明,谢谢合作. 免责声明:文章内容仅代表个人观点, ...
- 剑指Offer-数组中重复的数字
package Array; /** * 数组中重复的数字 *在一个长度为n的数组里的所有数字都在0到n-1的范围内. * 数组中某些数字是重复的,但不知道有几个数字是重复的.也不知道每个数字重复几次 ...
- 【Django】 初步学习
这个系列(或者成不了一个系列..)预计会全程参考Vamei様的Django系列,膜一发.说句题外话,其实更加崇拜像Vamei那样的能够玩转生活.各个领域都能取得不小成就的人. [Django] ■ 概 ...