原文链接: 猫狗大战 从 record 文件中读取一张图片并显示
下一篇: tensorflow flowers数据集 record文件 提取图像
record文件不会一次性全部加载进内存
写入的时候是按照rgb顺序写入的,使用opencv显示的时候需要做一次颜色转化
每次的图片显示的都是不一样的
import tensorflow as tf
import cv2 as cv
RECORD_PATH = "d:/data/cat_vs_dog/cat_vs_dog.record"
def read(path):
queue = tf.train.string_input_producer([path])
reader = tf.TFRecordReader()
_, data = reader.read(queue)
features = tf.parse_single_example(
data, {
'label': tf.FixedLenFeature([], tf.int64),
'image': tf.FixedLenFeature([], tf.string)
}
)
label = features['label']
image = features['image']
# 不知为何会出错...
# image = tf.image.decode_image(image, channels=3)
# 必须将图片转化为大小相同的矩阵,不然没办法进行批次训练
image = tf.decode_raw(image, tf.uint8)
image = tf.reshape(image, (224, 224, 3))
# image (224, 224, 3)
print('image ', image.shape)
image_batch, label_batch = tf.train.shuffle_batch(
[image, label],
batch_size=16,
capacity=256,
min_after_dequeue=128,
num_threads=4
)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator()
thread = tf.train.start_queue_runners(sess, coord)
image_data, label_data = sess.run(
[image_batch, label_batch]
)
# (16, 224, 224, 3) (16,)
print(image_data.shape, label_data.shape)
img = image_data[0]
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
# (224, 224, 3) 0
print(img.shape, label_data[0])
cv.imshow('image', img)
cv.waitKey(0)
coord.request_stop()
# 超时时间30s
coord.join(thread, 30)
if __name__ == '__main__':
read(RECORD_PATH)