如何将编码JPEG以字节写入TensorFlow TFRecord并正确读取?
如何将JPEG编码图像存入TFRecord并正确读取
嘿,David,先给你吃个定心丸:你的写入代码其实已经在存储编码后的JPEG图像了!之前文件体积大是因为你存了解码后的原始像素,现在这个写法才是正确的方向,问题大概率出在读取环节的细节处理上,咱们一步步理清楚:
先确认写入逻辑没问题
你用open(path, 'rb').read()直接读取磁盘上的JPEG二进制文件,这就是编码后的字节流,完全没做解码操作——这正是你想要的!只要你的wrap_bytes函数是像下面这样实现的,写入环节就没毛病:
def wrap_bytes(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def wrap_int64(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
优化读取函数,解决格式错误
你的读取思路是对的,但有两个小细节容易踩坑,调整后就能避免格式问题:
- 用
tf.image.decode_jpeg替代tf.image.decode_image:decode_image是通用解码函数,对JPEG来说,专用的decode_jpeg更稳定,还能明确指定通道数; - 显式设置图像形状:避免后续数据处理时因为形状不确定报错。
优化后的读取函数:
def parse(serialized): features = { 'image': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.int64) } parsed_example = tf.parse_single_example(serialized=serialized, features=features) # 解码JPEG编码的图像字节,指定3通道RGB image = tf.image.decode_jpeg(parsed_example['image'], channels=3) # 根据你的数据集调整尺寸,比如224x224 image = tf.reshape(image, [224, 224, 3]) # 转换为float32并归一化(训练时常用,可选) image = tf.cast(image, tf.float32) / 255.0 # 标签转成int32足够用,和大部分训练流程匹配 label = tf.cast(parsed_example['label'], tf.int32) return image, label
加个验证步骤,排查问题
如果还是遇到错误,可以用下面的代码快速验证TFRecord里的图像数据是否有效,帮你定位是写入还是读取的问题:
import tensorflow as tf import matplotlib.pyplot as plt import io from PIL import Image record_path = path_tfrecords_train # 遍历第一条记录验证 for serialized_example in tf.python_io.tf_record_iterator(record_path): example = tf.train.Example() example.ParseFromString(serialized_example) img_bytes = example.features.feature['image'].bytes_list.value[0] label = example.features.feature['label'].int64_list.value[0] # 把字节转回图像显示 img = Image.open(io.BytesIO(img_bytes)) plt.imshow(img) plt.title(f"Label: {label}") plt.show() break # 只看第一条就行
如果能正常显示图像,说明写入完全没问题,只需要调整读取函数即可。
为啥之前会出错?
你之前用tf.decode_raw读取编码后的JPEG字节肯定会报错,因为decode_raw是把字节直接解析成原始像素,而JPEG是压缩过的编码流,必须用专门的解码函数处理。现在换成decode_image是对的,但专用的decode_jpeg更靠谱。
总的来说,你的写入逻辑已经踩对了点,只要调整读取环节的这几个细节,就能顺利实现用编码格式存储JPEG到TFRecord啦!
内容的提问来源于stack exchange,提问作者D. Rusk
相关产品推荐
相关产品推荐

