tensorflow实战:端到端简单粗暴识别验证码(反爬利器)

今天分享一下如何简单粗暴的解决验证码的办法

背景:

  • 对于一个爬虫开发者来说,反爬虫无疑是一个又爱又恨的对手,两者之间通过键盘的斗争更是一个没有硝烟的战场。
  • 反爬虫有很多措施,在这里说说验证码这一块
  • 论爬虫修养大家都是混口饭吃上有老下有小,码农何苦为难码农?爬数据的时候尽可能减少服务器压力,能爬列表页,就不爬详情页,

环境

正文:

  • 数据集:百度上找的一个验证码数据集(因为懒得生成),也可以自己生成。

  • 在训练前可以先对图片进行降噪,去掉干扰点,可以用opencv里面的函数滤波器等。这样识别会快点

  • 在这里我就没有去做啦,不然怎么叫粗暴呢(真正:懒, 没时间)

  • 准确率训练到90+我就保存模型停止了,大家可以根据需求设置。看下图

  • 在这里插入图片描述

  • 这里是训练中的loss以及accuracy

  • 在这里插入图片描述

  • 这里是测试

  • 在这里插入图片描述在这里插入图片描述

  • 这个是识别有错误的,毕竟我的GTX950也辛苦算了这么久,再说这个7这么像1呀。莫得了。

  • 在这里插入图片描述在这里插入图片描述

话不多说来个网络结构图再说

在这里插入图片描述

觉得有点乱的,看看下面的图

在这里插入图片描述

划重点:show you code

import numpy as np
import tensorflow as tf
from PIL import Image
import os
import random
import time

number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# 图片所在文件夹
data_dir = 'F:/checkimages/train'

# 图片长宽
width = 160
height = 60
# 验证码长度
max_captcha = 4
# 每一批次的样本数
batch_size = 64
# 字符类别的长度
num_numbers = len(number)


def get_train_data(data_dir=data_dir):
    # 获取文件中的所有图片的路径
    # 返回包含所有的图片的地址和标签的键值对一个字典
    simples = {}
    for file_name in os.listdir(data_dir):
        captcha = file_name.split('.')[0]
        # {"F:/checkimages/train/1231.jpg" : "1231"}
        simples[data_dir + '/' + file_name] = captcha
    return simples

simples = get_train_data(data_dir)

# 获取所有的键,也就是所有图片的详细地址
file_dir = list(simples.keys())
num_simples = len(simples)

# 获取一批次的数据
def get_next_batch()# 初始化全部为0的张量
    # batch_x :[64, 160*60]
    batch_x = np.zeros([batch_size, width * height])
    # batch_y: [64, 10类别 * 4个字符]
    batch_y = np.zeros([batch_size, num_numbers * max_captcha])

    # 随机选取一张图片的数据填进去batch_x,batch_y
    # 注意,因为是随机选的,也即是有可能选到同一张,不过没关系
    for i in range(batch_size):
        # 随机选出一个simples里面的键,也就是图片的路径,如 F:/checkimages/train/1231.jpg
        file_name = file_dir[random.randint(0, num_simples - 1)]
        # 给每一个样本输入数值,覆盖掉之前的0
        # np.float32(Image.open(file_name).convert('L')):
        # [[247. 247. 247. ... 247. 247. 247.]
        # [247. 247. 247. ... 247. 247. 247.]]
        # flatten(): 将2维的像素值转化为一维的
        # 当然还要标准化,除255
        batch_x[i, :] = np.float32(Image.open(file_name).convert('L')).flatten() / 255
        # 获取每一个图片的标签,转化为one-hot编码
        batch_y[i, :] = text2vec(simples[file_name])
    return batch_x, batch_y

# 将目标值转换为one-hot编码。 
def text2vec(text):
    return [0 if ord(i) - 48 != j else 1 for i in text for j in range(num_numbers)]

3个卷积层, 2个全连接层,看不懂的可以看下我写的这个博客


with tf.name_scope("input_data"):
    x = tf.placeholder(tf.float32, [None, width * height], name='input')
    y_ = tf.placeholder(tf.float32, [None, num_numbers * max_captcha])


with tf.name_scope("conv1"):
    # 运算前,先转换图片像素数据的维度
    x_image = tf.reshape(x, [-1, height, width, 1])
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)

with tf.name_scope("conv2"):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)

with tf.name_scope("conv3"):
    W_conv3 = weight_variable([5, 5, 64, 64])
    b_conv3 = bias_variable([64])
    h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)
    h_pool3 = max_pool_2x2(h_conv3)

with tf.name_scope("fc1"):
    W_fc1 = weight_variable([8 * 20 * 64, 1024])
    b_fc1 = bias_variable([1024])
    h_pool3_flat = tf.reshape(h_pool3, [-1, 8 * 20 * 64])
    # 全连接层加了激活函数
    h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1)

with tf.name_scope("fc2"):
    W_fc2 = weight_variable([1024, num_numbers * max_captcha])
    b_fc2 = bias_variable([num_numbers * max_captcha])
    output = tf.matmul(h_fc1, W_fc2) + b_fc2
    output = tf.softmax(output)

损失函数,以及优化器

with tf.name_scope("loss"):
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=output))

with tf.name_scope("AdamOptimizer"):
	# 1e-4也就是: 0.0001 
    train_step = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cross_entropy)

with tf.name_scope("accuracy"):
    predict = tf.reshape(output, [-1, max_captcha, num_numbers])
    labels = tf.reshape(y_, [-1, max_captcha, num_numbers])
    correct_prediction = tf.equal(tf.argmax(predict, 2, name='predict_max_idx'), tf.argmax(labels, 2))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

最后就是训练了

with tf.Session() as sess:
    # sess = tf.InteractiveSession()
    sess.run(init_op)
    # 保存事件文件
    train_writer = tf.summary.FileWriter("F:/checkimages/event/", graph=sess.graph)

    saver = tf.train.Saver()  # 用于保存模型
    for i in range(8000):
        batch_x, batch_y = get_next_batch()
        if i % 100 == 0:
            train_accuracy = sess.run(accuracy, feed_dict={x: batch_x, y_: batch_y})
            print("第%d步 --- >准确率为: %g " % (i, sess.run(accuracy, feed_dict={x: batch_x, y_: batch_y})))

            # 保存训练过程的数据变化
            summary = sess.run(merged,  feed_dict={x: batch_x, y_: batch_y})
            train_writer.add_summary(summary, i)

            if train_accuracy > 0.90:
                saver.save(sess, "F:/checkimages/model/output.model", global_step=i)
                break
        # 训练模型
        sess.run(train_step, feed_dict={x: batch_x, y_: batch_y})

小结:

  • 这次分享主要目的事分享一下实现的代码,但不是说看了文章就可以识别验证码了。想要自己解决这些问题没有其他的办法。从头开始学,欢迎学习交流一下。
  • 这次使用的就是单任务训练模式。以后还会分享多任务模式以及使用Alexnet来实现。有兴趣的可以关注一下,以防迷路。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章