【问题标题】:tfRecords with images as inputs and targets以图像作为输入和目标的 tfRecords
【发布时间】:2019-03-12 15:50:10
【问题描述】:

我目前正在尝试从本地存储的一些 .png 图像创建一个 tf.Records。

我在这方面看到的大多数示例都是针对分类任务的,其中目标值是类。 我正在尝试构建一个 VAE,所以我的目标值也是图像。

我在生成 tf.Records 时找到了 this 示例:

# Converting the values into features
# _int64 is used for numeric values
def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

# _bytes is used for string/char values
def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

tfrecord_filename = 'something.tfrecords'

# Initiating the writer and creating the tfrecords file.
writer = tf.python_io.TFRecordWriter(tfrecord_filename)

# Loading the location of all files - image dataset
# Considering our image dataset has apple or orange
# The images are named as apple01.jpg, apple02.jpg .. , orange01.jpg .. etc.

images = glob.glob('data/*.jpg')
for image in images[:1]:
    img = Image.open(image)
    img = np.array(img.resize((32,32)))
label = 0 if 'apple' in image else 1
feature = { 'label': _int64_feature(label),'image': _bytes_feature(img.tostring()) }

# Create an example protocol buffer
example = tf.train.Example(features=tf.train.Features(feature=feature))

# Writing the serialized example.
writer.write(example.SerializeToString())

writer.close()

问题: 应该如何更改以将图像也保存为目标值?

有变化吗:

feature = { 'label': _int64_feature(label),'image': _bytes_feature(img.tostring()) }

feature = { 'label': _bytes_feature(img.tostring()),'image': _bytes_feature(img.tostring()) }

?

提前致谢

【问题讨论】:

    标签: python tensorflow machine-learning data-analysis tfrecord


    【解决方案1】:

    我认为您可以在一个示例中保存两个图像。而且通常 保存图像尺寸的好主意

    features=tf.train.Features(feature={'height': _int64_feature(h),
                                        'width': _int64_feature(w),
                                        'channels': _int64_feature(c)
                                        'image_1': _bytes_feature(image1)
                                        'image_2': _bytes_feature(image2)
                                        }
                              ))
    example = tf.train.Example(features=tf.train.Features(feature=feature))
    

    编辑

    如果我猜对了:

    list = np.array([image_1, image_2,...image_n])
    images = np.split(np.fromstring(list.tostring()), number_of_images)
    

    【讨论】:

    • 感谢您的回复。您作为特征传递的图像是 img.tostring() 还是原始 PIL 图像?
    • 另外,阿飞明白了,上面的例子只保存了1张图片。如何将所有图像保存在 1 tf.records 中?循环遍历所有图像值或将图像列表放入_bytes_feature()
    • 是的,您需要img.tostring()。我添加了一个如何传递图像列表的原始解决方案
    • 再次感谢,我以前用过 TF,但我是 tf.records 的新手。所以在您的编辑中,list np 数组中的元素是文件位置还是文件对象?
    • 它们是 numpy 数组,您可以使用类似 cv2.imread
    猜你喜欢
    • 2018-05-01
    • 2017-04-01
    • 2019-07-10
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2020-04-16
    • 1970-01-01
    相关资源
    最近更新 更多