用python将照片做成数据集_将自己的数据集制作成TFRecord格式教程

在使用TensorFlow训练神经网络时,首先面临的问题是:网络的输入

此篇文章,教大家将自己的数据集制作成TFRecord格式,feed进网络,除了TFRecord格式,TensorFlow也支持其他格

式的数据,此处就不再介绍了。建议大家使用TFRecord格式,在后面可以通过api进行多线程的读取文件队列。

1. 原本的数据集

此时,我有两类图片,分别是xiansu100,xiansu60,每一类中有10张图片。

20200217093128.jpg

2.制作成TFRecord格式

tfrecord会根据你选择输入文件的类,自动给每一类打上同样的标签。如在本例中,只有0,1 两类,想知道文件夹名与label关系的,可以自己保存起来。

#生成整数型的属性

def _int64_feature(value):

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

#生成字符串类型的属性

def _bytes_feature(value):

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

#制作TFRecord格式

def createTFRecord(filename,mapfile):

class_map = {}

data_dir = '/home/wc/DataSet/traffic/testTFRecord/'

classes = {'xiansu60','xiansu100'}

#输出TFRecord文件的地址

writer = tf.python_io.TFRecordWriter(filename)

for index,name in enumerate(classes):

class_path=data_dir+name+'/'

class_map[index] = name

for img_name in os.listdir(class_path):

img_path = class_path + img_name #每个图片的地址

img = Image.open(img_path)

img= img.resize((224,224))

img_raw = img.tobytes() #将图片转化成二进制格式

example = tf.train.Example(features = tf.train.Features(feature = {

'label':_int64_feature(index),

'image_raw': _bytes_feature(img_raw)

}))

writer.write(example.SerializeToString())

writer.close()

txtfile = open(mapfile,'w+')

for key in class_map.keys():

txtfile.writelines(str(key)+":"+class_map[key]+"\n")

txtfile.close()

此段代码,运行完后会产生生成的.tfrecord文件。

3. 读取TFRecord的数据,进行解析,此时使用了文件队列以及多线程

#读取train.tfrecord中的数据

def read_and_decode(filename):

#创建一个reader来读取TFRecord文件中的样例

reader = tf.TFRecordReader()

#创建一个队列来维护输入文件列表

filename_queue = tf.train.string_input_producer([filename], shuffle=False,num_epochs = 1)

#从文件中读出一个样例,也可以使用read_up_to一次读取多个样例

_,serialized_example = reader.read(filename_queue)

# print _,serialized_example

#解析读入的一个样例,如果需要解析多个,可以用parse_example

features = tf.parse_single_example(

serialized_example,

features = {'label':tf.FixedLenFeature([], tf.int64),

'image_raw': tf.FixedLenFeature([], tf.string),})

#将字符串解析成图像对应的像素数组

img = tf.decode_raw(features['image_raw'], tf.uint8)

img = tf.reshape(img,[224, 224, 3]) #reshape为128*128*3通道图片

img = tf.image.per_image_standardization(img)

labels = tf.cast(features['label'], tf.int32)

return img, labels

4. 将图片几个一打包,形成batch

def createBatch(filename,batchsize):

images,labels = read_and_decode(filename)

min_after_dequeue = 10

capacity = min_after_dequeue + 3 * batchsize

image_batch, label_batch = tf.train.shuffle_batch([images, labels],

batch_size=batchsize,

capacity=capacity,

min_after_dequeue=min_after_dequeue

)

label_batch = tf.one_hot(label_batch,depth=2)

return image_batch, label_batch

5.主函数

if __name__ =="__main__":

#训练图片两张为一个batch,进行训练,测试图片一起进行测试

mapfile = "/home/wc/DataSet/traffic/testTFRecord/classmap.txt"

train_filename = "/home/wc/DataSet/traffic/testTFRecord/train.tfrecords"

# createTFRecord(train_filename,mapfile)

test_filename = "/home/wc/DataSet/traffic/testTFRecord/test.tfrecords"

# createTFRecord(test_filename,mapfile)

image_batch, label_batch = createBatch(filename = train_filename,batchsize = 2)

test_images,test_labels = createBatch(filename = test_filename,batchsize = 20)

with tf.Session() as sess:

initop = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())

sess.run(initop)

coord = tf.train.Coordinator()

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

try:

step = 0

while 1:

_image_batch,_label_batch = sess.run([image_batch,label_batch])

