制作TFrecords格式数据

来源:互联网 发布:js鼠标移开div消失 编辑:程序博客网 时间:2024/05/29 07:10

关于自己的图像制作成tfrecords格式,网上源码很多,github上面也有详细介绍。以下是个人经常使用的数据TFrecords制作的两个函数,借鉴《tensorflow技术解析与实战》P82队列和线程的使用。


#coding:utf-8
import os 
import tensorflow as tf 
from PIL import Image 
import matplotlib.pyplot as plt 
import numpy as np


cwd="/home/dreamer/data/autoencode3/" #源数据的路径 
classes={'2PSK_L','FSK_L','LFMCW_L','LFM_L','PM_L'} #人为 设定 5 类
writer= tf.python_io.TFRecordWriter("radio_train_VGG.tfrecords") #要生成的文件名称


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,192));#设置存储的图片大小,默认是三通道
#img=img(:,:,1);
        img_raw=img.tobytes()#将图片转化为二进制格式
        example = tf.train.Example(features=tf.train.Features(feature={
            "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
            'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
        })) #example对象对label和image数据进行封装
        writer.write(example.SerializeToString())  #序列化为字符串
writer.close()#关闭文件流

以上是TFrecords格式的制作,当给定路径,设置好参数后,会在指定路径生成TFrecords后缀的文件

PS:关于TFrecords格式的使用,在我的上一篇博客VGG16中是有应用的

原创粉丝点击