build_image_data.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. # Copyright 2016 Google Inc. 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. """Converts image data to TFRecords file format with Example protos.
  16. The image data set is expected to reside in JPEG files located in the
  17. following directory structure.
  18. data_dir/label_0/image0.jpeg
  19. data_dir/label_0/image1.jpg
  20. ...
  21. data_dir/label_1/weird-image.jpeg
  22. data_dir/label_1/my-image.jpeg
  23. ...
  24. where the sub-sirectory is the unique label associated with these images.
  25. This TensorFlow script converts the training and evaluation data into
  26. a sharded data set consisting of TFRecord files
  27. train_directory/train-00000-of-01024
  28. train_directory/train-00001-of-01024
  29. ...
  30. train_directory/train-00127-of-01024
  31. and
  32. validation_directory/validation-00000-of-00128
  33. validation_directory/validation-00001-of-00128
  34. ...
  35. validation_directory/validation-00127-of-00128
  36. where we have selected 1024 and 128 shards for each data set. Each record
  37. within the TFRecord file is a serialized Example proto. The Example proto
  38. contains the following fields:
  39. image/encoded: string containing JPEG encoded image in RGB colorspace
  40. image/height: integer, image height in pixels
  41. image/width: integer, image width in pixels
  42. image/colorspace: string, specifying the colorspace, always 'RGB'
  43. image/channels: integer, specifying the number of channels, always 3
  44. image/format: string, specifying the format, always'JPEG'
  45. image/filename: string containing the basename of the image file
  46. e.g. 'n01440764_10026.JPEG' or 'ILSVRC2012_val_00000293.JPEG'
  47. image/class/label: integer specifying the index in a classification layer.
  48. The label ranges from [0, num_labels] where 0 is unused and left as
  49. the background class.
  50. image/class/text: string specifying the human-readable version of the label
  51. e.g. 'dog'
  52. If you data set involves bounding boxes, please look at build_imagenet_data.py.
  53. """
  54. from __future__ import absolute_import
  55. from __future__ import division
  56. from __future__ import print_function
  57. from datetime import datetime
  58. import os
  59. import random
  60. import sys
  61. import threading
  62. import numpy as np
  63. import tensorflow as tf
  64. tf.app.flags.DEFINE_string('train_directory', '/tmp/',
  65. 'Training data directory')
  66. tf.app.flags.DEFINE_string('validation_directory', '/tmp/',
  67. 'Validation data directory')
  68. tf.app.flags.DEFINE_string('output_directory', '/tmp/',
  69. 'Output data directory')
  70. tf.app.flags.DEFINE_integer('train_shards', 2,
  71. 'Number of shards in training TFRecord files.')
  72. tf.app.flags.DEFINE_integer('validation_shards', 2,
  73. 'Number of shards in validation TFRecord files.')
  74. tf.app.flags.DEFINE_integer('num_threads', 2,
  75. 'Number of threads to preprocess the images.')
  76. # The labels file contains a list of valid labels are held in this file.
  77. # Assumes that the file contains entries as such:
  78. # dog
  79. # cat
  80. # flower
  81. # where each line corresponds to a label. We map each label contained in
  82. # the file to an integer corresponding to the line number starting from 0.
  83. tf.app.flags.DEFINE_string('labels_file', '', 'Labels file')
  84. FLAGS = tf.app.flags.FLAGS
  85. def _int64_feature(value):
  86. """Wrapper for inserting int64 features into Example proto."""
  87. if not isinstance(value, list):
  88. value = [value]
  89. return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
  90. def _bytes_feature(value):
  91. """Wrapper for inserting bytes features into Example proto."""
  92. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
  93. def _convert_to_example(filename, image_buffer, label, text, height, width):
  94. """Build an Example proto for an example.
  95. Args:
  96. filename: string, path to an image file, e.g., '/path/to/example.JPG'
  97. image_buffer: string, JPEG encoding of RGB image
  98. label: integer, identifier for the ground truth for the network
  99. text: string, unique human-readable, e.g. 'dog'
  100. height: integer, image height in pixels
  101. width: integer, image width in pixels
  102. Returns:
  103. Example proto
  104. """
  105. colorspace = 'RGB'
  106. channels = 3
  107. image_format = 'JPEG'
  108. example = tf.train.Example(features=tf.train.Features(feature={
  109. 'image/height': _int64_feature(height),
  110. 'image/width': _int64_feature(width),
  111. 'image/colorspace': _bytes_feature(colorspace),
  112. 'image/channels': _int64_feature(channels),
  113. 'image/class/label': _int64_feature(label),
  114. 'image/class/text': _bytes_feature(text),
  115. 'image/format': _bytes_feature(image_format),
  116. 'image/filename': _bytes_feature(os.path.basename(filename)),
  117. 'image/encoded': _bytes_feature(image_buffer)}))
  118. return example
  119. class ImageCoder(object):
  120. """Helper class that provides TensorFlow image coding utilities."""
  121. def __init__(self):
  122. # Create a single Session to run all image coding calls.
  123. self._sess = tf.Session()
  124. # Initializes function that converts PNG to JPEG data.
  125. self._png_data = tf.placeholder(dtype=tf.string)
  126. image = tf.image.decode_png(self._png_data, channels=3)
  127. self._png_to_jpeg = tf.image.encode_jpeg(image, format='rgb', quality=100)
  128. # Initializes function that decodes RGB JPEG data.
  129. self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
  130. self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
  131. def png_to_jpeg(self, image_data):
  132. return self._sess.run(self._png_to_jpeg,
  133. feed_dict={self._png_data: image_data})
  134. def decode_jpeg(self, image_data):
  135. image = self._sess.run(self._decode_jpeg,
  136. feed_dict={self._decode_jpeg_data: image_data})
  137. assert len(image.shape) == 3
  138. assert image.shape[2] == 3
  139. return image
  140. def _is_png(filename):
  141. """Determine if a file contains a PNG format image.
  142. Args:
  143. filename: string, path of the image file.
  144. Returns:
  145. boolean indicating if the image is a PNG.
  146. """
  147. return '.png' in filename
  148. def _process_image(filename, coder):
  149. """Process a single image file.
  150. Args:
  151. filename: string, path to an image file e.g., '/path/to/example.JPG'.
  152. coder: instance of ImageCoder to provide TensorFlow image coding utils.
  153. Returns:
  154. image_buffer: string, JPEG encoding of RGB image.
  155. height: integer, image height in pixels.
  156. width: integer, image width in pixels.
  157. """
  158. # Read the image file.
  159. image_data = tf.gfile.FastGFile(filename, 'r').read()
  160. # Convert any PNG to JPEG's for consistency.
  161. if _is_png(filename):
  162. print('Converting PNG to JPEG for %s' % filename)
  163. image_data = coder.png_to_jpeg(image_data)
  164. # Decode the RGB JPEG.
  165. image = coder.decode_jpeg(image_data)
  166. # Check that image converted to RGB
  167. assert len(image.shape) == 3
  168. height = image.shape[0]
  169. width = image.shape[1]
  170. assert image.shape[2] == 3
  171. return image_data, height, width
  172. def _process_image_files_batch(coder, thread_index, ranges, name, filenames,
  173. texts, labels, num_shards):
  174. """Processes and saves list of images as TFRecord in 1 thread.
  175. Args:
  176. coder: instance of ImageCoder to provide TensorFlow image coding utils.
  177. thread_index: integer, unique batch to run index is within [0, len(ranges)).
  178. ranges: list of pairs of integers specifying ranges of each batches to
  179. analyze in parallel.
  180. name: string, unique identifier specifying the data set
  181. filenames: list of strings; each string is a path to an image file
  182. texts: list of strings; each string is human readable, e.g. 'dog'
  183. labels: list of integer; each integer identifies the ground truth
  184. num_shards: integer number of shards for this data set.
  185. """
  186. # Each thread produces N shards where N = int(num_shards / num_threads).
  187. # For instance, if num_shards = 128, and the num_threads = 2, then the first
  188. # thread would produce shards [0, 64).
  189. num_threads = len(ranges)
  190. assert not num_shards % num_threads
  191. num_shards_per_batch = int(num_shards / num_threads)
  192. shard_ranges = np.linspace(ranges[thread_index][0],
  193. ranges[thread_index][1],
  194. num_shards_per_batch + 1).astype(int)
  195. num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0]
  196. counter = 0
  197. for s in xrange(num_shards_per_batch):
  198. # Generate a sharded version of the file name, e.g. 'train-00002-of-00010'
  199. shard = thread_index * num_shards_per_batch + s
  200. output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards)
  201. output_file = os.path.join(FLAGS.output_directory, output_filename)
  202. writer = tf.python_io.TFRecordWriter(output_file)
  203. shard_counter = 0
  204. files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)
  205. for i in files_in_shard:
  206. filename = filenames[i]
  207. label = labels[i]
  208. text = texts[i]
  209. image_buffer, height, width = _process_image(filename, coder)
  210. example = _convert_to_example(filename, image_buffer, label,
  211. text, height, width)
  212. writer.write(example.SerializeToString())
  213. shard_counter += 1
  214. counter += 1
  215. if not counter % 1000:
  216. print('%s [thread %d]: Processed %d of %d images in thread batch.' %
  217. (datetime.now(), thread_index, counter, num_files_in_thread))
  218. sys.stdout.flush()
  219. print('%s [thread %d]: Wrote %d images to %s' %
  220. (datetime.now(), thread_index, shard_counter, output_file))
  221. sys.stdout.flush()
  222. shard_counter = 0
  223. print('%s [thread %d]: Wrote %d images to %d shards.' %
  224. (datetime.now(), thread_index, counter, num_files_in_thread))
  225. sys.stdout.flush()
  226. def _process_image_files(name, filenames, texts, labels, num_shards):
  227. """Process and save list of images as TFRecord of Example protos.
  228. Args:
  229. name: string, unique identifier specifying the data set
  230. filenames: list of strings; each string is a path to an image file
  231. texts: list of strings; each string is human readable, e.g. 'dog'
  232. labels: list of integer; each integer identifies the ground truth
  233. num_shards: integer number of shards for this data set.
  234. """
  235. assert len(filenames) == len(texts)
  236. assert len(filenames) == len(labels)
  237. # Break all images into batches with a [ranges[i][0], ranges[i][1]].
  238. spacing = np.linspace(0, len(filenames), FLAGS.num_threads + 1).astype(np.int)
  239. ranges = []
  240. threads = []
  241. for i in xrange(len(spacing) - 1):
  242. ranges.append([spacing[i], spacing[i+1]])
  243. # Launch a thread for each batch.
  244. print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges))
  245. sys.stdout.flush()
  246. # Create a mechanism for monitoring when all threads are finished.
  247. coord = tf.train.Coordinator()
  248. # Create a generic TensorFlow-based utility for converting all image codings.
  249. coder = ImageCoder()
  250. threads = []
  251. for thread_index in xrange(len(ranges)):
  252. args = (coder, thread_index, ranges, name, filenames,
  253. texts, labels, num_shards)
  254. t = threading.Thread(target=_process_image_files_batch, args=args)
  255. t.start()
  256. threads.append(t)
  257. # Wait for all the threads to terminate.
  258. coord.join(threads)
  259. print('%s: Finished writing all %d images in data set.' %
  260. (datetime.now(), len(filenames)))
  261. sys.stdout.flush()
  262. def _find_image_files(data_dir, labels_file):
  263. """Build a list of all images files and labels in the data set.
  264. Args:
  265. data_dir: string, path to the root directory of images.
  266. Assumes that the image data set resides in JPEG files located in
  267. the following directory structure.
  268. data_dir/dog/another-image.JPEG
  269. data_dir/dog/my-image.jpg
  270. where 'dog' is the label associated with these images.
  271. labels_file: string, path to the labels file.
  272. The list of valid labels are held in this file. Assumes that the file
  273. contains entries as such:
  274. dog
  275. cat
  276. flower
  277. where each line corresponds to a label. We map each label contained in
  278. the file to an integer starting with the integer 0 corresponding to the
  279. label contained in the first line.
  280. Returns:
  281. filenames: list of strings; each string is a path to an image file.
  282. texts: list of strings; each string is the class, e.g. 'dog'
  283. labels: list of integer; each integer identifies the ground truth.
  284. """
  285. print('Determining list of input files and labels from %s.' % data_dir)
  286. unique_labels = [l.strip() for l in tf.gfile.FastGFile(
  287. labels_file, 'r').readlines()]
  288. labels = []
  289. filenames = []
  290. texts = []
  291. # Leave label index 0 empty as a background class.
  292. label_index = 1
  293. # Construct the list of JPEG files and labels.
  294. for text in unique_labels:
  295. jpeg_file_path = '%s/%s/*' % (data_dir, text)
  296. matching_files = tf.gfile.Glob(jpeg_file_path)
  297. labels.extend([label_index] * len(matching_files))
  298. texts.extend([text] * len(matching_files))
  299. filenames.extend(matching_files)
  300. if not label_index % 100:
  301. print('Finished finding files in %d of %d classes.' % (
  302. label_index, len(labels)))
  303. label_index += 1
  304. # Shuffle the ordering of all image files in order to guarantee
  305. # random ordering of the images with respect to label in the
  306. # saved TFRecord files. Make the randomization repeatable.
  307. shuffled_index = range(len(filenames))
  308. random.seed(12345)
  309. random.shuffle(shuffled_index)
  310. filenames = [filenames[i] for i in shuffled_index]
  311. texts = [texts[i] for i in shuffled_index]
  312. labels = [labels[i] for i in shuffled_index]
  313. print('Found %d JPEG files across %d labels inside %s.' %
  314. (len(filenames), len(unique_labels), data_dir))
  315. return filenames, texts, labels
  316. def _process_dataset(name, directory, num_shards, labels_file):
  317. """Process a complete data set and save it as a TFRecord.
  318. Args:
  319. name: string, unique identifier specifying the data set.
  320. directory: string, root path to the data set.
  321. num_shards: integer number of shards for this data set.
  322. labels_file: string, path to the labels file.
  323. """
  324. filenames, texts, labels = _find_image_files(directory, labels_file)
  325. _process_image_files(name, filenames, texts, labels, num_shards)
  326. def main(unused_argv):
  327. assert not FLAGS.train_shards % FLAGS.num_threads, (
  328. 'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards')
  329. assert not FLAGS.validation_shards % FLAGS.num_threads, (
  330. 'Please make the FLAGS.num_threads commensurate with '
  331. 'FLAGS.validation_shards')
  332. print('Saving results to %s' % FLAGS.output_directory)
  333. # Run it!
  334. _process_dataset('validation', FLAGS.validation_directory,
  335. FLAGS.validation_shards, FLAGS.labels_file)
  336. _process_dataset('train', FLAGS.train_directory,
  337. FLAGS.train_shards, FLAGS.labels_file)
  338. if __name__ == '__main__':
  339. tf.app.run()