我有一个 TFRecords 文件,其中包含图像及其标签、名称、大小等。我的目标是将标签和图像提取为 numpy 数组。
我执行以下操作来加载文件:
def extract_fn(data_record):
features = {
# Extract features using the keys set during creation
"image/class/label": tf.FixedLenFeature([], tf.int64),
"image/encoded": tf.VarLenFeature(tf.string),
}
sample = tf.parse_single_example(data_record, features)
#sample = tf.cast(sample["image/encoded"], tf.float32)
return sample
filename = "path\train-00-of-10"
dataset = tf.data.TFRecordDataset(filename)
dataset = dataset.map(extract_fn)
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
with tf.Session() as sess:
while True:
data_record = sess.run(next_element)
print(data_record)
图像保存为字符串。我怎样才能将图像转换为float32
?我试过sample = tf.cast(sample["image/encoded"], tf.float32)
这是行不通的。我想data_record
是一个列表,其中包含作为 numpy 数组的图像和作为np.int32
数字。我怎样才能做到这一点?
现在data_record
看起来像这样:
{'image/encoded': SparseTensorValue(indices=array([[0]]), values=array([b'\xff\xd8\ ... 8G\xff\xd9'], dtype=object), dense_shape=array([1])), 'image/class/label': 394}
我不知道如何处理它。我将不胜感激任何帮助
EDIT
如果我打印sample
and sample['image/encoded']
in extract_fn()
我得到以下信息:
print(sample) =
{'image/encoded': <tensorflow.python.framework.sparse_tensor.SparseTensor object at 0x7fe41ec15978>, 'image/class/label': <tf.Tensor 'ParseSingleExample/ParseSingleExample:3' shape=() dtype=int64>}
print(sample['image/encoded'] =
SparseTensor(indices=Tensor("ParseSingleExample/ParseSingleExample:0", shape=(?, 1), dtype=int64), values=Tensor("ParseSingleExample/ParseSingleExample:1", shape=(?,), dtype=string), dense_shape=Tensor("ParseSingleExample/ParseSingleExample:2", shape=(1,), dtype=int64))
看起来图像是一个稀疏张量并且tf.image.decode_image
抛出错误。将图像提取为图像的正确方法是什么tf.float32
tensor?