微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将图像转换为 TF 记录格式的正确方法将图像写入 TFrecord 格式生成稀疏张量 创建示例:无错误以 TfRecord 格式写入数据:无错误读取和打印数据:无错误从 tfrecords 格式读取单个示例:无错误从 tfrecords 格式读取图像数据:无错误这里给出了错误:TypeError: a bytes-like object is required, not 'SparseTensor'

如何解决将图像转换为 TF 记录格式的正确方法将图像写入 TFrecord 格式生成稀疏张量 创建示例:无错误以 TfRecord 格式写入数据:无错误读取和打印数据:无错误从 tfrecords 格式读取单个示例:无错误从 tfrecords 格式读取图像数据:无错误这里给出了错误:TypeError: a bytes-like object is required, not 'SparseTensor'

我正在从本地文件系统读取图像,将其转换为字节格式,最后将图像摄取到 tf.train.Feature 以转换为 TFRecord 格式。一切正常,直到我读取 TFrecord 并提取最终似乎是稀疏格式的图像字节格式。下面是我的完整流程的代码

读取 df 和图像文件:无错误

import tensorflow as tf
from PIL import Image
img_bytes_list = []
for img_path in df.filepath:
    with tf.io.gfile.GFile(img_path,"rb") as f:
        raw_img = f.read()
        img_bytes_list.append(raw_img)

定义功能:没有错误

write_features = {'filename': tf.train.Feature(bytes_list=tf.train.BytesList(value=df['filename'].apply(lambda x: x.encode("utf-8")))),'img_arr':tf.train.Feature(bytes_list=tf.train.BytesList(value=img_bytes_list)),'width': tf.train.Feature(int64_list=tf.train.Int64List(value=df['width'])),'height': tf.train.Feature(int64_list=tf.train.Int64List(value=df['height'])),'img_class': tf.train.Feature(bytes_list=tf.train.BytesList(value=df['class'].apply(lambda x: x.encode("utf-8")))),'xmin': tf.train.Feature(int64_list=tf.train.Int64List(value=df['xmin'])),'ymin': tf.train.Feature(int64_list=tf.train.Int64List(value=df['ymin'])),'xmax': tf.train.Feature(int64_list=tf.train.Int64List(value=df['xmax'])),'ymax': tf.train.Feature(int64_list=tf.train.Int64List(value=df['ymax']))}

创建示例:无错误

example = tf.train.Example(features=tf.train.Features(feature=write_features))

以 TfRecord 格式写入数据:无错误

with tf.io.TFRecordWriter('image_data_tfr') as writer:
    writer.write(example.SerializetoString())

读取和打印数据:无错误

read_features = {"filename": tf.io.VarLenFeature(dtype=tf.string),"img_arr": tf.io.VarLenFeature(dtype=tf.string),"width": tf.io.VarLenFeature(dtype=tf.int64),"height": tf.io.VarLenFeature(dtype=tf.int64),"class": tf.io.VarLenFeature(dtype=tf.string),"xmin": tf.io.VarLenFeature(dtype=tf.int64),"ymin": tf.io.VarLenFeature(dtype=tf.int64),"xmax": tf.io.VarLenFeature(dtype=tf.int64),"ymax": tf.io.VarLenFeature(dtype=tf.int64)}

从 tfrecords 格式读取单个示例:无错误

for serialized_example in tf.data.TFRecordDataset(["image_data_tfr"]):
    parsed_s_example = tf.io.parse_single_example(serialized=serialized_example,features=read_features)

从 tfrecords 格式读取图像数据:无错误

image_raw = parsed_s_example['img_arr']

encoded_jpg_io = io.BytesIO(image_raw)

这里给出了错误:TypeError: a bytes-like object is required,not 'SparseTensor'

image = Image.open(encoded_jpg_io)
width,height = image.size
print(width,height)

请告诉我在“image_arr”的输入处需要做哪些更改,以便它不会生成稀疏张量并返回字节格式?

我可以做些什么来优化我现有的代码

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。