download_and_convert_cifar10.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 module 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. """
  22. from __future__ import absolute_import
  23. from __future__ import division
  24. from __future__ import print_function
  25. import cPickle
  26. import os
  27. import sys
  28. import tarfile
  29. import numpy as np
  30. from six.moves import urllib
  31. import tensorflow as tf
  32. from datasets import dataset_utils
  33. # The URL where the CIFAR data can be downloaded.
  34. _DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
  35. # The number of training files.
  36. _NUM_TRAIN_FILES = 5
  37. # The height and width of each image.
  38. _IMAGE_SIZE = 32
  39. # The names of the classes.
  40. _CLASS_NAMES = [
  41. 'airplane',
  42. 'automobile',
  43. 'bird',
  44. 'cat',
  45. 'deer',
  46. 'dog',
  47. 'frog',
  48. 'horse',
  49. 'ship',
  50. 'truck',
  51. ]
  52. def _add_to_tfrecord(filename, tfrecord_writer, offset=0):
  53. """Loads data from the cifar10 pickle files and writes files to a TFRecord.
  54. Args:
  55. filename: The filename of the cifar10 pickle file.
  56. tfrecord_writer: The TFRecord writer to use for writing.
  57. offset: An offset into the absolute number of images previously written.
  58. Returns:
  59. The new offset.
  60. """
  61. with tf.gfile.Open(filename, 'r') as f:
  62. data = cPickle.load(f)
  63. images = data['data']
  64. num_images = images.shape[0]
  65. images = images.reshape((num_images, 3, 32, 32))
  66. labels = data['labels']
  67. with tf.Graph().as_default():
  68. image_placeholder = tf.placeholder(dtype=tf.uint8)
  69. encoded_image = tf.image.encode_png(image_placeholder)
  70. with tf.Session('') as sess:
  71. for j in range(num_images):
  72. sys.stdout.write('\r>> Reading file [%s] image %d/%d' % (
  73. filename, offset + j + 1, offset + num_images))
  74. sys.stdout.flush()
  75. image = np.squeeze(images[j]).transpose((1, 2, 0))
  76. label = labels[j]
  77. png_string = sess.run(encoded_image,
  78. feed_dict={image_placeholder: image})
  79. example = dataset_utils.image_to_tfexample(
  80. png_string, 'png', _IMAGE_SIZE, _IMAGE_SIZE, label)
  81. tfrecord_writer.write(example.SerializeToString())
  82. return offset + num_images
  83. def _get_output_filename(dataset_dir, split_name):
  84. """Creates the output filename.
  85. Args:
  86. dataset_dir: The dataset directory where the dataset is stored.
  87. split_name: The name of the train/test split.
  88. Returns:
  89. An absolute file path.
  90. """
  91. return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name)
  92. def _download_and_uncompress_dataset(dataset_dir):
  93. """Downloads cifar10 and uncompresses it locally.
  94. Args:
  95. dataset_dir: The directory where the temporary files are stored.
  96. """
  97. filename = _DATA_URL.split('/')[-1]
  98. filepath = os.path.join(dataset_dir, filename)
  99. if not os.path.exists(filepath):
  100. def _progress(count, block_size, total_size):
  101. sys.stdout.write('\r>> Downloading %s %.1f%%' % (
  102. filename, float(count * block_size) / float(total_size) * 100.0))
  103. sys.stdout.flush()
  104. filepath, _ = urllib.request.urlretrieve(_DATA_URL, filepath, _progress)
  105. print()
  106. statinfo = os.stat(filepath)
  107. print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  108. tarfile.open(filepath, 'r:gz').extractall(dataset_dir)
  109. def _clean_up_temporary_files(dataset_dir):
  110. """Removes temporary files used to create the dataset.
  111. Args:
  112. dataset_dir: The directory where the temporary files are stored.
  113. """
  114. filename = _DATA_URL.split('/')[-1]
  115. filepath = os.path.join(dataset_dir, filename)
  116. tf.gfile.Remove(filepath)
  117. tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py')
  118. tf.gfile.DeleteRecursively(tmp_dir)
  119. def run(dataset_dir):
  120. """Runs the download and conversion operation.
  121. Args:
  122. dataset_dir: The dataset directory where the dataset is stored.
  123. """
  124. if not tf.gfile.Exists(dataset_dir):
  125. tf.gfile.MakeDirs(dataset_dir)
  126. training_filename = _get_output_filename(dataset_dir, 'train')
  127. testing_filename = _get_output_filename(dataset_dir, 'test')
  128. if tf.gfile.Exists(training_filename) and tf.gfile.Exists(testing_filename):
  129. print('Dataset files already exist. Exiting without re-creating them.')
  130. return
  131. dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir)
  132. # First, process the training data:
  133. with tf.python_io.TFRecordWriter(training_filename) as tfrecord_writer:
  134. offset = 0
  135. for i in range(_NUM_TRAIN_FILES):
  136. filename = os.path.join(dataset_dir,
  137. 'cifar-10-batches-py',
  138. 'data_batch_%d' % (i + 1)) # 1-indexed.
  139. offset = _add_to_tfrecord(filename, tfrecord_writer, offset)
  140. # Next, process the testing data:
  141. with tf.python_io.TFRecordWriter(testing_filename) as tfrecord_writer:
  142. filename = os.path.join(dataset_dir,
  143. 'cifar-10-batches-py',
  144. 'test_batch')
  145. _add_to_tfrecord(filename, tfrecord_writer)
  146. # Finally, write the labels file:
  147. labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES))
  148. dataset_utils.write_label_file(labels_to_class_names, dataset_dir)
  149. _clean_up_temporary_files(dataset_dir)
  150. print('\nFinished converting the Cifar10 dataset!')