1. 程式人生 > >驗證碼識別1---My way of AI 23

驗證碼識別1---My way of AI 23

寫一個練手的驗證碼識別專案

資料集和完整程式碼我會傳到我的下載資源

這篇文章是專案第一步,建立tfrecords檔案

# 程式碼邏輯

1.讀取圖片檔案
2.讀取csv檔案
3.處理一下讀取好的csv檔案到數字張量
4.寫入tfrecords檔案

1.讀取圖片檔案

1.建立檔案佇列
2.構造閱讀器取讀取檔案內容
3.選擇相應的檔案解碼器取decode
4.要根據驗證碼的尺寸取setshape,因為讀取過來的是一起讀過來的
5.批處理資料

def get_image():
    """
    獲取驗證碼圖片內容
    :return: 批處理
    """
file_name = os.listdir("./yz/train10000") # 構造路徑加檔名 file_list = [os.path.join(FLAGS.captcha_dir, file) for file in file_name] # 構造檔案佇列 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([180, 60, 3]) # 批處理資料 image_batch = tf.train.batch([image], batch_size=10318, num_threads=1, capacity=10318) return image_batch

2.得到csv檔案

這裡要先說明一下資料集的樣式,他是jegp格式的,每個圖片的檔名就是驗證碼的內容。所以我先讀取了檔名建立了一個csv檔案,在來讀csv

建立csv檔案
import os
import tensorflow as tf

# def get_name():
#     """
#     得到訓練集真實資料的函式
#     :return: a
#     """
print(os.listdir("./genpics/train/"))

a=list()
file_list=os.listdir("./yz/train10000")
with open("./data2.csv","w") as f:
    for i in range(len(file_list)):
       f.write(file_list[i][0:4]+"\n")# a.append()

# print(a)
讀取csv

1.建立檔案佇列
2.建立檔案閱讀器
3.讀檔案
4.解碼decode,注意格式
5.批處理

def get_label():
    """
    獲取驗證碼檔案的標籤資料,其實也就是獲取真實值
    :return: 真實值
    """
    file_queue = tf.train.string_input_producer(["./data2.csv"], shuffle=False)

    reader = tf.TextLineReader()

    key, value = reader.read(file_queue)

    records = [[1], ["None"]]

    key, label = tf.decode_csv(value, record_defaults=records)

    label_batch = tf.train.batch([label], batch_size=10318, num_threads=1, capacity=10318)
    return label_batch

3.處理字串標籤張量

剛才讀取的csv檔案其實就是真實值,但是還是字串,怎麼能去比較呢,所以我們要把他處理成數字的型別,於是乎我們就要建立字典去把他們一一對應起來。

1.建立字元索引
2.鍵值反轉
3.構建標籤列表
4.對標籤列表進行處理

def deal_label(label_str):
    """
    處理字串標籤張量
    """
    # 構建字元索引
    num_letter = dict(enumerate(list(FLAGS.letter)))

    # 鍵值反轉
    letter_num = dict(zip(num_letter.values(), num_letter.keys()))

    # 構建標籤列表
    array = []

    # 對標籤資料進行處理
    for string in label_str:
        letter_list = []

        # 修改編碼方式為”utf-8“,並迴圈找到每張驗證碼字元對應的數字標記
        for letter in string.decode('utf-8'):
            letter_list.append(letter_num[letter])

        array.append(letter_list)

    # 將array轉換成tensor型別
    label = tf.constant(array)

    return label

4.寫tfrecoreds檔案

把處理好的標籤和image存到tfrecords檔案
1.把標籤轉換成tf.uint8型別
2.建立tfrecords儲存器
3.建立一個協議塊,規定格式,注意這裡的寫法
4.寫入,關閉檔案。當然這裡用with更好


def write_to_tfrecords(image_batch, label_batch):
    """
    將圖片內容和標籤寫入tfrecords檔案
    """
    # 轉換型別
    label_batch = tf.cast(label_batch, tf.uint8)

    # 建立tfrecords儲存器
    writer = tf.python_io.TFRecordWriter(FLAGS.tfrecords_dir)

    # 迴圈將圖片上每一個example協議快,序列化後寫入
    for i in range(5000):
        image_string = image_batch[i].eval().tostring()

        label_string = label_batch[i].eval().tostring

        example = tf.train.Example(feature=tf.train.Feature(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

main函式

def main():
    # 獲取當前的圖片檔案
    image_bacth = get_image()

    # 獲取驗證碼檔案中標籤資料
    label_batch = get_label()

    print(image_bacth, label_batch)

    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)

        label_str = sess.run(label_batch)

        # 處理字串標籤到數字張量
        babel = deal_label(label_str)

        # 寫入到tfrecords檔案中
        write_to_tfrecords(image_bacth, label_batch)

        coord.request_stop()

        coord.join(threads)

author:[email protected] 歡迎交流