download_and_convert_flowers.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 Flowers data to TFRecords of TF-Example protos.
  16. This script downloads the Flowers data, uncompresses it, reads the files
  17. that make up the Flowers 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. Usage:
  22. $ bazel build slim:download_and_convert_flowers
  23. $ .bazel-bin/slim/download_and_convert_flowers --dataset_dir=[DIRECTORY]
  24. """
  25. from __future__ import absolute_import
  26. from __future__ import division
  27. from __future__ import print_function
  28. import math
  29. import os
  30. import random
  31. import sys
  32. import tarfile
  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 Flowers data can be downloaded.
  42. _DATA_URL = 'http://download.tensorflow.org/example_images/flower_photos.tgz'
  43. # The number of images in the validation set.
  44. _NUM_VALIDATION = 350
  45. # Seed for repeatability.
  46. _RANDOM_SEED = 0
  47. # The number of shards per dataset split.
  48. _NUM_SHARDS = 5
  49. class ImageReader(object):
  50. """Helper class that provides TensorFlow image coding utilities."""
  51. def __init__(self):
  52. # Initializes function that decodes RGB JPEG data.
  53. self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
  54. self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
  55. def read_image_dims(self, sess, image_data):
  56. image = self.decode_jpeg(sess, image_data)
  57. return image.shape[0], image.shape[1]
  58. def decode_jpeg(self, sess, image_data):
  59. image = sess.run(self._decode_jpeg,
  60. feed_dict={self._decode_jpeg_data: image_data})
  61. assert len(image.shape) == 3
  62. assert image.shape[2] == 3
  63. return image
  64. def _download_dataset(dataset_dir):
  65. """Downloads the flowers data and uncompresses it locally.
  66. Args:
  67. dataset_dir: The directory where the temporary files are stored.
  68. """
  69. filename = _DATA_URL.split('/')[-1]
  70. filepath = os.path.join(dataset_dir, filename)
  71. if not os.path.exists(filepath):
  72. def _progress(count, block_size, total_size):
  73. sys.stdout.write('\r>> Downloading %s %.1f%%' % (
  74. filename, float(count * block_size) / float(total_size) * 100.0))
  75. sys.stdout.flush()
  76. filepath, _ = urllib.request.urlretrieve(_DATA_URL, filepath, _progress)
  77. print()
  78. statinfo = os.stat(filepath)
  79. print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  80. tarfile.open(filepath, 'r:gz').extractall(dataset_dir)
  81. def _get_filenames_and_classes(dataset_dir):
  82. """Returns a list of filenames and inferred class names.
  83. Args:
  84. dataset_dir: A directory containing a set of subdirectories representing
  85. class names. Each subdirectory should contain PNG or JPG encoded images.
  86. Returns:
  87. A list of image file paths, relative to `dataset_dir` and the list of
  88. subdirectories, representing class names.
  89. """
  90. flower_root = os.path.join(dataset_dir, 'flower_photos')
  91. directories = []
  92. class_names = []
  93. for filename in os.listdir(flower_root):
  94. path = os.path.join(flower_root, filename)
  95. if os.path.isdir(path):
  96. directories.append(path)
  97. class_names.append(filename)
  98. photo_filenames = []
  99. for directory in directories:
  100. for filename in os.listdir(directory):
  101. path = os.path.join(directory, filename)
  102. photo_filenames.append(path)
  103. return photo_filenames, sorted(class_names)
  104. def _convert_dataset(split_name, filenames, class_names_to_ids, dataset_dir):
  105. """Converts the given filenames to a TFRecord dataset.
  106. Args:
  107. split_name: The name of the dataset, either 'train' or 'validation'.
  108. filenames: A list of absolute paths to png or jpg images.
  109. class_names_to_ids: A dictionary from class names (strings) to ids
  110. (integers).
  111. dataset_dir: The directory where the converted datasets are stored.
  112. """
  113. assert split_name in ['train', 'validation']
  114. num_per_shard = int(math.ceil(len(filenames) / float(_NUM_SHARDS)))
  115. with tf.Graph().as_default():
  116. image_reader = ImageReader()
  117. with tf.Session('') as sess:
  118. for shard_id in range(_NUM_SHARDS):
  119. output_filename = 'flowers_%s_%05d-of-%05d.tfrecord' % (
  120. split_name, shard_id, _NUM_SHARDS)
  121. output_filename = os.path.join(dataset_dir, output_filename)
  122. with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer:
  123. start_ndx = shard_id * num_per_shard
  124. end_ndx = min((shard_id+1) * num_per_shard, len(filenames))
  125. for i in range(start_ndx, end_ndx):
  126. sys.stdout.write('\r>> Converting image %d/%d shard %d' % (
  127. i+1, len(filenames), shard_id))
  128. sys.stdout.flush()
  129. # Read the filename:
  130. image_data = tf.gfile.FastGFile(filenames[i], 'r').read()
  131. height, width = image_reader.read_image_dims(sess, image_data)
  132. class_name = os.path.basename(os.path.dirname(filenames[i]))
  133. class_id = class_names_to_ids[class_name]
  134. example = dataset_utils.image_to_tfexample(
  135. image_data, 'jpg', height, width, class_id)
  136. tfrecord_writer.write(example.SerializeToString())
  137. sys.stdout.write('\n')
  138. sys.stdout.flush()
  139. def _clean_up_temporary_files(dataset_dir):
  140. """Removes temporary files used to create the dataset.
  141. Args:
  142. dataset_dir: The directory where the temporary files are stored.
  143. """
  144. filename = _DATA_URL.split('/')[-1]
  145. filepath = os.path.join(dataset_dir, filename)
  146. tf.gfile.Remove(filepath)
  147. tmp_dir = os.path.join(dataset_dir, 'flower_photos')
  148. tf.gfile.DeleteRecursively(tmp_dir)
  149. def main(_):
  150. if not FLAGS.dataset_dir:
  151. raise ValueError('You must supply the dataset directory with --dataset_dir')
  152. if not tf.gfile.Exists(FLAGS.dataset_dir):
  153. tf.gfile.MakeDirs(FLAGS.dataset_dir)
  154. _download_dataset(FLAGS.dataset_dir)
  155. photo_filenames, class_names = _get_filenames_and_classes(FLAGS.dataset_dir)
  156. class_names_to_ids = dict(zip(class_names, range(len(class_names))))
  157. # Divide into train and test:
  158. random.seed(_RANDOM_SEED)
  159. random.shuffle(photo_filenames)
  160. training_filenames = photo_filenames[_NUM_VALIDATION:]
  161. validation_filenames = photo_filenames[:_NUM_VALIDATION]
  162. # First, convert the training and validation sets.
  163. _convert_dataset('train', training_filenames, class_names_to_ids,
  164. FLAGS.dataset_dir)
  165. _convert_dataset('validation', validation_filenames, class_names_to_ids,
  166. FLAGS.dataset_dir)
  167. # Finally, write the labels file:
  168. labels_to_class_names = dict(zip(range(len(class_names)), class_names))
  169. dataset_utils.write_label_file(labels_to_class_names, FLAGS.dataset_dir)
  170. _clean_up_temporary_files(FLAGS.dataset_dir)
  171. print('\nFinished converting the Flowers dataset!')
  172. if __name__ == '__main__':
  173. tf.app.run()