TensorFlow笔记(一)制作TFRecord数据集,读取,显示及代码详解

这里写图片描述
在学习TensorFlow的时候,做实验所用到的数据集都是TensorFlow所提供的,这有点不太友好耶,做了那么久的实验,还不知道怎么批处理自己的数据,于是研究了一下TEFecond的用法,总的来说比较简单。


准备数据:这里准备了20张图片用于实验,分别是10张猫,10张狗
这里写图片描述
这里写图片描述


import os
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image  #注意Image,后面会用到

# 获取当前目录
cwd = os.getcwd ()
# 人为设定两类
classes = {'cat', 'dog'}
#要生成的文件名字
writer = tf.python_io.TFRecordWriter ("cat_and_dog.tfrecords")
# 第一个循环是打开猫和狗照片的两个文件夹
for index, name in enumerate (classes):
    class_path = cwd + '\\' +name + '\\'
    # 开始遍历每一张图片
    for image_name in os.listdir(class_path):
        image_path = class_path + image_name
        # 打开每一张图片
        img=Image.open(image_path)
        # 将图片设置为指定的大小,可以不设置,然后在feature中添加图片大小两项
        img= img.resize((300,300))
        #将图片转化为二进制格式
        img_raw=img.tobytes()

        # 下面这句话是核心内容,主要是对label image数据进行封装
        example = tf.train.Example(features=tf.train.Features(feature={
            "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
            'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
        })) 
        #序列化为字符串
        writer.write(example.SerializeToString())  
# 关闭
writer.close()

这时候会在文件夹中生成一个cat_and_dog.tfrecords文件


读取 TFRecond 文件

def read_and_decode(filename): # cat_and_dog.tfrecords
    filename_queue = tf.train.string_input_producer([filename])#生成一个queue队列

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)#返回文件名和文件
    # 核心内容,解析label 和 image 信息,这个名字需要与生成的时候一致
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'label': tf.FixedLenFeature([], tf.int64),
                                           'img_raw' : tf.FixedLenFeature([], tf.string),
                                       })#将image数据和label取出来

    img = tf.decode_raw(features['img_raw'], tf.uint8)
    img = tf.reshape(img, [128, 128, 3])  #reshape为128*128的3通道图片
    img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 #在流中抛出img张量
    label = tf.cast(features['label'], tf.int32) #在流中抛出label张量
    return img, label

下面这一段代码的主要作用是做实验,将TFRecord的图片读出来,并且进行保存

filename_queue = tf.train.string_input_producer(["cat_and_dog.tfrecords"]) #读入流中
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)   #返回文件名和文件
features = tf.parse_single_example(serialized_example,
                                   features={
                                       'label': tf.FixedLenFeature([], tf.int64),
                                       'img_raw' : tf.FixedLenFeature([], tf.string),
                                   })  #取出包含image和label的feature对象
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [300, 300, 3])
label = tf.cast(features['label'], tf.int32)
with tf.Session() as sess: #开始一个会话
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    coord=tf.train.Coordinator()
    threads= tf.train.start_queue_runners(coord=coord)
    for i in range(20):
        example, l = sess.run([image,label])#在会话中取出image和label
        img=Image.fromarray(example, 'RGB')#这里Image是之前提到的
        img.save(cwd+str(i)+'_''Label_'+str(l)+'.jpg')#存下图片
        print(example, l)
    coord.request_stop()
    coord.join(threads)

猜你喜欢

转载自blog.csdn.net/NaLaEur/article/details/81781948
今日推荐