def tfrecord_dataset(): filepath = os.path.dirname(basis_code.get_andclean_image()) #从TFRecord文件创建数据集 files = glob.glob(os.path.join(filepath, "output.tfrecords*")) dataset = tf.data.TFRecordDataset(files) #map()函数表示对数据集中的每一条数据进行调用相应的方法。使用TFRecordDataset读取的是二进制的数据,这里需要通过map()来调用parse对二进制数据进行解析。 dataset = dataset.map(parse) #定义迭代器 iterator = dataset.make_one_shot_iterator() image, pixels, labels = iterator.get_next() with tf.Session() as sess: for i in range(10): print(sess.run([image, pixels, labels]))
def initializable_iterator(): filepath = os.path.dirname(basis_code.get_andclean_image()) files = glob.glob(os.path.join(filepath, "output.tfr*")) #从TFRecord文件创建数据集,具体文件路径是一个placeholder,稍后再提供具体的路径 place_file = tf.placeholder(tf.string) dataset = tf.data.TFRecordDataset(place_file) dataset = dataset.map(parse) #还有其他迭代器,比如reinitializable_iterator和feedable_iterator两种更加灵活的迭代器,前者可以多次initialize用于遍历不同的数据来源,而后者可以用feed_dict的方式动态指定运行哪个iterator.具体使用参考官网API iterator = dataset.make_initializable_iterator() image, pixels, labels = iterator.get_next() with tf.Session() as sess: #首先初始化迭代器,并给出文件路径 sess.run(iterator.initializer, feed_dict={place_file: files}) #遍历所有数据,当遍历结束时,程序会抛出OutOfRangeError。在实际问题中,我们也不太清楚应该遍历几次,所以可以用while循环。 while True: try: print(sess.run([image, pixels, labels])) except tf.errors.OutOfRangeError: break
def text_dataset(): filepath = os.path.dirname(basis_code.get_andclean_image()) #构造文件 for i in range(2): filepaths = os.path.join(filepath, "input_files" + str(i)) file = open(filepaths, "a+") for j in range(5): if i == 1: j = j + 5 file.write(str(j)) file.close() #获取构造的文件路径列表 files = glob.glob(os.path.join(filepath, "input_files*")) #创建数据集 dataset = tf.data.TextLineDataset(files) iterator = dataset.make_one_shot_iterator() x = iterator.get_next() with tf.Session() as sess: for i in range(2): print(sess.run(x)) #删除构造的文件 for file in files: os.remove(file)
image = tf.image.convert_image_dtype(image, tf.float32) #随机截取图像,减少需要关注的物体大小对图像识别算法的影响 bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box( tf.shape(image), bounding_boxes=bbox) distorted_image = tf.slice(image, bbox_begin, bbox_size) #将随机截取的图像调整为神经网络输入层的大小。大小调整算法是随机选择的 distorted_image = tf.image.resize_images(distorted_image, [height, width], method=np.random.randint(4)) #随机上下翻转图像 distorted_image = tf.image.random_flip_up_down(distorted_image) #随机左右翻转图像 distorted_image = tf.image.random_flip_left_right(distorted_image) #随机使用一种顺序调整图片色彩 distorted_image = distort_color(distorted_image, color_ordering=np.random.randint(2)) return distorted_image #通过上面程序,就可以通过一张训练图像衍生出很多训练样本。通过将训练图像预处理,训练得到的神经网络模型可以识别不同大小、方位、色彩等方面的实体 if __name__ == "__main__": filepath = basis_code.get_andclean_image() image = basis_code.basis_decode(filepath) boxes = tf.constant([[[0.13, 0.24, 0.55, 0.89], [0.33, 0.43, 0.48, 0.67]]]) with tf.Session() as sess: #运行6次获得6种不同的图像 for i in range(6): result = preprocess_for_train(image, 180, 267, boxes) basis.drawing(sess.run(result)) basis_code.basis_encode(result, basis_code.get_encode_path(filepath, i))
"img_data": tf.FixedLenFeature([], tf.string), "labels": tf.FixedLenFeature([], tf.int64) }) image = tf.decode_raw(example["img_data"], tf.uint8) labels = tf.cast(example["labels"], tf.int32) with tf.Session() as sess: #虽然在本段程序中没有声明任何变量,但使用tf.train.match_filenames_once函数时需要初始化一些变量 tf.local_variables_initializer().run() Log_Util.getlogger("file names").info(sess.run(files)) #声明tf.train.Coordinator类来协同不同线程,并启动线程 coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) for i in range(6): Log_Util.getlogger("read img data").info(sess.run(image)) Log_Util.getlogger("read labels").info(sess.run(labels)) coord.request_stop() coord.join(threads) print("all thread stop!") if __name__ == "__main__": decode_path = basis_code.get_andclean_image() write_path = os.path.dirname(decode_path) write_tfrecord(decode_path, write_path) read_tfrecord(write_path)
import tensorflow as tf import os from com.tensorflow.exercise.preprocess import image_size as basis_code from com.tensorflow.exercise.preprocess import preprocess_case from com.tensorflow.exercise.mnist.final import mnist_inference ''' 下面这个案例将完成预处理全流程,也就是下面的流程: 指定原始数据的文件列表---->创建文件列表队列---->从文件中读取数据---->数据预处理---->整理成batch作为神经网络输入 ''' if __name__ == "__main__": filepath = os.path.dirname(basis_code.get_andclean_image()) #1.指定原始文件列表 files = tf.train.match_filenames_once( os.path.join(filepath, "data.tfrecords-*")) #2.创建文件列表队列 filename_queue = tf.train.string_input_producer(files) reader = tf.TFRecordReader() #3.从文件中读取数据 _, seriallzed_example = reader.read_up_to(filename_queue, 3) features = tf.parse_example(seriallzed_example, features={ "img_data": tf.FixedLenFeature([], tf.string), "labels": tf.FixedLenFeature([], tf.int64) }) img_data = tf.decode_raw(features["img_data"], tf.uint8) labels = tf.cast(features["labels"], tf.int32) #定义神经网络输入层大小 image_size = 784 #此处必须转换为3维 img_data = tf.reshape(img_data, [3, 10, 3])