import os
import tensorflow as tf
from PIL import Image # 注意Image,后面会用到
import matplotlib as plt
cwd = os.getcwd()
cwd = cwd + '\\17flowers\jpg\\'
classes = {'daffodil', 'snowdrop', 'lilyvalley', 'bluebell', 'crocus', 'iris', 'tigerlily', 'tulip', 'fritiuary',
'sunflower', 'daisy', 'coltsfoot', 'dandelion', 'cowslip', 'buttercup', 'windflower',
'pansy'} # 花为 设定 17 类首先开始要设定好文件的类别
#这里是生成。TFRecords文件
writer = tf.python_io.TFRecordWriter("flower_train.tfrecords") # 要生成的文件
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() # 将图片转化为二进制格式
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]))
})) # example对象对label和image数据进行封装
writer.write(example.SerializeToString()) # 序列化为字符串
writer.close()
# 读入flower_train.tfrecords的文件
def read_and_decode(filename):
filename_queue = tf.train.string_input_producer([filename]) # 生成一个queue队列
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取出来
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [224, 224, 3])
label = tf.cast(features['label'], tf.int32)
label = tf.one_hot(label, 17, 1, 0)
return image, label
image, label = read_and_decode('flower_train.tfrecords')
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(10):
example, l = sess.run([image, label]) # 在会话中取出image和label
img = Image.fromarray(example, 'RGB') # 这里Image是之前提到的
plt.imshow(img)
plt.axis('on') # 不显示坐标轴
plt.show()
img.save(cwd + str(i) + '_''Label_' + str(l) + '.jpg') # 存下图片
print(example, l)
coord.request_stop()
coord.join(threads)
有关于tensorflow的.TFRecords 文件怎么样来生成和读取操作
猜你喜欢
转载自blog.csdn.net/weixin_41605937/article/details/82736316
今日推荐
周排行