首先感谢该网址的博主:https://www.cnblogs.com/ydf0509/p/6916435.html,找了很多源码。就这个运行调试成功了。
其次还是要安装好tensorflow-gpu的环境,用GPU来训练,不然速度太慢了,CPU训练4位数字验证码还是太慢了。如何搭建环境tensorflow-gpu已经在前面博文中说了,仔细看即可。
原文的思路如下:
1、使用python自带的captcha库,随机生成训练或者预测所需验证码图片。该模块会被train和test调用。
验证码的字符类型可以设置。以下只使用数字的,大小写字母已经被注释。如果要中文的,还需要另外修改脚本,还可能需要其他的库包。
'''
该模块为自动随机生成验证码,作为训练或者预测集
'''
#coding=utf-8
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']
'''
number=['0','1','2','3','4','5','6','7','8','9']
alphabet =[]
ALPHABET =[]
# 验证码一般都无视大小写;验证码长度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():
while(1):
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.show()
captcha_image = np.array(captcha_image)
if captcha_image.shape==(60,160,3):
break
return captcha_text, captcha_image
if __name__ == '__main__':
# 测试
text, image = gen_captcha_text_and_image()
print (image)
gray = np.mean(image, -1)
print (gray)
print (image.shape)
print (gray.shape)
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()
2、使用train进行训练模型
#coding=utf-8
from gen_captcha import gen_captcha_text_and_image
from gen_captcha import number
from gen_captcha import alphabet
from gen_captcha import ALPHABET
import numpy as np
import tensorflow as tf
"""
text, image = gen_captcha_text_and_image()
print "验证码图像channel:", image.shape # (60, 160, 3)
# 图像大小
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
MAX_CAPTCHA = len(text)
print "验证码文本最长字符数", MAX_CAPTCHA # 验证码最长4字符; 我全部固定为4,可以不固定. 如果验证码长度小于4,用'_'补齐
"""
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
MAX_CAPTCHA = 4
# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用)
def convert2gray(img):
if len(img.shape) > 2:
gray = np.mean(img, -1)
# 上面的转法较快,正规转法如下
# r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
# gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
else:
return img
"""
cnn在图像大小是2的倍数时性能最高, 如果你用的图像大小不是2的倍数,可以在图像边缘补无用像素。
np.pad(image,((2,3),(2,2)), 'constant', constant_values=(255,)) # 在图像上补2行,下补3行,左补2行,右补2行
"""
# 文本转向量
char_set = number + alphabet + ALPHABET + ['_'] # 如果验证码长度小于4, '_'用来补齐
CHAR_SET_LEN = len(char_set)
def text2vec(text):
text_len = len(text)
if text_len > MAX_CAPTCHA:
raise ValueError('验证码最长4个字符')
vector = np.zeros(MAX_CAPTCHA * CHAR_SET_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(text):
#print text
idx = i * CHAR_SET_LEN + char2pos(c)
#print i,CHAR_SET_LEN,char2pos(c),idx
vector[idx] = 1
return vector
#print text2vec('1aZ_')
# 向量转回文本
def vec2text(vec):
char_pos = vec.nonzero()[0]
text = []
for i, c in enumerate(char_pos):
char_at_pos = i # c/63
char_idx = c % CHAR_SET_LEN
if char_idx < 10:
char_code = char_idx + ord('0')
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')
text.append(chr(char_code))
return "".join(text)
"""
#向量(大小MAX_CAPTCHA*CHAR_SET_LEN)用0,1编码 每63个编码一个字符,这样顺利有,字符也有
vec = text2vec("F5Sd")
text = vec2text(vec)
print(text) # F5Sd
vec = text2vec("SFd5")
text = vec2text(vec)
print(text) # SFd5
"""
# 生成一个训练batch
def get_next_batch(batch_size=128):
batch_x = np.zeros([batch_size, IMAGE_HEIGHT * IMAGE_WIDTH])
batch_y = np.zeros([batch_size, MAX_CAPTCHA * CHAR_SET_LEN])
# 有时生成图像大小不是(60, 160, 3)
def wrap_gen_captcha_text_and_image():
while True:
text, image = gen_captcha_text_and_image()
if image.shape == (60, 160, 3):
return text, image
for i in range(batch_size):
text, image = wrap_gen_captcha_text_and_image()
image = convert2gray(image)
batch_x[i, :] = image.flatten() / 255 # (image.flatten()-128)/128 mean为0
batch_y[i, :] = text2vec(text)
return batch_x, batch_y
####################################################################
X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT * IMAGE_WIDTH])
Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA * CHAR_SET_LEN])
keep_prob = tf.placeholder(tf.float32) # dropout
# 定义CNN
def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1):
x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])
# w_c1_alpha = np.sqrt(2.0/(IMAGE_HEIGHT*IMAGE_WIDTH)) #
# w_c2_alpha = np.sqrt(2.0/(3*3*32))
# w_c3_alpha = np.sqrt(2.0/(3*3*64))
# w_d1_alpha = np.sqrt(2.0/(8*32*64))
# out_alpha = np.sqrt(2.0/1024)
# 3 conv layer
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)
# Fully connected layer
w_d = tf.Variable(w_alpha * tf.random_normal([8 * 32 * 40, 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_SET_LEN]))
b_out = tf.Variable(b_alpha * tf.random_normal([MAX_CAPTCHA * CHAR_SET_LEN]))
out = tf.add(tf.matmul(dense, w_out), b_out)
# out = tf.nn.softmax(out)
return out
# 训练
def train_crack_captcha_cnn():
import time
start_time=time.time()
output = crack_captcha_cnn()
# loss
#loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(output, Y))
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y))
# 最后一层用来分类的softmax和sigmoid有什么不同?
# optimizer 为了加快训练 learning_rate应该开始大,然后慢慢衰
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])
max_idx_p = tf.argmax(predict, 2)
max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_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) #64是一次训练的样本数,可以更改
_, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})
#输出当前时间,训练轮次,损失值
#print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),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 (u'***************************************************************第%s次的准确率为%s'%(step, acc))
# 如果准确率大于50%,保存模型,完成训练
if acc > 0.97: ##我这里设了0.9,设得越大训练要花的时间越长,如果设得过于接近1,很难达到。如果使用cpu,花的时间很长,cpu占用很高电脑发烫。
saver.save(sess, "crack_capcha.model", global_step=step)
print (time.time()-start_time)
break
step += 1
if __name__ == "__main__":
train_crack_captcha_cnn()
3、使用test进行预测
from train import crack_captcha_cnn
from train import convert2gray
from train import vec2text
from train import X
from train import keep_prob
from gen_captcha import gen_captcha_text_and_image
from gen_captcha2 import gen_captcha_text_and_image_local
from gen_captcha import number
from gen_captcha import alphabet
from gen_captcha import ALPHABET
import tensorflow as tf
import numpy as np
import time
MAX_CAPTCHA = 4
# 文本转向量
char_set = number + alphabet + ALPHABET + ['_'] # 如果验证码长度小于4, '_'用来补齐
CHAR_SET_LEN = len(char_set)
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
output = crack_captcha_cnn()
saver = tf.train.Saver()
sess = tf.Session()
saver.restore(sess, tf.train.latest_checkpoint('.'))
predict_sum = 0 #记录总的预测数
predict_true = 0 #记录预测正确数
while(1):
#text, image = gen_captcha_text_and_image()
text, image = gen_captcha_text_and_image_local()
image = convert2gray(image)
image = image.flatten() / 255
predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
text_list = sess.run(predict, feed_dict={X: [image], keep_prob: 1})
predict_text = text_list[0].tolist()
vector = np.zeros(MAX_CAPTCHA * CHAR_SET_LEN)
i = 0
for t in predict_text:
vector[i * CHAR_SET_LEN + t] = 1
i += 1
# break
predict_sum += 1
if text[0:4] == vec2text(vector): #如果正确值=预测值
predict_true += 1
if predict_sum % 100 == 0:
print("总数: {} 正确: {} 目前正确率:{}".format(predict_sum, predict_true, predict_true/predict_sum))
time.sleep(5)
自己修改后的程序:
以上代码使用随机生成的验证码进行训练和预测,但是有两个明显的问题:
1、无法从本地读取验证码进行训练和预测
2、训练时,验证集和训练集都是随机生成的,当然当验证码库够大时,验证集和训练集重复概率很小;但万一两者如果有重复,就容易过拟合,为了避免这种情况,需要将训练集和验证集分离。
3、为了使用本地的验证码进行训练和预测,我重新修改了上述代码。
(1)在代码目录下构建了3个新目录:train, valide,test;train目录存放训练集,valide存放验证集,test存放预测集,三者的验证码尽量不能重复。valide大约为train的10%左右。
(2)新编写了gen_captcha_local.py模块:该模块可以从指定目录dir_path,随机获取图片。返回图片名(验证码),和图片数组;
'''
该模块可以从指定目录dir_path,随机获取图片。返回图片名(验证码),和图片数组
'''
#coding=utf-8
from captcha.image import ImageCaptcha # pip install captcha
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import random
import os
# 从本地test/train/valide目录随机读取字符对应的验证码:返回验证码数值和图片对象
def gen_captcha_text_and_image_local(dir_path):
image_name = os.listdir(dir_path)
#print('所有图片:',image_name)
index = random.randint(0,len(image_name)-1)
#print('选中的index:',index)
captcha_text = image_name[index]
#print('选中的验证码',captcha_text)
#image.write(captcha_text, captcha_text + '.jpg') # 写到文件
captcha_image = Image.open(dir_path + captcha_text)
#captcha_image.show()
captcha_image = np.array(captcha_image)
return captcha_text[:4], captcha_image #考虑有的验证码字符相同而使用后缀区分,因此截取前4位即可
if __name__ == '__main__':
captcha_text, captcha_image = gen_captcha_text_and_image_local()
print(captcha_text,captcha_image)
(3)train_model.py模块就是原来的train模块,但是将其中获取训练集和验证集的目录进行了参数化,通过调用gen_captcha_local模块中的方法,随机获取对应集合。
#coding=utf-8
#from gen_captcha import gen_captcha_text_and_image
from gen_captcha_local import gen_captcha_text_and_image_local
from gen_captcha import number
from gen_captcha import alphabet
from gen_captcha import ALPHABET
import numpy as np
import tensorflow as tf
"""
text, image = gen_captcha_text_and_image()
print "验证码图像channel:", image.shape # (60, 160, 3)
# 图像大小
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
MAX_CAPTCHA = len(text)
print "验证码文本最长字符数", MAX_CAPTCHA # 验证码最长4字符; 我全部固定为4,可以不固定. 如果验证码长度小于4,用'_'补齐
"""
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
MAX_CAPTCHA = 4
# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用)
def convert2gray(img):
if len(img.shape) > 2:
gray = np.mean(img, -1)
# 上面的转法较快,正规转法如下
# r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
# gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
else:
return img
"""
cnn在图像大小是2的倍数时性能最高, 如果你用的图像大小不是2的倍数,可以在图像边缘补无用像素。
np.pad(image,((2,3),(2,2)), 'constant', constant_values=(255,)) # 在图像上补2行,下补3行,左补2行,右补2行
"""
# 文本转向量
char_set = number + alphabet + ALPHABET + ['_'] # 如果验证码长度小于4, '_'用来补齐
CHAR_SET_LEN = len(char_set)
def text2vec(text):
text_len = len(text)
if text_len > MAX_CAPTCHA:
raise ValueError('验证码最长4个字符')
vector = np.zeros(MAX_CAPTCHA * CHAR_SET_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(text):
#print text
idx = i * CHAR_SET_LEN + char2pos(c)
#print i,CHAR_SET_LEN,char2pos(c),idx
vector[idx] = 1
return vector
#print text2vec('1aZ_')
# 向量转回文本
def vec2text(vec):
char_pos = vec.nonzero()[0]
text = []
for i, c in enumerate(char_pos):
char_at_pos = i # c/63
char_idx = c % CHAR_SET_LEN
if char_idx < 10:
char_code = char_idx + ord('0')
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')
text.append(chr(char_code))
return "".join(text)
"""
#向量(大小MAX_CAPTCHA*CHAR_SET_LEN)用0,1编码 每63个编码一个字符,这样顺利有,字符也有
vec = text2vec("F5Sd")
text = vec2text(vec)
print(text) # F5Sd
vec = text2vec("SFd5")
text = vec2text(vec)
print(text) # SFd5
"""
# 生成一个训练batch
def get_next_batch(dir_path, batch_size=128):
batch_x = np.zeros([batch_size, IMAGE_HEIGHT * IMAGE_WIDTH])
batch_y = np.zeros([batch_size, MAX_CAPTCHA * CHAR_SET_LEN])
# 有时生成图像大小不是(60, 160, 3)
def wrap_gen_captcha_text_and_image():
while True:
#选择获取验证码的函数:随机或者本地
#text, image = gen_captcha_text_and_image()
text, image = gen_captcha_text_and_image_local(dir_path)
if image.shape == (60, 160, 3):
return text, image
for i in range(batch_size):
text, image = wrap_gen_captcha_text_and_image()
image = convert2gray(image)
batch_x[i, :] = image.flatten() / 255 # (image.flatten()-128)/128 mean为0
batch_y[i, :] = text2vec(text)
return batch_x, batch_y
####################################################################
X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT * IMAGE_WIDTH])
Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA * CHAR_SET_LEN])
keep_prob = tf.placeholder(tf.float32) # dropout
# 定义CNN
def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1):
x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])
# w_c1_alpha = np.sqrt(2.0/(IMAGE_HEIGHT*IMAGE_WIDTH)) #
# w_c2_alpha = np.sqrt(2.0/(3*3*32))
# w_c3_alpha = np.sqrt(2.0/(3*3*64))
# w_d1_alpha = np.sqrt(2.0/(8*32*64))
# out_alpha = np.sqrt(2.0/1024)
# 3 conv layer
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)
# Fully connected layer
w_d = tf.Variable(w_alpha * tf.random_normal([8 * 32 * 40, 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_SET_LEN]))
b_out = tf.Variable(b_alpha * tf.random_normal([MAX_CAPTCHA * CHAR_SET_LEN]))
out = tf.add(tf.matmul(dense, w_out), b_out)
# out = tf.nn.softmax(out)
return out
# 训练
def train_crack_captcha_cnn():
import time
start_time=time.time()
output = crack_captcha_cnn()
# loss
#loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(output, Y))
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y))
# 最后一层用来分类的softmax和sigmoid有什么不同?
# optimizer 为了加快训练 learning_rate应该开始大,然后慢慢衰
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])
max_idx_p = tf.argmax(predict, 2)
max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_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('./train/', 64) #从训练集目录读取;64是一次训练的样本数,可以更改
_, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})
#输出当前时间,训练轮次,损失值
#print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),step, loss_)
# 每100 step计算一次准确率
if step % 100 == 0:
batch_x_test, batch_y_test = get_next_batch('./valide/', 50)#从验证集目录读取50张用于验证
acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})
print (u'***************************************************************第%s次的准确率为%s'%(step, acc))
# 如果准确率大于50%,保存模型,完成训练
if acc > 0.95: ##我这里设了0.9,设得越大训练要花的时间越长,如果设得过于接近1,很难达到。如果使用cpu,花的时间很长,cpu占用很高电脑发烫。
saver.save(sess, "crack_capcha.model", global_step=step)
print (time.time()-start_time)
break
step += 1
if __name__ == "__main__":
train_crack_captcha_cnn()
(4)test2.py模块是测试模块。该模块从test目录随机读取图片,使用当前目录下的模型进行预测,输出正确结果,每100次输出一次总的正确率
from train_model import crack_captcha_cnn
from train_model import convert2gray
from train_model import vec2text
from train_model import X
from train_model import keep_prob
from gen_captcha import gen_captcha_text_and_image
from gen_captcha_local import gen_captcha_text_and_image_local
from gen_captcha import number
from gen_captcha import alphabet
from gen_captcha import ALPHABET
import tensorflow as tf
import numpy as np
import time
#该模块从test目录随机读取图片,使用当前目录下的模型进行预测,输出正确结果,每100次输出一次总的正确率
MAX_CAPTCHA = 4
# 文本转向量
char_set = number + alphabet + ALPHABET + ['_'] # 如果验证码长度小于4, '_'用来补齐
CHAR_SET_LEN = len(char_set)
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
output = crack_captcha_cnn()
saver = tf.train.Saver()
sess = tf.Session()
saver.restore(sess, tf.train.latest_checkpoint('.'))
predict_sum = 0 #记录总的预测数
predict_true = 0 #记录预测正确数
dir_path = "./test/" #预测集路径
while(predict_sum < 1000): #随机预测1000次
#text, image = gen_captcha_text_and_image()
text, image = gen_captcha_text_and_image_local(dir_path)
image = convert2gray(image)
image = image.flatten() / 255
predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
text_list = sess.run(predict, feed_dict={X: [image], keep_prob: 1})
predict_text = text_list[0].tolist()
vector = np.zeros(MAX_CAPTCHA * CHAR_SET_LEN)
i = 0
for t in predict_text:
vector[i * CHAR_SET_LEN + t] = 1
i += 1
# break
print("正确值: {} 预测值:{}".format(text, vec2text(vector)))
time.sleep(0.25)
predict_sum += 1
if text == vec2text(vector): #如果正确值=预测值
predict_true += 1
if predict_sum % 100 == 0:
print("总数: {} 正确: {} 目前正确率:{}".format(predict_sum, predict_true, predict_true/predict_sum))
time.sleep(5)
(5)上述模块还是会用到gen_captcha.py模块中的一些变量。
具体实施步骤:
1、批量抓取4位数字验证码(我抓取了2000多张手机银行的验证码)
主要思路在移动端测试验证码识别思路——使用Tesseract-OCR识别一文中。核心思路就是使用appium对手机进行自动化测试,但是到验证码界面截图保存。
主要代码:mobileDriver是手机连接对象
#从截屏中截取验证码
def get_captcha_pics(mobileDriver, captcha_sum):
captcha_image = mobileDriver.find_element_by_id('captcha-image')
location = captcha_image.location
size = captcha_image.size
box = (location["x"], location["y"], location["x"] + size["width"], location["y"] + size["height"])
#要截取几张,就range的N
for i in range(captcha_sum):
print ('获取第' + str(i) + '张')
#screen_path = os.getcwd() + '\\train_pic\\screen_tmp' + str(i) + '.png'
captcha_path = os.getcwd() + '\\down_pic\\captcha_tmp' + str(i) + '.png'
mobileDriver.get_screenshot_as_file(captcha_path)
image = Image.open(captcha_path)
newImage = image.crop(box) #传入图片的坐标元组,进行截图
newImage.save(captcha_path) #默认截图为png格式,即RGBA格式,需转换成RGB
captcha_image.click() #点击切换图片
time.sleep(2)
2、人工标注(3.23我标注了1000多张)
3、将验证码转化为160*60分辨率,jpg格式。过程很简单。因为train_model中图片的分辨率是160*60的。对于数字、字母组成的验证码图片,都只需要分辨率和格式转化即可进行训练。
from PIL import Image
import os
in_path = './in/'
out_path = './out/'
x_s = 160
y_s = 60
image_list = os.listdir(in_path)
for image in image_list:
im = Image.open(in_path+ image)
out = im.resize((x_s,y_s),Image.ANTIALIAS) #resize image with high-quality
out.convert("RGB").save(out_path + image[:-4] + '.jpg')
4、900张放入train目录,100张放入valide目录,其他还有200多张放入test目录
训练和预测效果:
1、开始我没有注意到训练集合验证集之间有重复的问题,直接使用1000张验证码进行训练和验证(使用了未修改过的程序进行训练),这样生成的模型预测效果只有62%左右。具体如下:
.1.每轮32张 验证集50 预测集为150张 正确率为63%
.2.每轮64张 验证集50 预测集为150张 正确率为63%(使用60张预测集时,为67%)
2、后来我使用自己修改过的程序。每轮64张 验证集50 预测集为从60和210张中随机读取 每100次的正确率约为83%左右!(这就意味着通过把训练集和验证集分离进行训练,对预测效果提升十分明显)
3、训练时,开始正确率很低,但是一般会从某个轮次开始突然收敛。
4、接下来计划:进一步增加训练集到1500和2000,留取10%验证,比如1350训练,150验证。预计可以达到90%以上
附录:
运行预测时会报警告错误:
calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
使用keep_prob调用dropout(从tensorflow.python.op .nn_ops)是不赞成的,将在将来的版本中删除。今后如果因版本问题出错,无法运行的,再注意一下。此次运行预测时所包含的库包版本库:
absl-py (0.7.0)
Appium-Python-Client (0.34)
astor (0.7.1)
attrs (17.4.0)
captcha (0.3)
colorama (0.3.9)
cycler (0.10.0)
gast (0.2.2)
grpcio (1.19.0)
h5py (2.9.0)
Keras (2.2.4)
Keras-Applications (1.0.7)
Keras-Preprocessing (1.0.9)
kiwisolver (1.0.1)
Markdown (3.0.1)
matplotlib (3.0.3)
mock (2.0.0)
numpy (1.16.2)
opencv-python (4.0.0.21)
pbr (5.1.3)
pdfminer3k (1.3.1)
Pillow (5.4.1)
pip (9.0.1)
pluggy (0.6.0)
ply (3.10)
protobuf (3.7.0)
py (1.5.2)
pygame (1.9.3)
pyparsing (2.3.1)
pytesseract (0.2.6)
pytest (3.3.2)
python-dateutil (2.8.0)
PyYAML (3.13)
scipy (1.2.1)
selenium (3.141.0)
setuptools (28.8.0)
six (1.11.0)
tensorboard (1.13.1)
tensorflow (1.13.1)
tensorflow-estimator (1.13.0)
termcolor (1.1.0)
urllib3 (1.24.1)
Werkzeug (0.14.1)
wheel (0.33.1)