gpt4 book ai didi

tensorflow - 如何将编码的 jpeg 作为字节写入 Tensorflow tfrecord 然后读取它?

转载 作者:行者123 更新时间:2023-12-03 01:38:38 29 4
gpt4 key购买 nike

我正在尝试使用tensorflows tfrecords格式来存储我的数据集。

我设法读取 jpeg 图像并将它们解码为原始格式并将它们写入 tfrecord 文件。然后我可以稍后使用 tf.decode_raw 读取它们。

问题是这会导致文件大小巨大,因为我将图像存储为原始图像。现在我看到很多教程和博客说我可以将它们存储为编码格式,然后在阅读它们时只需解码它们。我找不到任何这方面的例子。我已经尝试了一段时间,但无论我做什么,我都会遇到格式错误。

TLDR有谁知道如何将图像作为 jpeg 而不是原始图像写入 tfrecord 文件。

谢谢你,大卫。

我的写作功能。

def convert(image_paths, labels, out_path):

num_images = len(image_paths)

with tf.python_io.TFRecordWriter(out_path) as writer:
for i, (path, label) in enumerate(zip(image_paths, labels)):

print_progress(count=i, total=num_images-1)
img = open(path, 'rb').read()

data ={'image': wrap_bytes(img),
'label': wrap_int64(label)}

feature = tf.train.Features(feature=data)
example = tf.train.Example(features=feature)
serialized = example.SerializeToString()
writer.write(serialized)

用这个转换数据集:

{convert(image_paths=image_paths_train,
labels=cls_train,
out_path=path_tfrecords_train)}

我的阅读功能

def parse(serialized):

features = \
{
'image': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64)
}
parsed_example = tf.parse_single_example(serialized=serialized,
features=features)

# Get the image as raw bytes.
image_raw = parsed_example['image']

# Decode the raw bytes so it becomes a tensor with type.
image = tf.image.decode_image(image_raw,channels=3)

#image = tf.decode_raw(image_raw, tf.uint8)

# The type is now uint8 but we need it to be float.
image = tf.cast(image, tf.float32)

# Get the label associated with the image.
label = parsed_example['label']

# The image and label are now correct TensorFlow types.
return image, label

最佳答案

要进行写入,只需将文件作为二进制文件打开 (fp = open('something.jpg', 'rb')) 并 .read() 其内容。当您现在存储图像时,将该内容存储在 tfrecord Example 中(即,作为字节功能)。

要进行读取,请使用 tf.image.decode_image 并传入从示例读取器获得的张量,而不是执行 decode_raw

如果您发布代码,我可以提供更好的代码示例,但不知道您的代码看起来如何,这是我所能得到的详细信息。

关于tensorflow - 如何将编码的 jpeg 作为字节写入 Tensorflow tfrecord 然后读取它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48343900/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com