我目前正在尝试从本地存储的.png图像创建tf.Records。
我看到的大多数例子都是关于分类任务的,其中目标值是类别。我正在尝试构建一个变分自编码器(VAE),所以我的目标值也将是图像。
我找到了这个关于生成tf.Records的例子:
# 将值转换为特征# _int64 用于数值def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))# _bytes 用于字符串/字符值def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))tfrecord_filename = 'something.tfrecords'# 初始化写入器并创建tfrecords文件writer = tf.python_io.TFRecordWriter(tfrecord_filename)# 加载所有文件的位置 - 图像数据集# 假设我们的图像数据集有苹果或橙子# 图像被命名为apple01.jpg, apple02.jpg .. , orange01.jpg .. 等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 1feature = { 'label': _int64_feature(label),'image': _bytes_feature(img.tostring()) }# 创建一个示例协议缓冲区example = tf.train.Example(features=tf.train.Features(feature=feature))# 写入序列化示例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()) }
?
提前感谢
回答:
我认为你可以在一个示例中保存两张图像。通常,保存图像尺寸也是个好主意
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)