以下内容主要是针对遇上tensorflow之如何构建自己的图片数据集tfrecords等问题,我们该怎么处理呢。下面这篇文章将为你提供一个解决思路,希望能帮你解决到相关问题。
1、什么是TFrecords
TFrecords是TensorFlow提供的一种数据存储格式,它是一种将图片和标签统一存储的二进制文件,可以有效提高数据的存取速度,比起普通的文件存储格式,TFrecords可以更好的满足深度学习的需求。
2、构建自己的图片数据集TFrecords
1、首先需要准备好自己的图片,图片的格式可以是jpg、png等,并且需要准备好相应的标签,比如图片代表的物体类别等。
2、将图片和标签转换成TFrecords格式,首先需要安装TensorFlow,然后在Python中引入TensorFlow,接着使用tf.python_io.TFRecordWriter()函数创建一个TFrecords文件,然后使用tf.train.Example()函数,将图片转换成字符串格式,并将图片和标签封装成Example协议内存块,然后将Example写入TFrecords文件中。
3、最后使用tf.TFRecordReader()函数读取TFrecords文件,并使用tf.parse_single_example()函数解析出图片和标签。
3、代码示例
# 将图片转换成字符串
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
# 将标签转换成int64
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
# 将图片和标签封装成Example协议内存块
def image_example(image_string, label):
image_shape = tf.image.decode_jpeg(image_string).shape
feature = {
'height': _int64_feature(image_shape[0]),
'width': _int64_feature(image_shape[1]),
'depth': _int64_feature(image_shape[2]),
'label': _int64_feature(label),
'image_raw': _bytes_feature(image_string)
}
return tf.train.Example(features=tf.train.Features(feature=feature))
# 将Example写入TFrecords文件中
def write_tfrecords(image_paths, labels, out_path):
with tf.python_io.TFRecordWriter(out_path) as writer:
for i, (image_path, label) in enumerate(zip(image_paths, labels)):
image_string = open(image_path, 'rb').read()
example = image_example(image_string, label)
writer.write(example.SerializeToString())
print('Processed {}/{}'.format(i+1, len(image_paths)))
# 读取TFrecords文件
def read_tfrecords(tfrecords_path):
dataset = tf.data.TFRecordDataset(tfrecords_path)
for serialized_example in dataset:
example = tf.train.Example()
example.ParseFromString(serialized_example.numpy())
image_string = example.features.feature['image_raw'].bytes_list.value[0]
label = example.features.feature['label'].int64_list.value[0]
height = example.features.feature['height'].int64_list.value[0]
width = example.features.feature['width'].int64_list.value[0]
depth = example.features.feature['depth'].int64_list.value[0]
image_shape = (height, width, depth)
image_data = tf.image.decode_jpeg(image_string, channels=3)
yield image_data, label, image_shape
总结
以上就是为你整理的tensorflow之如何构建自己的图片数据集tfrecords全部内容,希望文章能够帮你解决相关问题,更多请关注本站相关栏目的其它相关文章!