将编码的png写入TFRecord

时间:2019-02-15 00:37:20

标签: tensorflow

我有一个图像,形状为HxWx3的numpy数组,我试图将其编码为png并写入tfrecord。我正在使用tf.image.encode_png进行编码,它返回类型为Tensor的{​​{1}}。如何将这个张量转换为string

BytesList

这是我得到的错误

    encoded_image = tf.image.encode_png(img)
example = tf.train.Example(features=tf.train.Features(feature={
    'height': _int64_feature(256),
    'width': _int64_feature(256),
    'image':  tf.train.Feature(bytes_list = tf.train.BytesList(value = [encoded_image])) 
}))

我想我可以写到TypeError: <tf.Tensor 'EncodePng_58:0' shape=() dtype=string> has type Tensor, but expected one of: bytes 文件并进行二进制读取以获取字节,但是我想避免这样做。根据此处的这篇文章Tensorflow: How to encode and read bmp images?,我所做的应该可以,但出现上述错误。

1 个答案:

答案 0 :(得分:0)

您需要在tf.Session()中评估张量。

writer = tf.python_io.TFRecordWriter('test.tfrecords')
with tf.Session() as sess:
    str = sess.run(tf.image.encode_png(img))

example = tf.train.Example(features=tf.train.Features(feature={'image_raw': _bytes_feature(str)}))
writer.write(example.SerializeToString())
writer.close()

您可以在不使用会话的情况下使用numpy.tostring()

str = img.tostring()

,但预期效果会更差。