1、读取数据集到tfrecorder
<h3>1、读取照片以及标签存入 tfrecorder</h3>
<pre><code>import tensorflow as tf
#from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
from PIL import Image
import os
import pandas as pd
#---从自己电脑磁盘文件中读取图片,存储到一个TFRecord文件中,这里把猫狗大战的训练样本存储到一个TFRecord文件中---#
#"f:\\cat_dog_image\\train\\"
#猫狗大战训练样本在本地磁盘中的地址
# D:/work/jupyterNotebook/baidu_dianshi/data/micro_height_dataIALT_JQV4INA5dynXU8jl.jpg
#生成字符型的属性
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
#生成整数型的属性
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
'''
for file in os.listdir(file_dir):
img_path=file_dir+file #每个图片的地址
print(img_path)
name = file.split(sep='.')
if name[0]=='cat':
label=0
else:
label=1
'''
def save_to_tfrecord():
# 照片目录
file_dir="D:\\work\\jupyterNotebook\\baidu_dianshi\\data\\micro_height_data"
# 读入标签数据
df = pd.DataFrame(pd.read_csv('./data/micro_height_data_lable.csv',header=0))
# 获取lables 和img_name
lables = df['lables']
img_name = df['img_name']
#输出TFRecord文件的地址
filename="./output.tfrecords"
#创建一个writer来写TFRecord文件
writer=tf.python_io.TFRecordWriter(filename)
# 遍历文件夹内所有图片,读取图片存到img,遍历到名字,在img_name中查找
# 查找到后,获取当前行数,取出对应的label,并替换为1-6的整数存入label_name
for file in os.listdir(file_dir):
print(file)
img_path=file_dir+'\\'+file #每个图片的地址
img=Image.open(img_path)
i = 0
for file_name in img_name:
if file_name == file:
label = lables[i]
break
i = i+1
print(label)
if label == 'MOUNTAIN':
label_name = 1
elif label == 'OCEAN':
label_name = 2
elif label == 'DESERT': #沙漠
label_name = 3
elif label == 'LAKE':
label_name = 4
elif label == 'FARMLAND': #农田
label_name = 5
elif label == 'CITY':
label_name = 6
#将图像矩阵转化成一个字符串
image_raw=img.tobytes()
#获取图像尺寸
(img_W,img_H)=img.size
#图像通道数
channels=3
#将一个样例转化成Example Protocol Buffer,并将所有的信息写入这个数据结构
example=tf.train.Example(features=tf.train.Features(feature={
'img_W': _int64_feature(img_W),
'img_H': _int64_feature(img_H),
'channels': _int64_feature(channels),
'label': _int64_feature(label_name),
'image_raw': _bytes_feature(image_raw)}))
#将一个Example写入TFRecord文件中
writer.write(example.SerializeToString())
writer.close()
return None
def read_data():
#读取TFRecord文件,创建文件列表,并通过文件列表创建输入文件队列。在调用输入数据处理流程前,需要统一所有原始数据的格式并将它们存储到TFRecord文件中。
files=tf.train.match_filenames_once("./output.tfrecords")
filename_queue=tf.train.string_input_producer(files,shuffle=True) #不随机打乱
#解析TFRecord文件里的数据
reader=tf.TFRecordReader()
_,serialized_example=reader.read(filename_queue)
features=tf.parse_single_example(serialized_example,
features={
'image_raw': tf.FixedLenFeature([],tf.string),
'label': tf.FixedLenFeature([],tf.int64),
'img_W': tf.FixedLenFeature([],tf.int64),
})
#得到图像原始数据、尺寸、标签。
image,label,img_W=features['image_raw'],features['label'],features['img_W']
print(img_W)
#从原始图像数据解析出像素矩阵,并根据图像尺寸还原图像
decode_image=tf.decode_raw(image,tf.uint8)
decode_image=tf.reshape(decode_image,[256,256,1])
#将图像和标签数据通过tf.train.shuffle_batch整理成神经网络训练时需要的batch
min_after_dequeue=500
batch_size=100
capacity=min_after_dequeue+3*batch_size
image_batch,label_batch=tf.train.shuffle_batch([decode_image,label],batch_size=batch_size,capacity=capacity,min_after_dequeue=min_after_dequeue)
image_batch=tf.cast(image_batch,tf.float32)
#返回batch数据
return image_batch,label_batch
if __name__ == '__main__':
(image_batch,label_batch) = read_data()
print(image_batch)
</code></pre>