TensorFlow实现中文字体分类(二):数据流

来源:互联网 发布:好用的气垫 知乎 编辑:程序博客网 时间:2024/06/07 18:20

上一篇 《TensorFlow实现中文字体分类(一):预处理》 



读入数据使用TensorFlow最近发布的1.4版本的Dataset API。

先根据目录树结构,来读取图片与标签



#!/usr/bin/env python# -*- coding: utf-8 -*-import sysimport osimport randomimport tensorflow as tffrom tensorflow.python.framework import ops  from tensorflow.python.framework import dtypes  dir_path, _ = os.path.split(os.path.realpath(__file__))def read_labeled_image_list(images_dir):        folders = [folder for _, folder, _ in os.walk(images_dir) if folder][0]        filenames = []    labels = []    for index, folder in enumerate(folders):        label = [0] * len(folders)        image_dir = os.path.join(images_dir, folder)        filename = [os.path.join(image_dir, f) for f in os.listdir(image_dir) if f[0] != '.']        filenames += filename        label[index] = 1.0        labels += [label] * len(filename)             return filenames, labels, folders

这里返回的folders是标签的顺序

接着就是读取功能


def read_data(batch_size):    with tf.name_scope('input_pipeline'):        filenames, labels, annotation = read_labeled_image_list(os.path.join(dir_path, 'images'))                instances = zip(filenames, labels)        random.shuffle(instances)        filenames, labels = zip(*instances)        filenames, labels = list(filenames), list(labels)                dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))        dataset = dataset.map(parse_function)        dataset = dataset.shuffle(100).batch(batch_size).repeat()        return dataset, annotation


dataset.map()类似map()的用法,接收一个函数,作用于每个元素。这里parse_function的作用是读取图片,调整尺寸并标准化(非归一化),代码如下:

def parse_function(filenames, label):    file_contents = tf.read_file(filenames)    example = tf.image.decode_png(file_contents, channels=3)    example = tf.cast(tf.image.resize_images(example, [128, 128]), tf.uint8)     example = tf.image.per_image_standardization(example)    return example, label


下一篇《TensorFlow实现中文字体分类(三):模型-VGG16》

参考资料:

  1. 知乎专栏: TensorFlow全新的数据读取方式:Dataset API入门教程
  2. 网盘:The tf.data API.pdf