第一章節介紹了單個字符識別模型的訓練和使用,實際遇到的驗證碼可能存在粘連而沒法完整的切割成單個字符。針對這種驗證碼咱們能夠採用端到端總體識別的方式來解決,對驗證碼不作任何處理,總體輸入模型進行訓練一樣也能夠得到一個理想模型;與單字符模型訓練的差異就是要得到較高識別率模型須要的樣本量較大,以前經驗值大概10000張以上圖片能夠得到一個可用識別模型,樣本越多模型精度越高,且不容易過擬合。python
關於訓練樣本的得到,第一章有介紹,能夠依據實際圖片來選擇合適的方式得到訓練樣本git
本章訓練所用驗證碼以下圖所示: bash
第一章介紹的和本節方法的區別,本節驗證碼識別是總體輸入,總體輸出;一次輸入一次輸出。驗證碼總體輸入模型,模型直接輸出四字符做爲結果,流程以下圖 網絡
第一章介紹的方法,須要對圖片先按照字符個數切分紅單個圖片,切分出來的每一個小圖片在依次輸入模型,模型每次輸出一個字符,最後經過代碼合併成一個總體的過程,流程以下圖所示:app
本節的方法不須要對驗證碼作額外處理,並且識別時只須要調用一次模型便可得到所需輸出,識別時間短。任何事物都有兩面性,有優勢就優缺點,缺點就是訓練模型須要的樣本量比較多,適合訓練樣本獲取容易的驗證碼識別,土豪能夠不用考慮,直接對接打碼平臺獲取訓練樣本便可。dom
四字符訓練須要修改nets文件夾下的模型文件alexnet.py(修改的地方第一章有介紹)函數
模型 code學習
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
slim = tf.contrib.slim
trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev)
def alexnet_v2_arg_scope(weight_decay=0.0005):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=tf.nn.relu,
biases_initializer=tf.constant_initializer(0.1),
weights_regularizer=slim.l2_regularizer(weight_decay)):
with slim.arg_scope([slim.conv2d], padding='SAME'):
with slim.arg_scope([slim.max_pool2d], padding='VALID') as arg_sc:
return arg_sc
def alexnet_v2(inputs,
num_classes=1000,
is_training=True,
dropout_keep_prob=0.5,
spatial_squeeze=True,
scope='alexnet_v2'):
with tf.variable_scope(scope, 'alexnet_v2', [inputs]) as sc:
end_points_collection = sc.name + '_end_points'
# Collect outputs for conv2d, fully_connected and max_pool2d.
with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d],
outputs_collections=[end_points_collection]):
net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID',
scope='conv1')
net = slim.max_pool2d(net, [3, 3], 2, scope='pool1')
net = slim.conv2d(net, 192, [5, 5], scope='conv2')
net = slim.max_pool2d(net, [3, 3], 2, scope='pool2')
net = slim.conv2d(net, 384, [3, 3], scope='conv3')
net = slim.conv2d(net, 384, [3, 3], scope='conv4')
net = slim.conv2d(net, 256, [3, 3], scope='conv5')
net = slim.max_pool2d(net, [3, 3], 2, scope='pool5')
# Use conv2d instead of fully_connected layers.
with slim.arg_scope([slim.conv2d],
weights_initializer=trunc_normal(0.005),
biases_initializer=tf.constant_initializer(0.1)):
net = slim.conv2d(net, 4096, [5, 5], padding='VALID',
scope='fc6')
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout6')
net = slim.conv2d(net, 4096, [1, 1], scope='fc7')
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout7')
net0 = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer(),
scope='fc8_0')
net1 = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer(),
scope='fc8_1')
net2 = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer(),
scope='fc8_2')
net3 = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer(),
scope='fc8_3')
# Convert end_points_collection into a end_point dict.
end_points = slim.utils.convert_collection_to_dict(end_points_collection)
if spatial_squeeze:
net0 = tf.squeeze(net0, [1, 2], name='fc8_0/squeezed')
end_points[sc.name + '/fc8_0'] = net0
net1 = tf.squeeze(net1, [1, 2], name='fc8_1/squeezed')
end_points[sc.name + '/fc8_1'] = net1
net2 = tf.squeeze(net2, [1, 2], name='fc8_2/squeezed')
end_points[sc.name + '/fc8_2'] = net2
net3 = tf.squeeze(net3, [1, 2], name='fc8_3/squeezed')
end_points[sc.name + '/fc8_3'] = net3
return net0,net1,net2,net3,end_points
alexnet_v2.default_image_size = 224
複製代碼
注意和第一章單子符生成代碼的不一樣測試
code:優化
import tensorflow as tf
import os
import random
import math
import sys
from PIL import Image
import numpy as np
#驗證集數量
_NUM_TEST = 500
#隨機種子
_RANDOM_SEED = 0
#驗證碼最大長度
MAX_CAPTCHA = 4
#訓練數據集路徑
DATASET_DIR = './train_data/'
#tfrecord文件存放路徑
TFRECORD_DIR = './TFrecord/'
#判斷tfrecord文件是否存在
def _dataset_exists(dataset_dir):
for split_name in ['train', 'test']:
output_filename = os.path.join(dataset_dir,split_name + '.tfrecords')
if not tf.gfile.Exists(output_filename):
return False
return True
#獲取全部驗證碼圖片
def _get_filenames_and_classes(dataset_dir):
photo_filenames = []
for filename in os.listdir(dataset_dir):
#獲取文件路徑
path = os.path.join(dataset_dir, filename)
photo_filenames.append(path)
return photo_filenames
def int64_feature(values):
if not isinstance(values, (tuple, list)):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=values))
def bytes_feature(values):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values]))
def image_to_tfexample(image_data, label0, label1, label2, label3):
#Abstract base class for protocol messages.
return tf.train.Example(features=tf.train.Features(feature={
'image': bytes_feature(image_data),
'label0': int64_feature(label0),
'label1': int64_feature(label1),
'label2': int64_feature(label2),
'label3': int64_feature(label3),
}))
#字符轉成int
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
def char2pos1(c):
if c=='_':
k=36
return k
k = ord(c)-48
if k>9:
k = ord(c) - 55
if k>35:
k = ord(c) - (61+26)
if k>36:
raise ValueError('No Map')
return k
#把數據轉爲TFRecord格式
def _convert_dataset(split_name, filenames, dataset_dir):
assert split_name in ['train', 'test']
with tf.Session() as sess:
#定義tfrecord文件的路徑+名字
output_filename = os.path.join(TFRECORD_DIR,split_name + '.tfrecords')
with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer:
for i,filename in enumerate(filenames):
try:
sys.stdout.write('\r>> Converting image %d/%d' % (i+1, len(filenames)))
sys.stdout.flush()
#讀取圖片
image_data = Image.open(filename)
#根據模型的結構resize
image_data = image_data.resize((224, 224))
#灰度化
image_data = np.array(image_data.convert('L'))
#將圖片轉化爲bytes
image_data = image_data.tobytes()
#獲取label
labels = filename.split('/')[-1][0:4]
num_labels = []
for j in range(4):
num_labels.append(int(char2pos1(labels[j])))
example = image_to_tfexample(image_data, num_labels[0], num_labels[1], num_labels[2], num_labels[3])
tfrecord_writer.write(example.SerializeToString())
except IOError as e:
print('Could not read:',filename)
print('Error:',e)
print('Skip it\n')
sys.stdout.write('\n')
sys.stdout.flush()
#判斷tfrecord文件是否存在
if _dataset_exists(TFRECORD_DIR):
print('tfcecord文件已存在')
else:
#得到全部圖片
photo_filenames = _get_filenames_and_classes(DATASET_DIR)
#把數據切分爲訓練集和測試集,並打亂
random.seed(_RANDOM_SEED)
random.shuffle(photo_filenames)
training_filenames = photo_filenames[_NUM_TEST:]
testing_filenames = photo_filenames[:_NUM_TEST]
#數據轉換
_convert_dataset('train', training_filenames, DATASET_DIR)
_convert_dataset('test', testing_filenames, DATASET_DIR)
print('生成tfcecord文件')
複製代碼
也是在第一章單字符識別訓練代碼的基礎上增長了三個通道,留意代碼不一樣的地方,就能夠依據本身的字符個數修改代碼實現指定字符個數驗證碼識別模型
訓練code
#coding=GB2312
import os
import tensorflow as tf
from PIL import Image
from nets import nets_factory
import numpy as np
# 不一樣字符數量
CHAR_SET_LEN = 36
# 圖片高度
IMAGE_HEIGHT = 60
# 圖片寬度
IMAGE_WIDTH = 160
# 批次
BATCH_SIZE = 25
# tfrecord文件存放路徑
TFRECORD_FILE = "./TFrecord/train.tfrecords"
# placeholder
x = tf.placeholder(tf.float32, [None, 224, 224])
y0 = tf.placeholder(tf.float32, [None])
y1 = tf.placeholder(tf.float32, [None])
y2 = tf.placeholder(tf.float32, [None])
y3 = tf.placeholder(tf.float32, [None])
# 學習率
lr = tf.Variable(0.003, dtype=tf.float32)
# 從tfrecord讀出數據
def read_and_decode(filename):
# 根據文件名生成一個隊列
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
# 返回文件名和文件
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example,
features={
'image' : tf.FixedLenFeature([], tf.string),
'label0': tf.FixedLenFeature([], tf.int64),
'label1': tf.FixedLenFeature([], tf.int64),
'label2': tf.FixedLenFeature([], tf.int64),
'label3': tf.FixedLenFeature([], tf.int64),
})
# 獲取圖片數據
image = tf.decode_raw(features['image'], tf.uint8)
# tf.train.shuffle_batch必須肯定shape
image = tf.reshape(image, [224, 224])
# 圖片預處理
image = tf.cast(image, tf.float32) / 255.0
image = tf.subtract(image, 0.5)
image = tf.multiply(image, 2.0)
# 獲取label
label0 = tf.cast(features['label0'], tf.int32)
label1 = tf.cast(features['label1'], tf.int32)
label2 = tf.cast(features['label2'], tf.int32)
label3 = tf.cast(features['label3'], tf.int32)
return image, label0, label1, label2, label3
# 獲取圖片數據和標籤
image, label0, label1, label2, label3 = read_and_decode(TFRECORD_FILE)
#使用shuffle_batch能夠隨機打亂
image_batch, label_batch0, label_batch1, label_batch2, label_batch3 = tf.train.shuffle_batch(
[image, label0, label1, label2, label3], batch_size = BATCH_SIZE,
capacity = 50000, min_after_dequeue=10000, num_threads=1)
#定義網絡結構
train_network_fn = nets_factory.get_network_fn(
'alexnet_v2',
num_classes=CHAR_SET_LEN,
weight_decay=0.0005,
is_training=True)
with tf.Session() as sess:
# inputs: a tensor of size [batch_size, height, width, channels]
X = tf.reshape(x, [BATCH_SIZE, 224, 224, 1])
# 數據輸入網絡獲得輸出值
logits0,logits1,logits2,logits3,end_points = train_network_fn(X)
# 把標籤轉成one_hot的形式
one_hot_labels0 = tf.one_hot(indices=tf.cast(y0, tf.int32), depth=CHAR_SET_LEN)
one_hot_labels1 = tf.one_hot(indices=tf.cast(y1, tf.int32), depth=CHAR_SET_LEN)
one_hot_labels2 = tf.one_hot(indices=tf.cast(y2, tf.int32), depth=CHAR_SET_LEN)
one_hot_labels3 = tf.one_hot(indices=tf.cast(y3, tf.int32), depth=CHAR_SET_LEN)
# 計算loss
loss0 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits0,labels=one_hot_labels0))
loss1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits1,labels=one_hot_labels1))
loss2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits2,labels=one_hot_labels2))
loss3 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits3,labels=one_hot_labels3))
# 計算總的loss
total_loss = (loss0+loss1+loss2+loss3)/4.0
# 優化total_loss
optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(total_loss)
# 計算準確率
correct_prediction0 = tf.equal(tf.argmax(one_hot_labels0,1),tf.argmax(logits0,1))
accuracy0 = tf.reduce_mean(tf.cast(correct_prediction0,tf.float32))
correct_prediction1 = tf.equal(tf.argmax(one_hot_labels1,1),tf.argmax(logits1,1))
accuracy1 = tf.reduce_mean(tf.cast(correct_prediction1,tf.float32))
correct_prediction2 = tf.equal(tf.argmax(one_hot_labels2,1),tf.argmax(logits2,1))
accuracy2 = tf.reduce_mean(tf.cast(correct_prediction2,tf.float32))
correct_prediction3 = tf.equal(tf.argmax(one_hot_labels3,1),tf.argmax(logits3,1))
accuracy3 = tf.reduce_mean(tf.cast(correct_prediction3,tf.float32))
# 用於保存模型
saver = tf.train.Saver()
# 初始化
sess.run(tf.global_variables_initializer())
# 建立一個協調器,管理線程
coord = tf.train.Coordinator()
# 啓動QueueRunner, 此時文件名隊列已經進隊
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(40001):
# 獲取一個批次的數據和標籤
b_image, b_label0, b_label1 ,b_label2 ,b_label3 = sess.run([image_batch, label_batch0, label_batch1, label_batch2, label_batch3])
# 優化模型
sess.run(optimizer, feed_dict={x: b_image, y0:b_label0, y1: b_label1, y2: b_label2, y3: b_label3})
# 每迭代20次計算一次loss和準確率
if i % 20 == 0:
# 每迭代2000次下降一次學習率
if i%2000 == 0:
sess.run(tf.assign(lr, lr/3))
acc0,acc1,acc2,acc3,loss_ = sess.run([accuracy0,accuracy1,accuracy2,accuracy3,total_loss],feed_dict={x: b_image,
y0: b_label0,
y1: b_label1,
y2: b_label2,
y3: b_label3})
learning_rate = sess.run(lr)
print ("Iter:%d Loss:%.3f Accuracy:%.2f,%.2f,%.2f,%.2f Learning_rate:%.4f" % (i,loss_,acc0,acc1,acc2,acc3,learning_rate))
# 保存模型
if acc0 > 0.96 and acc1 > 0.96 and acc2 > 0.96 and acc3 > 0.96:
saver.save(sess, "./models/crack_captcha.model", global_step=i)
break
if i==40000:
saver.save(sess, "./models/crack_captcha.model", global_step=i)
break
# 通知其餘線程關閉
coord.request_stop()
# 其餘全部線程關閉以後,這一函數才能返回
coord.join(threads)
複製代碼
測試模型code
import os
import tensorflow as tf
from PIL import Image
from nets import nets_factory
import numpy as np
import matplotlib.pyplot as plt
# 不一樣字符數量
CHAR_SET_LEN = 36
# 圖片高度
IMAGE_HEIGHT = 60
# 圖片寬度
IMAGE_WIDTH = 160
# 批次
BATCH_SIZE = 1
# tfrecord文件存放路徑
TFRECORD_FILE = "./TFrecord/test.tfrecords"
# placeholder
x = tf.placeholder(tf.float32, [None, 224, 224])
# 從tfrecord讀出數據
def read_and_decode(filename):
# 根據文件名生成一個隊列
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
# 返回文件名和文件
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example,
features={
'image' : tf.FixedLenFeature([], tf.string),
'label0': tf.FixedLenFeature([], tf.int64),
'label1': tf.FixedLenFeature([], tf.int64),
'label2': tf.FixedLenFeature([], tf.int64),
'label3': tf.FixedLenFeature([], tf.int64),
})
# 獲取圖片數據
image = tf.decode_raw(features['image'], tf.uint8)
# 沒有通過預處理的灰度圖
image_raw = tf.reshape(image, [224, 224])
# tf.train.shuffle_batch必須肯定shape
image = tf.reshape(image, [224, 224])
# 圖片預處理
image = tf.cast(image, tf.float32) / 255.0
image = tf.subtract(image, 0.5)
image = tf.multiply(image, 2.0)
# 獲取label
label0 = tf.cast(features['label0'], tf.int32)
label1 = tf.cast(features['label1'], tf.int32)
label2 = tf.cast(features['label2'], tf.int32)
label3 = tf.cast(features['label3'], tf.int32)
return image, image_raw, label0, label1, label2, label3
# 獲取圖片數據和標籤
image, image_raw, label0, label1, label2, label3 = read_and_decode(TFRECORD_FILE)
#使用shuffle_batch能夠隨機打亂
image_batch, image_raw_batch, label_batch0, label_batch1, label_batch2, label_batch3 = tf.train.shuffle_batch(
[image, image_raw, label0, label1, label2, label3], batch_size = BATCH_SIZE,
capacity = 50000, min_after_dequeue=10000, num_threads=1)
#定義網絡結構
train_network_fn = nets_factory.get_network_fn(
'alexnet_v2',
num_classes=CHAR_SET_LEN,
weight_decay=0.0005,
is_training=False)
with tf.Session() as sess:
# inputs: a tensor of size [batch_size, height, width, channels]
X = tf.reshape(x, [BATCH_SIZE, 224, 224, 1])
# 數據輸入網絡獲得輸出值
logits0,logits1,logits2,logits3,end_points = train_network_fn(X)
# 預測值
predict0 = tf.reshape(logits0, [-1, CHAR_SET_LEN])
predict0 = tf.argmax(predict0, 1)
predict1 = tf.reshape(logits1, [-1, CHAR_SET_LEN])
predict1 = tf.argmax(predict1, 1)
predict2 = tf.reshape(logits2, [-1, CHAR_SET_LEN])
predict2 = tf.argmax(predict2, 1)
predict3 = tf.reshape(logits3, [-1, CHAR_SET_LEN])
predict3 = tf.argmax(predict3, 1)
# 初始化
sess.run(tf.global_variables_initializer())
# 載入訓練好的模型
saver = tf.train.Saver()
saver.restore(sess,'./models/crack_captcha.model-21560')
# 建立一個協調器,管理線程
coord = tf.train.Coordinator()
# 啓動QueueRunner, 此時文件名隊列已經進隊
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(20):
# 獲取一個批次的數據和標籤
b_image, b_image_raw, b_label0, b_label1 ,b_label2 ,b_label3 = sess.run([image_batch,
image_raw_batch,
label_batch0,
label_batch1,
label_batch2,
label_batch3])
# 顯示圖片
img=Image.fromarray(b_image_raw[0],'L')
plt.imshow(img)
plt.axis('off')
plt.show()
# 打印標籤
print('label:',b_label0, b_label1 ,b_label2 ,b_label3)
# 預測
label0,label1,label2,label3 = sess.run([predict0,predict1,predict2,predict3], feed_dict={x: b_image})
# 打印預測值
print('predict:',label0,label1,label2,label3)
# 通知其餘線程關閉
coord.request_stop()
# 其餘全部線程關閉以後,這一函數才能返回
coord.join(threads)
複製代碼
models文件夾中存放最後訓練好的模型
nets文件中爲模型文件
train_data爲打碼以後的標籤圖片
TFrecord文件存放由TFrecord_Convert.py代碼從train_data中轉換以後的TFrecord格式數據
Tensorflow_train.py爲模型訓練代碼
Tensorflow_test.py爲測試模型用代碼文件
本章所用訓練樣本12000樣本,實際測試在測試集模型識別率90%以上
本章代碼百度網盤地址:連接:pan.baidu.com/s/1yy-gLFN9… 提取碼:iwbm
因爲網速問題數據集和模型文件未上傳,有須要訓練數據集的能夠加QQ:1071830794進行獲取,或者發郵件,我看到郵件會把數據集的TFrecord格式數據以郵件方式發給你們
本章介紹了一種驗證碼總體識別方法,下一章節會寫關於不定長字符驗證碼模型訓練識別方法。
文章中有錯誤和不足地方歡迎你們指正,歡迎你們一塊兒學習和成長