tfrecord 中读取一张灰度图并显示

本文介绍如何使用TensorFlow从TFRecords文件中读取数据,解析并转换图像,包括处理灰度图的常见错误及解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

filename = './train.tfrecords'

filename_queue = tf.train.string_input_producer([filename])  # 读入流中
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)  # 返回文件名和文件
features = tf.parse_single_example(serialized_example,
                                   features={
                                       'label': tf.FixedLenFeature([], tf.int64),
                                       'img_raw': tf.FixedLenFeature([], tf.string),
                                   })  # 取出包含image和label的feature对象
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [28, 28, 1])
label = tf.cast(features['label'], tf.int32)

with tf.Session() as sess:  # 开始一个会话
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    coord = tf.train.Coordinator()  # 线程管理器
    threads = tf.train.start_queue_runners(coord=coord)
    for i in range(20):
        example, l = sess.run([image, label])  # 在会话中取出image和label
        img = Image.fromarray(example)  # 这里Image是之前提到的
        img.save('./Save_test/' + str(i) + '_''Label_' + str(l) + '.jpg')  # 存下图片
        print(example, l)
    coord.request_stop()
    coord.join(threads)

!!! img = Image.fromarray(example) 一直报错,原来如果tfrecode里面是灰度图,image = tf.reshape(image, [28, 28, 1])改为image = tf.reshape(image, [28, 28])即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值