📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Examples to demonstrate how to write an image file to a TFRecord,1and how to read a TFRecord file using TFRecordReader.2Author: Chip Huyen3Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"4cs20si.stanford.edu5"""6import os7os.environ['TF_CPP_MIN_LOG_LEVEL']='2'89import sys10sys.path.append('..')1112from PIL import Image13import numpy as np14import matplotlib.pyplot as plt15import tensorflow as tf1617# image supposed to have shape: 480 x 640 x 3 = 92160018IMAGE_PATH = 'data/'1920def _int64_feature(value):21return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))2223def _bytes_feature(value):24return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))2526def get_image_binary(filename):27""" You can read in the image using tensorflow too, but it's a drag28since you have to create graphs. It's much easier using Pillow and NumPy29"""30image = Image.open(filename)31image = np.asarray(image, np.uint8)32shape = np.array(image.shape, np.int32)33return shape.tobytes(), image.tobytes() # convert image to raw data bytes in the array.3435def write_to_tfrecord(label, shape, binary_image, tfrecord_file):36""" This example is to write a sample to TFRecord file. If you want to write37more samples, just use a loop.38"""39writer = tf.python_io.TFRecordWriter(tfrecord_file)40# write label, shape, and image content to the TFRecord file41example = tf.train.Example(features=tf.train.Features(feature={42'label': _int64_feature(label),43'shape': _bytes_feature(shape),44'image': _bytes_feature(binary_image)45}))46writer.write(example.SerializeToString())47writer.close()4849def write_tfrecord(label, image_file, tfrecord_file):50shape, binary_image = get_image_binary(image_file)51write_to_tfrecord(label, shape, binary_image, tfrecord_file)5253def read_from_tfrecord(filenames):54tfrecord_file_queue = tf.train.string_input_producer(filenames, name='queue')55reader = tf.TFRecordReader()56_, tfrecord_serialized = reader.read(tfrecord_file_queue)5758# label and image are stored as bytes but could be stored as59# int64 or float64 values in a serialized tf.Example protobuf.60tfrecord_features = tf.parse_single_example(tfrecord_serialized,61features={62'label': tf.FixedLenFeature([], tf.int64),63'shape': tf.FixedLenFeature([], tf.string),64'image': tf.FixedLenFeature([], tf.string),65}, name='features')66# image was saved as uint8, so we have to decode as uint8.67image = tf.decode_raw(tfrecord_features['image'], tf.uint8)68shape = tf.decode_raw(tfrecord_features['shape'], tf.int32)69# the image tensor is flattened out, so we have to reconstruct the shape70image = tf.reshape(image, shape)71label = tfrecord_features['label']72return label, shape, image7374def read_tfrecord(tfrecord_file):75label, shape, image = read_from_tfrecord([tfrecord_file])7677with tf.Session() as sess:78coord = tf.train.Coordinator()79threads = tf.train.start_queue_runners(coord=coord)80label, image, shape = sess.run([label, image, shape])81coord.request_stop()82coord.join(threads)83print(label)84print(shape)85plt.imshow(image)86plt.show()8788def main():89# assume the image has the label Chihuahua, which corresponds to class number 190label = 191image_file = IMAGE_PATH + 'friday.jpg'92tfrecord_file = IMAGE_PATH + 'friday.tfrecord'93write_tfrecord(label, image_file, tfrecord_file)94read_tfrecord(tfrecord_file)9596if __name__ == '__main__':97main()9899100101