深度学习笔记(3)破解验证码

验证码生成程序:

from captcha.image import ImageCaptcha  # pip install captcha
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import random
 
# 验证码中的字符, 就不用汉字了
number = ['0','1','2','3','4','5','6','7','8','9']
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
# 验证码一般都无视大小写;验证码长度4个字符
def random_captcha_text(char_set=number+alphabet+ALPHABET, captcha_size=4):
    captcha_text = []
    for i in range(captcha_size):
        c = random.choice(char_set)
        captcha_text.append(c)
    return captcha_text
 
# 生成字符对应的验证码
def gen_captcha_text_and_image():
    image = ImageCaptcha()
 
    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)
 
    captcha = image.generate(captcha_text)
    #image.write(captcha_text, captcha_text + '.jpg')  # 写到文件
 
    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
 
if __name__ == '__main__':
    # 测试
    text, image = gen_captcha_text_and_image()
 
    f = plt.figure()
    ax = f.add_subplot(111)
    ax.text(0.1, 0.9,text, ha='center', va='center', transform=ax.transAxes)
    plt.imshow(image)
 
    plt.show()

上面是参考代码,我的过程,notebook怎么坏了。。。。
我现在只想破解4位带数字的验证码
生成一万个数字串

labels = [random_captcha_text(number,4) for _ in range(10000)]

生成验证码(这里有个缺点就是生成相同验证码会覆盖)

for l in labels:
    name = ''.join(l)
    image.write(name,'D:/png/'+name+'.png')

列出所有文件

import os
print(os.listdir('D:/png'))
filenames = os.listdir('D:/png')

从文件名中提取标签

labels = [filename[:4] for filename in filenames]

把标签转换为向量(1,40),不要问为何是40维度,我想了两天

import numpy as np
def dtv(nums):#data to vector
    ret = []
    for d in nums:
        v = np.zeros((1,10),dtype=np.float32)
        v[0,int(d)] = 1
        ret.append(v)
    return np.hstack(ret)
vectors = np.vstack([ dtv(l) for l in labels])

读取图像数据

paths = ['D:/png/'+filename for filename in filenames]
imdatas = [np.array(Image.open(p)) for p in paths]

这里出现了问题,我没有像上面那样把样本都集中起来vstack。这里发现验证码的维度出现了问题,大部分图像的维度是(60,164,3),但是有少部分图像是(60,164,3)这里必须要进行裁剪。
测试用的裁剪代码

xx00 = np.delete(xx0,[160,161,162,163],axis=1)

http://www.mamicode.com/info-detail-1666278.html

第二天修改

labels = [''.join(random_captcha_text(number,4)) for _ in range(10000)]
def dtv(nums):#data to vector
    ret = []
    for d in nums:
        v = np.zeros((1,10),dtype=np.float32)
        v[0,int(d)] = 1
        ret.append(v)
    return np.hstack(ret)
def getdatas(labels,retlabel=False):
    image = ImageCaptcha()
    x = []
    y = []
    for l in labels:
        captcha = image.generate(l)
        im = Image.open(captcha)
        imdata = np.array(im)
        if (60,164,3) == imdata.shape:
            imdata = np.delete(imdata,[160,161,162,163],axis=1)
        v = dtv(l)
        x.append(imdata)
        y.append(v)
    return np.vstack(x),np.vstack(y)
深度学习笔记(3)破解验证码_第1张图片
Paste_Image.png
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)
def gettrains(train_images,train_labels,num):
    start = np.random.randint(10000)
    limit = 10000-num
    if start>limit:
        start = limit
    t_x = train_images[start:start+num]
    t_y = train_labels[start:start+num]
    return (t_x,t_y)
def cnn_train(train_images,train_labels,test_images = None,test_labels = None):
    
    x = tf.placeholder("float", [None, 60,160,3])
    y_ = tf.placeholder("float", [None,40])

    '''
    卷积第一层
    '''
    W_conv1 = weight_variable([5, 5, 3, 36])
    b_conv1 = bias_variable([36])

    h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)

    '''
    卷积第二层
    '''

    W_conv2 = weight_variable([5, 5, 36, 72])
    b_conv2 = bias_variable([72])

    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)

    '''
    全连接层
    '''

    W_fc1 = weight_variable([15 * 60 * 72, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 15 * 60 * 72])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)


    '''
    抛弃部分节点
    '''

    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    '''
    输出层
    '''
    W_fc2 = weight_variable([1024, 40])
    b_fc2 = bias_variable([40])
    
    
    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
    
    vals = [W_conv1,b_conv1,W_conv2,b_conv2,W_fc1,b_fc1,W_fc2,b_fc2]
    
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_))
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    for i in range(2000):
        batch_xs, batch_ys = gettrains(train_images,train_labels,100)
        if i%100 == 0:
            train_accuracy = accuracy.eval(session=sess,feed_dict={x:batch_xs, y_: batch_ys, keep_prob: 1.0})
            print("step %d, training accuracy %g"%(i, train_accuracy))
        train_step.run(session=sess,feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})
    return sess.run(vals)#计算结果
    #print("test accuracy %g"%accuracy.eval(session=sess,feed_dict={x: test_images, y_: test_labels, keep_prob: 1.0}))
def predict(x,W_conv1,b_conv1,W_conv2,b_conv2,W_fc1,b_fc1,W_fc2,b_fc2):
    W_conv1 = weight_variable([5, 5, 3, 36])
    b_conv1 = bias_variable([36])

    h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
    
    W_conv2 = weight_variable([5, 5, 36, 72])
    b_conv2 = bias_variable([72])

    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)
    
    W_fc1 = weight_variable([15 * 60 * 72, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 15 * 60 * 72])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    
    keep_prob = 0.5
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    
    W_fc2 = weight_variable([1024, 40])
    b_fc2 = bias_variable([40])
    
    
    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
    return y_conv

上面代表是有问题的
(1) 预测是如果是40个数选一个最大的值,肯定不对,我要分成四组来执行argmax
(2)图像转为灰度图像加快识别速度
(3)

你可能感兴趣的:(深度学习笔记(3)破解验证码)