验证码进阶(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 ...
随机推荐
- Python魔法方法(转发整合)
如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一切都是自动发生的. __new__: 是一个对象实例化时调用的第一 ...
- 【learning】凸包
吐槽 计算几何这种东西qwq一开始真的觉得恶心qwq(主要是总觉得为啥画图那么直观的东西非要写一大堆式子来求qwq真的难受qwq) 但其实静下心来学习的话感觉还是很妙的ovo题目思考起来也十分好玩ov ...
- 关系型数据库工作原理-SQL解析(翻译自Coding-Geek文章)
本文翻译自Coding-Geek文章:< How does a relational database work>.原文链接:http://coding-geek.com/how-data ...
- oracle使用中的一些问题
一.设置自增主键(假设表的主键名为:company_id) 1)创建序列(company_autoinc): maxvalue start increment nocache; 2)创建触发器(com ...
- 完整的站内搜索实战应用(Lucene.Net+盘古分词)
首先自问自答几个问题,以让各位看官了解写此文的目的 什么是站内搜索?与一般搜索的区别? 多网站都有搜索功能,很多都是用SQL语句的Like实现的,但是Like无法做到模糊匹配(例如我搜索". ...
- WPF自学入门(七)WPF 初识Binding
今天记录一下Binding的基础和具体的使用方法,说起这个Binding,在WPF中,Binding是很重要的特征,在传统的Windows软件来看,大多数都是UI驱动程序的模式,也可以说事件驱动程序, ...
- JS如何判断滚动条是否滚到底部
判断滚动条到底部,需要用到DOM的三个属性值,即scrollTop.clientHeight.scrollHeight. scrollTop为滚动条在Y轴上的滚动距离. clientHeigh ...
- Maven打包的三种方式(转)
Maven可以使用mvn package指令对项目进行打包,如果使用Java -jar xxx.jar执行运行jar文件,会出现"no main manifest attribute, in ...
- C语言第十次博客作业--结构体
一.PTA实验作业 题目1: 结构体数组按总分排序 1. 本题PTA提交列表 2. 设计思路 求出每名学生的总分 定义i,j循环变量 for i=0 to n for j=0 to 3 p[i].su ...
- pyrhon多进程操作初探
linux系统中提供了fork函数进行进程的创建,这个接口在函数返回上比较特殊,有两个返回值,一个是子进程返回值为0,一个是父进程返回值,值大于0,表是子进程的ID.如果小于0.则表示接口出错. py ...