download_and_convert_cifar10.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. r"""Downloads and converts cifar10 data to TFRecords of TF-Example protos.
  16. This script downloads the cifar10 data, uncompresses it, reads the files
  17. that make up the cifar10 data and creates two TFRecord datasets: one for train
  18. and one for test. Each TFRecord dataset is comprised of a set of TF-Example
  19. protocol buffers, each of which contain a single image and label.
  20. The script should take several minutes to run.
  21. Usage:
  22. $ bazel build slim:download_and_convert_cifar10
  23. $ .bazel-bin/slim/download_and_convert_cifar10 --dataset_dir=[DIRECTORY]
  24. """
  25. from __future__ import absolute_import
  26. from __future__ import division
  27. from __future__ import print_function
  28. import cPickle
  29. import os
  30. import sys
  31. import tarfile
  32. import numpy as np
  33. from six.moves import urllib
  34. import tensorflow as tf
  35. from slim.datasets import dataset_utils
  36. tf.app.flags.DEFINE_string(
  37. 'dataset_dir',
  38. None,
  39. 'The directory where the output TFRecords and temporary files are saved.')
  40. FLAGS = tf.app.flags.FLAGS
  41. # The URL where the CIFAR data can be downloaded.
  42. _DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
  43. # The number of training files.
  44. _NUM_TRAIN_FILES = 5
  45. # The height and width of each image.
  46. _IMAGE_SIZE = 32
  47. # The names of the classes.
  48. _CLASS_NAMES = [
  49. 'airplane',
  50. 'automobile',
  51. 'bird',
  52. 'cat',
  53. 'deer',
  54. 'dog',
  55. 'frog',
  56. 'horse',
  57. 'ship',
  58. 'truck',
  59. ]
  60. def _add_to_tfrecord(filename, tfrecord_writer, offset=0):
  61. """Loads data from the cifar10 pickle files and writes files to a TFRecord.
  62. Args:
  63. filename: The filename of the cifar10 pickle file.
  64. tfrecord_writer: The TFRecord writer to use for writing.
  65. offset: An offset into the absolute number of images previously written.
  66. Returns:
  67. The new offset.
  68. """
  69. with tf.gfile.Open(filename, 'r') as f:
  70. data = cPickle.load(f)
  71. images = data['data']
  72. num_images = images.shape[0]
  73. images = images.reshape((num_images, 3, 32, 32))
  74. labels = data['labels']
  75. with tf.Graph().as_default():
  76. image_placeholder = tf.placeholder(dtype=tf.uint8)
  77. encoded_image = tf.image.encode_png(image_placeholder)
  78. with tf.Session('') as sess:
  79. for j in range(num_images):
  80. sys.stdout.write('\r>> Reading file [%s] image %d/%d' % (
  81. filename, offset + j + 1, offset + num_images))
  82. sys.stdout.flush()
  83. image = np.squeeze(images[j]).transpose((1, 2, 0))
  84. label = labels[j]
  85. png_string = sess.run(encoded_image,
  86. feed_dict={image_placeholder: image})
  87. example = dataset_utils.image_to_tfexample(
  88. png_string, 'png', _IMAGE_SIZE, _IMAGE_SIZE, label)
  89. tfrecord_writer.write(example.SerializeToString())
  90. return offset + num_images
  91. def _get_output_filename(split_name):
  92. """Creates the output filename.
  93. Args:
  94. split_name: The name of the train/test split.
  95. Returns:
  96. An absolute file path.
  97. """
  98. return '%s/cifar10_%s.tfrecord' % (FLAGS.dataset_dir, split_name)
  99. def _download_and_uncompress_dataset(dataset_dir):
  100. """Downloads cifar10 and uncompresses it locally.
  101. Args:
  102. dataset_dir: The directory where the temporary files are stored.
  103. """
  104. filename = _DATA_URL.split('/')[-1]
  105. filepath = os.path.join(dataset_dir, filename)
  106. if not os.path.exists(filepath):
  107. def _progress(count, block_size, total_size):
  108. sys.stdout.write('\r>> Downloading %s %.1f%%' % (
  109. filename, float(count * block_size) / float(total_size) * 100.0))
  110. sys.stdout.flush()
  111. filepath, _ = urllib.request.urlretrieve(_DATA_URL, filepath, _progress)
  112. print()
  113. statinfo = os.stat(filepath)
  114. print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  115. tarfile.open(filepath, 'r:gz').extractall(dataset_dir)
  116. def _clean_up_temporary_files(dataset_dir):
  117. """Removes temporary files used to create the dataset.
  118. Args:
  119. dataset_dir: The directory where the temporary files are stored.
  120. """
  121. filename = _DATA_URL.split('/')[-1]
  122. filepath = os.path.join(dataset_dir, filename)
  123. tf.gfile.Remove(filepath)
  124. tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py')
  125. tf.gfile.DeleteRecursively(tmp_dir)
  126. def main(_):
  127. if not FLAGS.dataset_dir:
  128. raise ValueError('You must supply the dataset directory with --dataset_dir')
  129. if not tf.gfile.Exists(FLAGS.dataset_dir):
  130. tf.gfile.MakeDirs(FLAGS.dataset_dir)
  131. _download_and_uncompress_dataset(FLAGS.dataset_dir)
  132. # First, process the training data:
  133. output_file = _get_output_filename('train')
  134. with tf.python_io.TFRecordWriter(output_file) as tfrecord_writer:
  135. offset = 0
  136. for i in range(_NUM_TRAIN_FILES):
  137. filename = os.path.join(FLAGS.dataset_dir,
  138. 'cifar-10-batches-py',
  139. 'data_batch_%d' % (i + 1)) # 1-indexed.
  140. offset = _add_to_tfrecord(filename, tfrecord_writer, offset)
  141. # Next, process the testing data:
  142. output_file = _get_output_filename('test')
  143. with tf.python_io.TFRecordWriter(output_file) as tfrecord_writer:
  144. filename = os.path.join(FLAGS.dataset_dir,
  145. 'cifar-10-batches-py',
  146. 'test_batch')
  147. _add_to_tfrecord(filename, tfrecord_writer)
  148. # Finally, write the labels file:
  149. labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES))
  150. dataset_utils.write_label_file(labels_to_class_names, FLAGS.dataset_dir)
  151. _clean_up_temporary_files(FLAGS.dataset_dir)
  152. print('\nFinished converting the Cifar10 dataset!')
  153. if __name__ == '__main__':
  154. tf.app.run()