step += 1

print step

print (_label_batch)

except tf.errors.OutOfRangeError:

print (" trainData done!")

try:

step = 0

while 1:

_test_images,_test_labels = sess.run([test_images,test_labels])

step += 1

print step

# print _image_batch.shape

print (_test_labels)

except tf.errors.OutOfRangeError:

print (" TEST done!")

coord.request_stop()

coord.join(threads)

此时,生成的batch,就可以feed进网络了。

以上这篇将自己的数据集制作成TFRecord格式教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
将VOC数据集转换为TFRecord文件需要以下步骤: 1. 下载VOC数据集并解压缩。 2. 安装TensorFlow和Pillow库。 3. 编写脚本将VOC数据集转换为TFRecord文件。 以下是一个简单的Python脚本示例,可以将VOC数据集转换为TFRecord文件: ```python import tensorflow as tf import os import io import xml.etree.ElementTree as ET from PIL import Image def create_tf_example(example): # 读取图像文件 img_path = os.path.join('VOCdevkit/VOC2012/JPEGImages', example['filename']) with tf.io.gfile.GFile(img_path, 'rb') as fid: encoded_jpg = fid.read() encoded_jpg_io = io.BytesIO(encoded_jpg) image = Image.open(encoded_jpg_io) width, height = image.size # 读取标注文件 xml_path = os.path.join('VOCdevkit/VOC2012/Annotations', example['filename'].replace('.jpg', '.xml')) with tf.io.gfile.GFile(xml_path, 'r') as fid: xml_str = fid.read() xml = ET.fromstring(xml_str) # 解析标注文件 xmins = [] xmaxs = [] ymins = [] ymaxs = [] classes_text = [] classes = [] for obj in xml.findall('object'): class_name = obj.find('name').text classes_text.append(class_name.encode('utf8')) classes.append(label_map[class_name]) bbox = obj.find('bndbox') xmins.append(float(bbox.find('xmin').text) / width) ymins.append(float(bbox.find('ymin').text) / height) xmaxs.append(float(bbox.find('xmax').text) / width) ymaxs.append(float(bbox.find('ymax').text) / height) # 构造TFRecord Example tf_example = tf.train.Example(features=tf.train.Features(feature={ 'image/height': tf.train.Feature(int64_list=tf.train.Int64List(value=[height])), 'image/width': tf.train.Feature(int64_list=tf.train.Int64List(value=[width])), 'image/filename': tf.train.Feature(bytes_list=tf.train.BytesList(value=[example['filename'].encode('utf8')])), 'image/source_id': tf.train.Feature(bytes_list=tf.train.BytesList(value=[example['filename'].encode('utf8')])), 'image/encoded': tf.train.Feature(bytes_list=tf.train.BytesList(value=[encoded_jpg])), 'image/format': tf.train.Feature(bytes_list=tf.train.BytesList(value=['jpeg'.encode('utf8')])), 'image/object/bbox/xmin': tf.train.Feature(float_list=tf.train.FloatList(value=xmins)), 'image/object/bbox/xmax': tf.train.Feature(float_list=tf.train.FloatList(value=xmaxs)), 'image/object/bbox/ymin': tf.train.Feature(float_list=tf.train.FloatList(value=ymins)), 'image/object/bbox/ymax': tf.train.Feature(float_list=tf.train.FloatList(value=ymaxs)), 'image/object/class/text': tf.train.Feature(bytes_list=tf.train.BytesList(value=classes_text)), 'image/object/class/label': tf.train.Feature(int64_list=tf.train.Int64List(value=classes)), })) return tf_example # 将VOC数据集转换为TFRecord文件 def create_tf_record(output_file): examples = [...] # 从VOC数据集读取实例 writer = tf.io.TFRecordWriter(output_file) for example in examples: tf_example = create_tf_example(example) writer.write(tf_example.SerializeToString()) writer.close() label_map = {...} # 标签映射 output_file = 'voc_train.tfrecord' create_tf_record(output_file) ``` 其中`create_tf_example`函数将一个VOC样本转换为TFRecord Example,`create_tf_record`函数将整个VOC数据集转换为TFRecord文件。在这个例子中,我们假设VOC数据集已经被解压缩到`VOCdevkit/VOC2012`目录下,标签映射已经定义为`label_map`变量。你需要根据自己的实际情况修改这些变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值