首先是生成tfrecords格式的数据,具体代码如下:
#coding:utf-8import os import tensorflow as tf from PIL import Imagecwd = os.getcwd() ''' 此处我加载的数据目录如下: bt -- 14018.jpg14019.jpg14020.jpgnbt -- 1_ddd.jpg1_dsdfs.jpg1_dfd.jpg这里的bt nbt 就是类别,也就是代码中的classes '''writer = tf.python_io.TFRecordWriter("train.tfrecords") classes = ['bt','nbt'] for index, name in enumerate(classes):class_path = cwd + '/'+ name +'/' #每一类图片的目录地址for img_name in os.listdir(class_path):img_path = class_path + img_name #每一张图片的路径img = Image.open(img_path)img = img.resize((224,224)) img_raw = img.tobytes() #将图片转化为原生bytesexample = 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]))}))print "write" + ' ' + str(img_path) + "to train.tfrecords."writer.write(example.SerializeToString()) #序列化为字符串 writer.close()
然后读取生成的tfrecords数据,并且将tfrecords里面的数据保存成jpg格式的图片。具体代码如下:
#coding:utf-8 import os import tensorflow as tf from PIL import Image cwd = '/media/project/tfLearnning/dataread/pic/' def read_and_decode(filename):#根据文件名生成一个队列filename_queue = tf.train.string_input_producer([filename])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),})img = tf.decode_raw(features['img_raw'],tf.uint8)img = tf.reshape(img,[224,224,3])#img = tf.cast(img,tf.float32) * (1./255) - 0.5 # 将图片变成tensor#对图片进行归一化操作将【0,255】之间的像素归一化到【-0.5,0.5】,标准化处理可以使得不同的特征具有相同的尺度(Scale)。#这样,在使用梯度下降法学习参数的时候,不同特征对参数的影响程度就一样了label = tf.cast(features['label'], tf.int32) #将标签转化tensorprint imgprint labelreturn img, label#read_and_decode('train.tfrecords') img, label = read_and_decode('train.tfrecords') #print img.shape, label img_batch, label_batch = tf.train.shuffle_batch([img,label],batch_size=10,capacity=2000,min_after_dequeue=1000) #形成一个batch的数据,由于使用shuffle,因此每次取batch的时候#都是随机取的,可以使样本尽可能被充分地训练,保证min_after值小于capacit值 init = tf.global_variables_initializer()with tf.Session() as sess:sess.run(init)# 创建一个协调器,管理线程coord = tf.train.Coordinator()# 启动QueueRunner, 此时文件名队列已经进队threads = tf.train.start_queue_runners(sess=sess, coord=coord)for i in range(10):example, l = sess.run([img, label]) #从对列中一张一张读取图片和标签#example, l = sess.run([img_batch,label_batch])print(example.shape,l)img1=Image.fromarray(example, 'RGB') #将tensor转化成图片格式img1.save(cwd+str(i)+'_'+'Label_'+str(l)+'.jpg')#save image# 通知其他线程关闭 coord.request_stop()# 其他所有线程关闭之后,这一函数才能返回coord.join(threads)