驗(yàn)證碼生成程序:
from captcha.image import ImageCaptcha # pip install captcha
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import random
# 驗(yàn)證碼中的字符, 就不用漢字了
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']
# 驗(yàn)證碼一般都無視大小寫;驗(yàn)證碼長度4個(gè)字符
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
# 生成字符對應(yīng)的驗(yàn)證碼
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怎么壞了。悟狱。。。
我現(xiàn)在只想破解4位帶數(shù)字的驗(yàn)證碼
生成一萬個(gè)數(shù)字串
labels = [random_captcha_text(number,4) for _ in range(10000)]
生成驗(yàn)證碼(這里有個(gè)缺點(diǎn)就是生成相同驗(yàn)證碼會(huì)覆蓋)
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')
從文件名中提取標(biāo)簽
labels = [filename[:4] for filename in filenames]
把標(biāo)簽轉(zhuǎn)換為向量(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])
讀取圖像數(shù)據(jù)
paths = ['D:/png/'+filename for filename in filenames]
imdatas = [np.array(Image.open(p)) for p in paths]
這里出現(xiàn)了問題,我沒有像上面那樣把樣本都集中起來vstack博其。這里發(fā)現(xiàn)驗(yàn)證碼的維度出現(xiàn)了問題套才,大部分圖像的維度是(60,164,3),但是有少部分圖像是(60,164,3)這里必須要進(jìn)行裁剪慕淡。
測試用的裁剪代碼
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)
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)
'''
拋棄部分節(jié)點(diǎn)
'''
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)#計(jì)算結(jié)果
#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) 預(yù)測是如果是40個(gè)數(shù)選一個(gè)最大的值,肯定不對沸毁,我要分成四組來執(zhí)行argmax
(2)圖像轉(zhuǎn)為灰度圖像加快識別速度
(3)