TFRecord-制作数据集

# -*- coding:utf-8 -*-

import os
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _byte_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

cwd = 'Picture'
classes = {'glacier','rock','urban'}
filename = 'TFRecord/glacier_rock_urban.tfrecords'
writer = tf.python_io.TFRecordWriter(filename)

for index, name in enumerate(classes):

    class_path = cwd + '/' +  name + '/'

    for img_name in os.listdir(class_path):

        img_path = class_path + img_name
        img = Image.open(img_path)
        #img = img.resize((64,64))
        img_raw = img.tobytes()

        example = tf.train.Example(features=tf.train.Features(feature={
            'label':_int64_feature(index),
            'img_raw':_byte_feature(img_raw),
        }))
        writer.write(example.SerializeToString())

writer.close()

# -*- coding:utf-8 -*-

import os
import tensorflow as tf
from PIL import Image


cwd = os.getcwd()
reader = tf.TFRecordReader()
filename = 'TFRecord/glacier_rock_urban.tfrecords'
filename_queue = tf.train.string_input_producer([filename])
_, 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 = tf.decode_raw(features['img_raw'],tf.uint8)
image = tf.reshape(image, shape=[256,256,3])
label = tf.cast(features['label'],tf.int64)

with tf.Session() as sess:

    init_glob = tf.global_variables_initializer()
    init_local = tf.local_variables_initializer()
    sess.run([init_glob,init_local])

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess,coord=coord)

    for i in range(10):

        example, l = sess.run([image, label])
        # image = sess.run(tf.reshape(example, shape=[256, 256, 3]))
        img = Image.fromarray(example,'RGB')
        img.save(fp=cwd + str(i) + '_' + str(l) + '.jpg')
        print("example:"  ,example)
        print("label:", l)

    coord.request_stop()
    coord.join(threads)

参考:https://zhuanlan.zhihu.com/p/35666271

https://zhuanlan.zhihu.com/p/40588218

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值