如何将.png文件转换为TFrecord张量流格式?

问题描述

我有.png格式的图像和.csv格式的标签。我想将它们转换为tfrecords格式。我对tensorflow非常陌生。如果有人可以将我指向所有我需要知道的事情以及如何做到这一点。很好。

我在网上搜寻。但是有些过时或有些非常先进。

编辑:我的图像存储在一个目录中。

谢谢

解决方法

您必须将图像转换为tf.train.Example才能将其写为tfrecord文件。 这是一个简单的示例。

看看csv文件:

this

代码:

# The following functions can be used to convert a value to a type compatible
# with tf.train.Example.

def _bytes_feature(value):
    """Returns a bytes_list from a string / byte."""
    if isinstance(value,type(tf.constant(0))):
        value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _float_feature(value):
    """Returns a float_list from a float / double."""
    return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))

def _int64_feature(value):
    """Returns an int64_list from a bool / enum / int / uint."""
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))


def image_example(image_string,label):
    image_shape = tf.image.decode_png(image_string).shape
    feature = {
      'height': _int64_feature(image_shape[0]),'width': _int64_feature(image_shape[1]),'depth': _int64_feature(image_shape[2]),'label': _int64_feature(label),'image_raw': _bytes_feature(image_string),}
    return tf.train.Example(features=tf.train.Features(feature=feature))

image_example函数返回单个图像的tf.train.Example对象。

您必须遍历数据框以创建每个图像的tf.train.Example对象,然后使用tf.io.TFRecordWriter写入对象。

代码:

record_file = 'images.tfrecords'
image_labels = {
    'cat': 0,'bridge': 1,}
with tf.io.TFRecordWriter(record_file) as writer:
    for row in df.index:
        full_path = 'data/img/new/' + df['filename'][row]
        label = image_labels[df['label'][row]]
        image_string = tf.io.read_file(full_path)
        tf_example = image_example(image_string,label)
        writer.write(tf_example.SerializeToString())

有关读取/写入TFRecord文件的完整教程,请参见this

如果您有多个标签,则可以在image_example内的功能字典中创建多个功能。 代码:

def image_example(image_string,label_color,label_type):
    image_shape = tf.image.decode_png(image_string).shape
    feature = {
      'height': _int64_feature(image_shape[0]),'label_color': _int64_feature(label_color),'label_type': _int64_feature(label_type),}
    return tf.train.Example(features=tf.train.Features(feature=feature))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...