用户登录
用户注册

分享至

tensorflow学习笔记之tfrecord文件的生成与读取

  • 作者: 我呵呵你一脸花露水
  • 来源: 51数据库
  • 2021-08-29

训练模型时,我们并不是直接将图像送入模型,而是先将图像转换为tfrecord文件,再将tfrecord文件送入模型。为进一步理解tfrecord文件,本例先将6幅图像及其标签转换为tfrecord文件,然后读取tfrecord文件,重现6幅图像及其标签。
1、生成tfrecord文件

import os
import numpy as np
import tensorflow as tf
from pil import image

filenames = [
'images/cat/1.jpg',
'images/cat/2.jpg',
'images/dog/1.jpg',
'images/dog/2.jpg',
'images/pig/1.jpg',
'images/pig/2.jpg',]

labels = {'cat':0, 'dog':1, 'pig':2}

def int64_feature(values):
	if not isinstance(values, (tuple, list)):
		values = [values]
	return tf.train.feature(int64_list=tf.train.int64list(value=values))

def bytes_feature(values):
	return tf.train.feature(bytes_list=tf.train.byteslist(value=[values]))

with tf.session() as sess:
	output_filename = os.path.join('images/train.tfrecords')
	with tf.python_io.tfrecordwriter(output_filename) as tfrecord_writer:
		for filename in filenames:
			#读取图像
			image_data = image.open(filename)
			#图像灰度化
			image_data = np.array(image_data.convert('l'))
			#将图像转化为bytes
			image_data = image_data.tobytes()
			#读取label
			label = labels[filename.split('/')[-2]]
			#生成protocol数据类型
			example = tf.train.example(features=tf.train.features(feature={'image': bytes_feature(image_data),
																			'label': int64_feature(label)}))
			tfrecord_writer.write(example.serializetostring())

2、读取tfrecord文件

import tensorflow as tf
import matplotlib.pyplot as plt
from pil import image

# 根据文件名生成一个队列
filename_queue = tf.train.string_input_producer(['images/train.tfrecords'])
reader = tf.tfrecordreader()
# 返回文件名和文件
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example, 
									features={'image': tf.fixedlenfeature([], tf.string), 
												'label': tf.fixedlenfeature([], tf.int64)})
# 获取图像数据
image = tf.decode_raw(features['image'], tf.uint8)
# 恢复图像原始尺寸[高,宽]
image = tf.reshape(image, [60, 160])
# 获取label
label = tf.cast(features['label'], tf.int32)

with tf.session() as sess:
	# 创建一个协调器,管理线程
	coord = tf.train.coordinator()
	# 启动queuerunner, 此时文件名队列已经进队
	threads = tf.train.start_queue_runners(sess=sess, coord=coord)

	for i in range(6):
		image_b, label_b = sess.run([image, label])
		img = image.fromarray(image_b, 'l')
		plt.imshow(img)
		plt.axis('off')
		plt.show()
		print(label_b)

	# 通知其他线程关闭
	coord.request_stop()
	# 其他所有线程关闭之后,这一函数才能返回
	coord.join(threads)

到此这篇关于tensorflow学习笔记之tfrecord文件的生成与读取的文章就介绍到这了,更多相关tfrecord文件的生成与读取内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

软件
前端设计
程序设计
Java相关