问题描述
我正在从本地文件系统读取图像,将其转换为字节格式,最后将图像摄取到 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 (将#修改为@)