image_batch, label_batch=read_and_decode()
#一层全连接
#[100,20803] 权重[20803,426]+偏置[104]=[100,104]
y_predict=fc_model(image_batch)
#print(y_predict)#Tensor(“model/add:0”, shape=(100, 104), dtype=float32)
y_true=predict_onehot(label_batch)
loss_new=loss(y_predict,y_true)
train_op=sgd(loss_new)
acc_new=acc(y_predict,y_true)
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("tfrecords_dir", "./tfrecords/captcha.tfrecords", "验证码tfrecords文件")
tf.app.flags.DEFINE_string("captcha_dir", "../data/Genpics/", "验证码图片路径")
tf.app.flags.DEFINE_string("letter", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "验证码字符的种类")
def dealwithlabel(label_str):
# 构建字符索引 {0:'A', 1:'B'......}
num_letter = dict(enumerate(list(FLAGS.letter)))
# 键值对反转 {'A':0, 'B':1......}
letter_num = dict(zip(num_letter.values(), num_letter.keys()))
print(letter_num)
# 构建标签的列表
array = []
# 给标签数据进行处理[[b"NZPP"], ......]
for string in label_str:
letter_list = []# [1,2,3,4]
# 修改编码,b'FVQJ'到字符串,并且循环找到每张验证码的字符对应的数字标记
for letter in string.decode('utf-8'):
letter_list.append(letter_num[letter])
array.append(letter_list)
# [[13, 25, 15, 15], [22, 10, 7, 10], [22, 15, 18, 9], [16, 6, 13, 10], [1, 0, 8, 17], [0, 9, 24, 14].....]
print(array)
# 将array转换成tensor类型
label = tf.constant(array)
return label
def get_captcha_image():
"""
获取验证码图片数据
:param file_list: 路径+文件名列表
:return: image
"""
# 构造文件名
filename = []
for i in range(6000):
string = str(i) + ".jpg"
filename.append(string)
# 构造路径+文件
file_list = [os.path.join(FLAGS.captcha_dir, file) for file in filename]
# 构造文件队列
file_queue = tf.train.string_input_producer(file_list, shuffle=False)
# 构造阅读器
reader = tf.WholeFileReader()
# 读取图片数据内容
key, value = reader.read(file_queue)
# 解码图片数据
image = tf.image.decode_jpeg(value)
image.set_shape([20, 80, 3])
# 批处理数据 [6000, 20, 80, 3]
image_batch = tf.train.batch([image], batch_size=6000, num_threads=1, capacity=6000)
return image_batch
def get_captcha_label():
"""
读取验证码图片标签数据
:return: label
"""
file_queue = tf.train.string_input_producer(["../data/Genpics/labels.csv"], shuffle=False)
reader = tf.TextLineReader()
key, value = reader.read(file_queue)
records = [[1], ["None"]]
number, label = tf.decode_csv(value, record_defaults=records)
# [["NZPP"], ["WKHK"], ["ASDY"]]
label_batch = tf.train.batch([label], batch_size=6000, num_threads=1, capacity=6000)
return label_batch
def write_to_tfrecords(image_batch, label_batch):
"""
将图片内容和标签写入到tfrecords文件当中
:param image_batch: 特征值
:param label_batch: 标签纸
:return: None
"""
# 转换类型
label_batch = tf.cast(label_batch, tf.uint8)
print(label_batch)
# 建立TFRecords 存储器
writer = tf.python_io.TFRecordWriter(FLAGS.tfrecords_dir)
# 循环将每一个图片上的数据构造example协议块,序列化后写入
for i in range(6000):
# 取出第i个图片数据,转换相应类型,图片的特征值要转换成字符串形式
image_string = image_batch[i].eval().tostring()
# 标签值,转换成整型
label_string = label_batch[i].eval().tostring()
# 构造协议块
example = tf.train.Example(features=tf.train.Features(feature={
"image": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_string])),
"label": tf.train.Feature(bytes_list=tf.train.BytesList(value=[label_string]))
}))
writer.write(example.SerializeToString())
# 关闭文件
writer.close()
return None
if __name__ == "__main__":
# 获取验证码文件当中的图片
image_batch = get_captcha_image()
# 获取验证码文件当中的标签数据
label = get_captcha_label()
print(image_batch, label)
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
# [b'NZPP' b'WKHK' b'WPSJ' ..., b'FVQJ' b'BQYA' b'BCHR']
label_str = sess.run(label)
print(label_str)
# 处理字符串标签到数字张量
label_batch = dealwithlabel(label_str)
print(label_batch)
# 将图片数据和内容写入到tfrecords文件当中
write_to_tfrecords(image_batch, label_batch)
coord.request_stop()
coord.join(threads)
import tensorflow as tf
# FLAGS=tf.app.flags.FLAGS
# tf.app.flags.DEFINE_string('captcha_dir','./captcha.tfrecords','验证码数据路径')
def read_and_decode():
"""
读取验证码数据API
:return:
"""
#1构建文件队列
file_queue=tf.train.string_input_producer(['./captcha.tfrecords'])
#2构建阅读器
reader=tf.TFRecordReader()
#3读取内容
key,value=reader.read((file_queue))
#tfrecords格式需要解析
features = tf.parse_single_example(value, features={"image": tf.FixedLenFeature([], tf.string),
"label": tf.FixedLenFeature([], tf.string)})
#解码内容
#1先解析图片的特征值
image=tf.decode_raw(features['image'],tf.uint8)
#解码目标值
label=tf.decode_raw(features['label'],tf.uint8)
# print(image)
# print(label)
#固定形状
image_reshape=tf.reshape(image,[20,80,3])
label_reshape=tf.reshape(label,[4])
# print(image_reshape)
# print(label_reshape)
#Tensor("Reshape:0", shape=(20, 80, 3), dtype=uint8)
#Tensor("Reshape_1:0", shape=(4,), dtype=uint8)
#进行批量处理,每次处理的样本为100(每次训练的样本)
image_batch,label_batch=tf.train.batch([image_reshape,label_reshape],batch_size=100,capacity=100,num_threads=1)
# print(image_batch,label_batch)
return image_batch,label_batch
#定义一个初始化权重的函数
def weight_variables(shape):
w=tf.Variable(tf.random_normal(shape=shape,mean=0.0,stddev=1.0))
return w
#定义一个初始化偏置函数
def bias_variables(shape):
b=tf.Variable(tf.constant(0.0,shape=shape))
return b
def fc_model(image):
"""
进行预测结果
:param image:100图片的特征值
:return:y_predict 预测值[100,4*26]
"""
with tf.variable_scope('model'):
#将图片数据形状转化成二维形状
image_reshape=tf.reshape(image,[-1,20*80*3])
#随机初始化权重和偏置
weights=weight_variables([20*80*3,4*26])
bais=bias_variables([4*26])
#进行全连接层计算 [100,104]
y_predict=tf.matmul(tf.cast(image_reshape,tf.float32),weights)+bais
return y_predict
def predict_onehot(label):
"""
将读取文件目标值转化onehot编码
:param label: [100,4]
:return:
"""
#进行one_hot编码转换,提供给交叉熵损失计算,准确率计算
label_onehot=tf.one_hot(label,depth=26,on_value=1.0,axis=2)
# print(label_onehot)#Tensor("one_hot:0", shape=(100, 4, 26), dtype=float32)
return label_onehot
def loss(y_predict,y_true):
"""
计算交叉熵损失值
:param y_predict:
:param y_true:
:return:
"""
with tf.variable_scope('loss'):
tf.reshape(y_true,[100,4*26])
#求平均交叉熵
loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
labels=tf.reshape(y_true,[100,4*26]),
logits=y_predict, name='softmax'))
return loss
def sgd(loss):
"""
sgd优化 梯度下降优化
:param loss: 损失
:return:
"""
with tf.variable_scope('sgd'):
#学习率
train_op=tf.train.GradientDescentOptimizer(0.01).minimize(loss)
return train_op
def acc(y_predict,y_true):
"""
准确率预测
:param y_predict:
:param y_true:
:return:
"""
with tf.variable_scope('acc'):
#200 104 200 4 26
y_predict_reshape=tf.reshape(y_predict,[100,4,26])
#进行比对
#计算最大值位置
equil_list=tf.equal(tf.arg_max(y_predict_reshape,2),tf.arg_max(y_true,2))
#在行的结果上进行 结果
# res=tf.reduce_all(equil_list,1)
acc=tf.reduce_mean(tf.cast(equil_list,tf.float32))
return acc
def captcharec():
"""
验证码识别程序
:return:
"""
#1 读取验证码的数据文件
image_batch, label_batch=read_and_decode()
#2通过输入图片特征数据,建立模型,得出预测结果
#一层全连接
#[100,20*80*3] *权重[20*80*3,4*26]+偏置[104]=[100,104]
y_predict=fc_model(image_batch)
# print(y_predict)#Tensor("model/add:0", shape=(100, 104), dtype=float32)
#3将目标值转化成onghot编码
y_true=predict_onehot(label_batch)
#4交叉熵损失计算 softmax计算
loss_new=loss(y_predict,y_true)
#5梯度下降优化损失
train_op=sgd(loss_new)
#6求每批次预测的准确率 三维比较
acc_new=acc(y_predict,y_true)
#开启会话训练
#初始化变量op
init_op=tf.global_variables_initializer()
with tf.Session() as ss:
ss.run(init_op)
#创建线程调度器
cd=tf.train.Coordinator()
#开启线程
threads=tf.train.start_queue_runners(sess=ss,coord=cd)
#训练识别程序
for i in range(1000):
ss.run(train_op)
print('第{}批次的准确率为:{}'.format(i,acc_new.eval()))
# 请求结果
cd.request_stop()
# 回收线程
cd.join(threads)
if __name__ == '__main__':
captcharec()