为了清楚起见,我在一个.tfrecords文件中有几千张图像,它们是720 x 720 rgb png文件。标签是0、1、2、3之一。
我也尝试使用parse_example,但无法使其正常工作,但此解决方案可与parse_single_example一起使用。
不利之处在于,现在我必须知道每个.tf记录中有多少个项目,这真是太糟糕了。如果我找到更好的方法,我将更新答案。另外,请注意不要超出.tfrecords文件中记录的数量范围,如果您循环经过最后一条记录,它将从第一条记录开始
诀窍是让队列运行器使用协调器。
我在这里留下了一些代码,以保存正在读取的图像,以便您可以验证图像是否正确。
from PIL import Image
import numpy as np
import tensorflow as tf
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
'image_raw': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64),
'height': tf.FixedLenFeature([], tf.int64),
'width': tf.FixedLenFeature([], tf.int64),
'depth': tf.FixedLenFeature([], tf.int64)
})
image = tf.decode_raw(features['image_raw'], tf.uint8)
label = tf.cast(features['label'], tf.int32)
height = tf.cast(features['height'], tf.int32)
width = tf.cast(features['width'], tf.int32)
depth = tf.cast(features['depth'], tf.int32)
return image, label, height, width, depth
def get_all_records(FILE):
with tf.Session() as sess:
filename_queue = tf.train.string_input_producer([ FILE ])
image, label, height, width, depth = read_and_decode(filename_queue)
image = tf.reshape(image, tf.pack([height, width, 3]))
image.set_shape([720,720,3])
init_op = tf.initialize_all_variables()
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(2053):
example, l = sess.run([image, label])
img = Image.fromarray(example, 'RGB')
img.save( "output/" + str(i) + '-train.png')
print (example,l)
coord.request_stop()
coord.join(threads)
get_all_records('/path/to/train-0.tfrecords')
0
您如何一次从TFRecords中读取所有示例?
我一直在使用
tf.parse_single_example
来读取单个示例,其代码类似于read_and_decode
的示例中的read_and_decode方法中给出的代码。但是,我想一次对整个验证数据集运行网络,因此想全部加载它们。我不确定,但是文档似乎建议我可以使用
tf.parse_example
而不是tf.parse_single_example
一次加载整个TFRecords文件。我似乎无法使它正常工作。我猜想这与我如何指定功能有关,但是我不确定在功能说明中如何声明有多个示例。换句话说,我尝试使用类似于以下内容的内容:
不能正常工作,我认为这是因为这些功能不会一次包含多个示例(但我不确定)。 [这导致
ValueError: Shape () must have rank 1
错误ValueError: Shape () must have rank 1
]这是一次读取所有记录的正确方法吗?如果是这样,我需要更改什么才能实际读取记录?非常感谢!