download_and_convert_mnist_m.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 MNIST-M data to TFRecords of TF-Example protos.
  16. This module downloads the MNIST-M data, uncompresses it, reads the files
  17. that make up the MNIST-M 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 about a minute to run.
  21. """
  22. from __future__ import absolute_import
  23. from __future__ import division
  24. from __future__ import print_function
  25. import os
  26. import random
  27. import sys
  28. import google3
  29. import numpy as np
  30. from six.moves import urllib
  31. import tensorflow as tf
  32. from google3.third_party.tensorflow_models.slim.datasets import dataset_utils
  33. tf.app.flags.DEFINE_string(
  34. 'dataset_dir', None,
  35. 'The directory where the output TFRecords and temporary files are saved.')
  36. FLAGS = tf.app.flags.FLAGS
  37. # The URLs where the MNIST-M data can be downloaded.
  38. _DATA_URL = 'http://yann.lecun.com/exdb/mnist/'
  39. _TRAIN_DATA_DIR = 'mnist_m_train'
  40. _TRAIN_LABELS_FILENAME = 'mnist_m_train_labels'
  41. _TEST_DATA_DIR = 'mnist_m_test'
  42. _TEST_LABELS_FILENAME = 'mnist_m_test_labels'
  43. _IMAGE_SIZE = 32
  44. _NUM_CHANNELS = 3
  45. # The number of images in the training set.
  46. _NUM_TRAIN_SAMPLES = 59001
  47. # The number of images to be kept from the training set for the validation set.
  48. _NUM_VALIDATION = 1000
  49. # The number of images in the test set.
  50. _NUM_TEST_SAMPLES = 9001
  51. # Seed for repeatability.
  52. _RANDOM_SEED = 0
  53. # The names of the classes.
  54. _CLASS_NAMES = [
  55. 'zero',
  56. 'one',
  57. 'two',
  58. 'three',
  59. 'four',
  60. 'five',
  61. 'size',
  62. 'seven',
  63. 'eight',
  64. 'nine',
  65. ]
  66. class ImageReader(object):
  67. """Helper class that provides TensorFlow image coding utilities."""
  68. def __init__(self):
  69. # Initializes function that decodes RGB PNG data.
  70. self._decode_png_data = tf.placeholder(dtype=tf.string)
  71. self._decode_png = tf.image.decode_png(self._decode_png_data, channels=3)
  72. def read_image_dims(self, sess, image_data):
  73. image = self.decode_png(sess, image_data)
  74. return image.shape[0], image.shape[1]
  75. def decode_png(self, sess, image_data):
  76. image = sess.run(
  77. self._decode_png, feed_dict={self._decode_png_data: image_data})
  78. assert len(image.shape) == 3
  79. assert image.shape[2] == 3
  80. return image
  81. def _convert_dataset(split_name, filenames, filename_to_class_id, dataset_dir):
  82. """Converts the given filenames to a TFRecord dataset.
  83. Args:
  84. split_name: The name of the dataset, either 'train' or 'valid'.
  85. filenames: A list of absolute paths to png images.
  86. filename_to_class_id: A dictionary from filenames (strings) to class ids
  87. (integers).
  88. dataset_dir: The directory where the converted datasets are stored.
  89. """
  90. print('Converting the {} split.'.format(split_name))
  91. # Train and validation splits are both in the train directory.
  92. if split_name in ['train', 'valid']:
  93. png_directory = os.path.join(dataset_dir, 'mnist-m', 'mnist_m_train')
  94. elif split_name == 'test':
  95. png_directory = os.path.join(dataset_dir, 'mnist-m', 'mnist_m_test')
  96. with tf.Graph().as_default():
  97. image_reader = ImageReader()
  98. with tf.Session('') as sess:
  99. output_filename = _get_output_filename(dataset_dir, split_name)
  100. with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer:
  101. for filename in filenames:
  102. # Read the filename:
  103. image_data = tf.gfile.FastGFile(
  104. os.path.join(png_directory, filename), 'r').read()
  105. height, width = image_reader.read_image_dims(sess, image_data)
  106. class_id = filename_to_class_id[filename]
  107. example = dataset_utils.image_to_tfexample(image_data, 'png', height,
  108. width, class_id)
  109. tfrecord_writer.write(example.SerializeToString())
  110. sys.stdout.write('\n')
  111. sys.stdout.flush()
  112. def _extract_labels(label_filename):
  113. """Extract the labels into a dict of filenames to int labels.
  114. Args:
  115. labels_filename: The filename of the MNIST-M labels.
  116. Returns:
  117. A dictionary of filenames to int labels.
  118. """
  119. print('Extracting labels from: ', label_filename)
  120. label_file = tf.gfile.FastGFile(label_filename, 'r').readlines()
  121. label_lines = [line.rstrip('\n').split() for line in label_file]
  122. labels = {}
  123. for line in label_lines:
  124. assert len(line) == 2
  125. labels[line[0]] = int(line[1])
  126. return labels
  127. def _get_output_filename(dataset_dir, split_name):
  128. """Creates the output filename.
  129. Args:
  130. dataset_dir: The directory where the temporary files are stored.
  131. split_name: The name of the train/test split.
  132. Returns:
  133. An absolute file path.
  134. """
  135. return '%s/mnist_m_%s.tfrecord' % (dataset_dir, split_name)
  136. def _get_filenames(dataset_dir):
  137. """Returns a list of filenames and inferred class names.
  138. Args:
  139. dataset_dir: A directory containing a set PNG encoded MNIST-M images.
  140. Returns:
  141. A list of image file paths, relative to `dataset_dir`.
  142. """
  143. photo_filenames = []
  144. for filename in os.listdir(dataset_dir):
  145. photo_filenames.append(filename)
  146. return photo_filenames
  147. def run(dataset_dir):
  148. """Runs the download and conversion operation.
  149. Args:
  150. dataset_dir: The dataset directory where the dataset is stored.
  151. """
  152. if not tf.gfile.Exists(dataset_dir):
  153. tf.gfile.MakeDirs(dataset_dir)
  154. train_filename = _get_output_filename(dataset_dir, 'train')
  155. testing_filename = _get_output_filename(dataset_dir, 'test')
  156. if tf.gfile.Exists(train_filename) and tf.gfile.Exists(testing_filename):
  157. print('Dataset files already exist. Exiting without re-creating them.')
  158. return
  159. #TODO(konstantinos): Add download and cleanup functionality
  160. train_validation_filenames = _get_filenames(
  161. os.path.join(dataset_dir, 'mnist-m', 'mnist_m_train'))
  162. test_filenames = _get_filenames(
  163. os.path.join(dataset_dir, 'mnist-m', 'mnist_m_test'))
  164. # Divide into train and validation:
  165. random.seed(_RANDOM_SEED)
  166. random.shuffle(train_validation_filenames)
  167. train_filenames = train_validation_filenames[_NUM_VALIDATION:]
  168. validation_filenames = train_validation_filenames[:_NUM_VALIDATION]
  169. train_validation_filenames_to_class_ids = _extract_labels(
  170. os.path.join(dataset_dir, 'mnist-m', 'mnist_m_train_labels.txt'))
  171. test_filenames_to_class_ids = _extract_labels(
  172. os.path.join(dataset_dir, 'mnist-m', 'mnist_m_test_labels.txt'))
  173. # Convert the train, validation, and test sets.
  174. _convert_dataset('train', train_filenames,
  175. train_validation_filenames_to_class_ids, dataset_dir)
  176. _convert_dataset('valid', validation_filenames,
  177. train_validation_filenames_to_class_ids, dataset_dir)
  178. _convert_dataset('test', test_filenames, test_filenames_to_class_ids,
  179. dataset_dir)
  180. # Finally, write the labels file:
  181. labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES))
  182. dataset_utils.write_label_file(labels_to_class_names, dataset_dir)
  183. print('\nFinished converting the MNIST-M dataset!')
  184. def main(_):
  185. run(FLAGS.dataset_dir)
  186. if __name__ == '__main__':
  187. tf.app.run()