深度学习-验证码识别

环境

1.Win10 64位

2.Python 3.5.6

3.Anaconda

  1. Tensorflow-Gpu 1.10.0

PS:Python 库如下图 (pip list查看此电脑已安装的库)
"Python 库"

基本配置

1.分别新建trainImage(放置训练样本)、model(存放模型)、captcha_image(识别样本)

2.安装captcha 利用captcha生成样本集

captcha安装命令:pip install captcha

ps:captcha安装可能需要翻墙 如缺少其他依赖 pip install ‘库名’ 可按照上面图安装

生成验证码样本集

如果用手动标记会很累,So,用captcha自动生成样本集 编写input_data.py

input_data.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from captcha.image import ImageCaptcha
import numpy as np
from PIL import Image
import random
import cv2
import os

# 验证码中的字符
#number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

alphabet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9','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','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=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)

captcha_image = Image.open(captcha)
captcha_image = np.array(captcha_image)
return captcha_text, captcha_image


if __name__ == '__main__':
#保存路径
path = 'trainImage'
# path = './validImage'
for i in range(10000):
text, image = gen_captcha_text_and_image()
fullPath = os.path.join(path, text + ".jpg")
cv2.imwrite(fullPath, image)
print ("{0}/10000".format(i))
print ("/完成!")

可以在trainImage文件夹看到已经生成了1W张样本了
"样本集"

训练验证集

利用tensorflow进行样本集的训练。最好使用GPU版本的tensorflow 博主刚开始用的CPU跑的,发现CPU太慢了!!! 编辑train.py

train.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import numpy as np
import tensorflow as tf
import cv2
import os
import random
import time

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

alphabet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9','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','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']

data_dir = 'captcha_image'



width = 160
height = 60
max_captcha = 4
batch_size = 150
num_numbers = len(alphabet)

def get_train_data(data_dir = data_dir):
simples = {}
for file_name in os.listdir(data_dir):
captcha = file_name.split('.')[0]
simples[data_dir + '/' + file_name] = captcha
return simples

simples = get_train_data(data_dir)
file_simples = list(simples.keys())
num_simples = len(simples)

def get_next_batch():
batch_x = np.zeros([batch_size, width * height])
batch_y = np.zeros([batch_size, num_numbers * max_captcha])

for i in range(batch_size):
file_name = file_simples[random.randint(0, num_simples - 1)]
batch_x[i, :] = np.float32(cv2.imread(file_name, 0)).flatten() / 255
batch_y[i, :] = text2vec(simples[file_name])
return batch_x, batch_y

def text2vec(text):
return [0 if ord(i) - 48 != j else 1 for i in text for j in range(num_numbers)]
####################################################################

x = tf.placeholder(tf.float32, [None, width * height], name = 'input')
y_ = tf.placeholder(tf.float32, [None, num_numbers * max_captcha])
x_image = tf.reshape(x, [-1, height, width, 1])

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 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')

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)

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)

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)

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)

W_fc2 = weight_variable([1024, num_numbers * max_captcha])
b_fc2 = bias_variable([num_numbers * max_captcha])
output = tf.add(tf.matmul(h_fc1, W_fc2), b_fc2)

cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels = y_, logits = output))
train_step = tf.train.AdamOptimizer(learning_rate = 1e-4).minimize(cross_entropy)

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))

def train():
sess = tf.InteractiveSession()
saver = tf.train.Saver(max_to_keep=1)
tf.global_variables_initializer().run()
for i in range(50000000):
batch_x, batch_y = get_next_batch()
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict = {x: batch_x, y_: batch_y})
print("迭代 %d, 精度 %g " % (i, train_accuracy))
#if train_accuracy > 0.60:
saver.save(sess, "model/output.model", global_step = i+1)
train_step.run(feed_dict = {x: batch_x, y_: batch_y})

train()

PS:如需要训练纯数字的四位验证码 把

num_numbers = len(alphabet)

改为

num_numbers = len(number)

"开始训练"

开始测试

训练的时候特别慢需要一段时间,如果用台式 有条件的话可以用4个2080跑(博主是笔记本无法外界显卡坞,穷的一逼别说2080了,1080都买不起)编辑test.py

test.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import numpy as np
import tensorflow as tf
import cv2
import os
import random
import time

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

alphabet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9','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','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']

data_dir = 'captcha_image'

width = 160
height = 60
max_captcha = 4
batch_size = 64
num_numbers = len(alphabet)

def get_train_data(data_dir = data_dir):
simples = {}
for file_name in os.listdir(data_dir):
captcha = file_name.split('.')[0]
simples[data_dir + '/' + file_name] = captcha
return simples

simples = get_train_data(data_dir)
file_simples = list(simples.keys())
num_simples = len(simples)

def test(input_, label_):
saver = tf.train.import_meta_graph('model/output.model-98501.meta')
graph = tf.get_default_graph()
inputs = graph.get_tensor_by_name('input:0')
predict_max_idx = graph.get_tensor_by_name('predict_max_idx:0')
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('model'))
predict = sess.run(predict_max_idx, feed_dict = {inputs:[input_]})
print(predict[0], label_, predict[0] == label_)

for i in range(num_simples):
input_ = np.float32(cv2.imread(file_simples[i], 0)).flatten() / 255
label_ = [ord(captcha) - 48 for captcha in simples[file_simples[i]]]
test(input_, label_)
print(file_simples[i])

调用model里位模型文件进行识别

PS:因为在训练的时候我用的覆盖式的训练方法 所以把

saver = tf.train.import_meta_graph(‘model/output.model-98501.meta’)

里面的模型文件名改为最后你训练完成的那个名称。

此文章只适合初学新手(像我这样的),大牛勿喷!

0%