TensorFlow从TFRecord读取JPEG图像出现信息丢失的问题求助
从TFRecord读取JPEG图像出现信息丢失问题
从TFRecord中读取JPEG图像时似乎出现了信息丢失,示例如下:
- 原始图像:https://i.sstatic.net/QyKMI.jpg
- 解码后JPEG图像(重塑为600x600维度):https://i.sstatic.net/dUyoP.jpg
我使用Keras的image_dataset_from_directory函数创建了tf.data.Dataset,并通过tf.io.encode_jpeg将每个形状为600x600x3的图像张量编码为字节字符串:
image = tf.image.convert_image_dtype(image_tensor, dtype=tf.uint8) image = tf.io.encode_jpeg(image, quality=100)
每个TFRecord样本的构造方式如下:
# encoded_image 为 encode_jpeg 函数的输出 image_feature = tf.train.Feature( bytes_list=tf.train.BytesList(value=[ encoded_image ]) ) features = tf.train.Features(feature={ 'image': image_feature }) example = tf.train.Example(features=features) return example.SerializeToString()
以下是加载TFRecords数据集的代码,使用tf.image.decode_jpeg将图像解码回形状为600x600x3的张量,之后通过PIL将单张图像保存到磁盘:
def read_tfrecord(example): tfrecord = { "image": tf.io.FixedLenFeature([], tf.string) } example = tf.io.parse_single_example(example, tfrecord) image = tf.image.decode_jpeg(example['image'], channels=3) return image def read_dataset(dataset_path): filenames = tf.io.gfile.glob(dataset_path + '/validation/*.tfrecord') dataset = tf.data.TFRecordDataset(filenames) dataset = dataset.map(read_tfrecord) dataset = dataset.repeat() dataset = dataset.batch(128) for image, label in dataset.take(1): Image.fromarray((image[0].numpy())).save('./images/img.jpeg')
我目前完全不清楚是什么导致了这种明显的图像信息丢失,非常感谢大家提供的任何帮助!
备注
- 使用的环境为Tensorflow v2.5.0、Pillow v8.0.1
- 完整代码可查看对应Gist:https://gist.github.com/deeDude/c40fa1f14e4fa4b7f2ef149e5a344023
内容的提问来源于stack exchange,提问作者TheDude
相关产品推荐
相关产品推荐

