build_imagenet_data.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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 ImageNet data to TFRecords file format with Example protos.
  16. The raw ImageNet data set is expected to reside in JPEG files located in the
  17. following directory structure.
  18. data_dir/n01440764/ILSVRC2012_val_00000293.JPEG
  19. data_dir/n01440764/ILSVRC2012_val_00000543.JPEG
  20. ...
  21. where 'n01440764' is the unique synset label associated with
  22. these images.
  23. The training data set consists of 1000 sub-directories (i.e. labels)
  24. each containing 1200 JPEG images for a total of 1.2M JPEG images.
  25. The evaluation data set consists of 1000 sub-directories (i.e. labels)
  26. each containing 50 JPEG images for a total of 50K JPEG images.
  27. This TensorFlow script converts the training and evaluation data into
  28. a sharded data set consisting of 1024 and 128 TFRecord files, respectively.
  29. train_directory/train-00000-of-01024
  30. train_directory/train-00001-of-01024
  31. ...
  32. train_directory/train-00127-of-01024
  33. and
  34. validation_directory/validation-00000-of-00128
  35. validation_directory/validation-00001-of-00128
  36. ...
  37. validation_directory/validation-00127-of-00128
  38. Each validation TFRecord file contains ~390 records. Each training TFREcord
  39. file contains ~1250 records. Each record within the TFRecord file is a
  40. serialized Example proto. The Example proto contains the following fields:
  41. image/encoded: string containing JPEG encoded image in RGB colorspace
  42. image/height: integer, image height in pixels
  43. image/width: integer, image width in pixels
  44. image/colorspace: string, specifying the colorspace, always 'RGB'
  45. image/channels: integer, specifying the number of channels, always 3
  46. image/format: string, specifying the format, always'JPEG'
  47. image/filename: string containing the basename of the image file
  48. e.g. 'n01440764_10026.JPEG' or 'ILSVRC2012_val_00000293.JPEG'
  49. image/class/label: integer specifying the index in a classification layer.
  50. The label ranges from [1, 1000] where 0 is not used.
  51. image/class/synset: string specifying the unique ID of the label,
  52. e.g. 'n01440764'
  53. image/class/text: string specifying the human-readable version of the label
  54. e.g. 'red fox, Vulpes vulpes'
  55. image/object/bbox/xmin: list of integers specifying the 0+ human annotated
  56. bounding boxes
  57. image/object/bbox/xmax: list of integers specifying the 0+ human annotated
  58. bounding boxes
  59. image/object/bbox/ymin: list of integers specifying the 0+ human annotated
  60. bounding boxes
  61. image/object/bbox/ymax: list of integers specifying the 0+ human annotated
  62. bounding boxes
  63. image/object/bbox/label: integer specifying the index in a classification
  64. layer. The label ranges from [1, 1000] where 0 is not used. Note this is
  65. always identical to the image label.
  66. Note that the length of xmin is identical to the length of xmax, ymin and ymax
  67. for each example.
  68. Running this script using 16 threads may take around ~2.5 hours on a HP Z420.
  69. """
  70. from __future__ import absolute_import
  71. from __future__ import division
  72. from __future__ import print_function
  73. from datetime import datetime
  74. import os
  75. import random
  76. import sys
  77. import threading
  78. import numpy as np
  79. import tensorflow as tf
  80. tf.app.flags.DEFINE_string('train_directory', '/tmp/',
  81. 'Training data directory')
  82. tf.app.flags.DEFINE_string('validation_directory', '/tmp/',
  83. 'Validation data directory')
  84. tf.app.flags.DEFINE_string('output_directory', '/tmp/',
  85. 'Output data directory')
  86. tf.app.flags.DEFINE_integer('train_shards', 1024,
  87. 'Number of shards in training TFRecord files.')
  88. tf.app.flags.DEFINE_integer('validation_shards', 128,
  89. 'Number of shards in validation TFRecord files.')
  90. tf.app.flags.DEFINE_integer('num_threads', 8,
  91. 'Number of threads to preprocess the images.')
  92. # The labels file contains a list of valid labels are held in this file.
  93. # Assumes that the file contains entries as such:
  94. # n01440764
  95. # n01443537
  96. # n01484850
  97. # where each line corresponds to a label expressed as a synset. We map
  98. # each synset contained in the file to an integer (based on the alphabetical
  99. # ordering). See below for details.
  100. tf.app.flags.DEFINE_string('labels_file',
  101. 'imagenet_lsvrc_2015_synsets.txt',
  102. 'Labels file')
  103. # This file containing mapping from synset to human-readable label.
  104. # Assumes each line of the file looks like:
  105. #
  106. # n02119247 black fox
  107. # n02119359 silver fox
  108. # n02119477 red fox, Vulpes fulva
  109. #
  110. # where each line corresponds to a unique mapping. Note that each line is
  111. # formatted as <synset>\t<human readable label>.
  112. tf.app.flags.DEFINE_string('imagenet_metadata_file',
  113. 'imagenet_metadata.txt',
  114. 'ImageNet metadata file')
  115. # This file is the output of process_bounding_box.py
  116. # Assumes each line of the file looks like:
  117. #
  118. # n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940
  119. #
  120. # where each line corresponds to one bounding box annotation associated
  121. # with an image. Each line can be parsed as:
  122. #
  123. # <JPEG file name>, <xmin>, <ymin>, <xmax>, <ymax>
  124. #
  125. # Note that there might exist mulitple bounding box annotations associated
  126. # with an image file.
  127. tf.app.flags.DEFINE_string('bounding_box_file',
  128. './imagenet_2012_bounding_boxes.csv',
  129. 'Bounding box file')
  130. FLAGS = tf.app.flags.FLAGS
  131. def _int64_feature(value):
  132. """Wrapper for inserting int64 features into Example proto."""
  133. if not isinstance(value, list):
  134. value = [value]
  135. return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
  136. def _float_feature(value):
  137. """Wrapper for inserting float features into Example proto."""
  138. if not isinstance(value, list):
  139. value = [value]
  140. return tf.train.Feature(float_list=tf.train.FloatList(value=value))
  141. def _bytes_feature(value):
  142. """Wrapper for inserting bytes features into Example proto."""
  143. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
  144. def _convert_to_example(filename, image_buffer, label, synset, human, bbox,
  145. height, width):
  146. """Build an Example proto for an example.
  147. Args:
  148. filename: string, path to an image file, e.g., '/path/to/example.JPG'
  149. image_buffer: string, JPEG encoding of RGB image
  150. label: integer, identifier for the ground truth for the network
  151. synset: string, unique WordNet ID specifying the label, e.g., 'n02323233'
  152. human: string, human-readable label, e.g., 'red fox, Vulpes vulpes'
  153. bbox: list of bounding boxes; each box is a list of integers
  154. specifying [xmin, ymin, xmax, ymax]. All boxes are assumed to belong to
  155. the same label as the image label.
  156. height: integer, image height in pixels
  157. width: integer, image width in pixels
  158. Returns:
  159. Example proto
  160. """
  161. xmin = []
  162. ymin = []
  163. xmax = []
  164. ymax = []
  165. for b in bbox:
  166. assert len(b) == 4
  167. # pylint: disable=expression-not-assigned
  168. [l.append(point) for l, point in zip([xmin, ymin, xmax, ymax], b)]
  169. # pylint: enable=expression-not-assigned
  170. colorspace = 'RGB'
  171. channels = 3
  172. image_format = 'JPEG'
  173. example = tf.train.Example(features=tf.train.Features(feature={
  174. 'image/height': _int64_feature(height),
  175. 'image/width': _int64_feature(width),
  176. 'image/colorspace': _bytes_feature(colorspace),
  177. 'image/channels': _int64_feature(channels),
  178. 'image/class/label': _int64_feature(label),
  179. 'image/class/synset': _bytes_feature(synset),
  180. 'image/class/text': _bytes_feature(human),
  181. 'image/object/bbox/xmin': _float_feature(xmin),
  182. 'image/object/bbox/xmax': _float_feature(xmax),
  183. 'image/object/bbox/ymin': _float_feature(ymin),
  184. 'image/object/bbox/ymax': _float_feature(ymax),
  185. 'image/object/bbox/label': _int64_feature([label] * len(xmin)),
  186. 'image/format': _bytes_feature(image_format),
  187. 'image/filename': _bytes_feature(os.path.basename(filename)),
  188. 'image/encoded': _bytes_feature(image_buffer)}))
  189. return example
  190. class ImageCoder(object):
  191. """Helper class that provides TensorFlow image coding utilities."""
  192. def __init__(self):
  193. # Create a single Session to run all image coding calls.
  194. self._sess = tf.Session()
  195. # Initializes function that converts PNG to JPEG data.
  196. self._png_data = tf.placeholder(dtype=tf.string)
  197. image = tf.image.decode_png(self._png_data, channels=3)
  198. self._png_to_jpeg = tf.image.encode_jpeg(image, format='rgb', quality=100)
  199. # Initializes function that converts CMYK JPEG data to RGB JPEG data.
  200. self._cmyk_data = tf.placeholder(dtype=tf.string)
  201. image = tf.image.decode_jpeg(self._cmyk_data, channels=0)
  202. self._cmyk_to_rgb = tf.image.encode_jpeg(image, format='rgb', quality=100)
  203. # Initializes function that decodes RGB JPEG data.
  204. self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
  205. self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
  206. def png_to_jpeg(self, image_data):
  207. return self._sess.run(self._png_to_jpeg,
  208. feed_dict={self._png_data: image_data})
  209. def cmyk_to_rgb(self, image_data):
  210. return self._sess.run(self._cmyk_to_rgb,
  211. feed_dict={self._cmyk_data: image_data})
  212. def decode_jpeg(self, image_data):
  213. image = self._sess.run(self._decode_jpeg,
  214. feed_dict={self._decode_jpeg_data: image_data})
  215. assert len(image.shape) == 3
  216. assert image.shape[2] == 3
  217. return image
  218. def _is_png(filename):
  219. """Determine if a file contains a PNG format image.
  220. Args:
  221. filename: string, path of the image file.
  222. Returns:
  223. boolean indicating if the image is a PNG.
  224. """
  225. # File list from:
  226. # https://groups.google.com/forum/embed/?place=forum/torch7#!topic/torch7/fOSTXHIESSU
  227. return 'n02105855_2933.JPEG' in filename
  228. def _is_cmyk(filename):
  229. """Determine if file contains a CMYK JPEG format image.
  230. Args:
  231. filename: string, path of the image file.
  232. Returns:
  233. boolean indicating if the image is a JPEG encoded with CMYK color space.
  234. """
  235. # File list from:
  236. # https://github.com/cytsai/ilsvrc-cmyk-image-list
  237. blacklist = ['n01739381_1309.JPEG', 'n02077923_14822.JPEG',
  238. 'n02447366_23489.JPEG', 'n02492035_15739.JPEG',
  239. 'n02747177_10752.JPEG', 'n03018349_4028.JPEG',
  240. 'n03062245_4620.JPEG', 'n03347037_9675.JPEG',
  241. 'n03467068_12171.JPEG', 'n03529860_11437.JPEG',
  242. 'n03544143_17228.JPEG', 'n03633091_5218.JPEG',
  243. 'n03710637_5125.JPEG', 'n03961711_5286.JPEG',
  244. 'n04033995_2932.JPEG', 'n04258138_17003.JPEG',
  245. 'n04264628_27969.JPEG', 'n04336792_7448.JPEG',
  246. 'n04371774_5854.JPEG', 'n04596742_4225.JPEG',
  247. 'n07583066_647.JPEG', 'n13037406_4650.JPEG']
  248. return filename.split('/')[-1] in blacklist
  249. def _process_image(filename, coder):
  250. """Process a single image file.
  251. Args:
  252. filename: string, path to an image file e.g., '/path/to/example.JPG'.
  253. coder: instance of ImageCoder to provide TensorFlow image coding utils.
  254. Returns:
  255. image_buffer: string, JPEG encoding of RGB image.
  256. height: integer, image height in pixels.
  257. width: integer, image width in pixels.
  258. """
  259. # Read the image file.
  260. image_data = tf.gfile.FastGFile(filename, 'r').read()
  261. # Clean the dirty data.
  262. if _is_png(filename):
  263. # 1 image is a PNG.
  264. print('Converting PNG to JPEG for %s' % filename)
  265. image_data = coder.png_to_jpeg(image_data)
  266. elif _is_cmyk(filename):
  267. # 22 JPEG images are in CMYK colorspace.
  268. print('Converting CMYK to RGB for %s' % filename)
  269. image_data = coder.cmyk_to_rgb(image_data)
  270. # Decode the RGB JPEG.
  271. image = coder.decode_jpeg(image_data)
  272. # Check that image converted to RGB
  273. assert len(image.shape) == 3
  274. height = image.shape[0]
  275. width = image.shape[1]
  276. assert image.shape[2] == 3
  277. return image_data, height, width
  278. def _process_image_files_batch(coder, thread_index, ranges, name, filenames,
  279. synsets, labels, humans, bboxes, num_shards):
  280. """Processes and saves list of images as TFRecord in 1 thread.
  281. Args:
  282. coder: instance of ImageCoder to provide TensorFlow image coding utils.
  283. thread_index: integer, unique batch to run index is within [0, len(ranges)).
  284. ranges: list of pairs of integers specifying ranges of each batches to
  285. analyze in parallel.
  286. name: string, unique identifier specifying the data set
  287. filenames: list of strings; each string is a path to an image file
  288. synsets: list of strings; each string is a unique WordNet ID
  289. labels: list of integer; each integer identifies the ground truth
  290. humans: list of strings; each string is a human-readable label
  291. bboxes: list of bounding boxes for each image. Note that each entry in this
  292. list might contain from 0+ entries corresponding to the number of bounding
  293. box annotations for the image.
  294. num_shards: integer number of shards for this data set.
  295. """
  296. # Each thread produces N shards where N = int(num_shards / num_threads).
  297. # For instance, if num_shards = 128, and the num_threads = 2, then the first
  298. # thread would produce shards [0, 64).
  299. num_threads = len(ranges)
  300. assert not num_shards % num_threads
  301. num_shards_per_batch = int(num_shards / num_threads)
  302. shard_ranges = np.linspace(ranges[thread_index][0],
  303. ranges[thread_index][1],
  304. num_shards_per_batch + 1).astype(int)
  305. num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0]
  306. counter = 0
  307. for s in xrange(num_shards_per_batch):
  308. # Generate a sharded version of the file name, e.g. 'train-00002-of-00010'
  309. shard = thread_index * num_shards_per_batch + s
  310. output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards)
  311. output_file = os.path.join(FLAGS.output_directory, output_filename)
  312. writer = tf.python_io.TFRecordWriter(output_file)
  313. shard_counter = 0
  314. files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)
  315. for i in files_in_shard:
  316. filename = filenames[i]
  317. label = labels[i]
  318. synset = synsets[i]
  319. human = humans[i]
  320. bbox = bboxes[i]
  321. image_buffer, height, width = _process_image(filename, coder)
  322. example = _convert_to_example(filename, image_buffer, label,
  323. synset, human, bbox,
  324. height, width)
  325. writer.write(example.SerializeToString())
  326. shard_counter += 1
  327. counter += 1
  328. if not counter % 1000:
  329. print('%s [thread %d]: Processed %d of %d images in thread batch.' %
  330. (datetime.now(), thread_index, counter, num_files_in_thread))
  331. sys.stdout.flush()
  332. print('%s [thread %d]: Wrote %d images to %s' %
  333. (datetime.now(), thread_index, shard_counter, output_file))
  334. sys.stdout.flush()
  335. shard_counter = 0
  336. print('%s [thread %d]: Wrote %d images to %d shards.' %
  337. (datetime.now(), thread_index, counter, num_files_in_thread))
  338. sys.stdout.flush()
  339. def _process_image_files(name, filenames, synsets, labels, humans,
  340. bboxes, num_shards):
  341. """Process and save list of images as TFRecord of Example protos.
  342. Args:
  343. name: string, unique identifier specifying the data set
  344. filenames: list of strings; each string is a path to an image file
  345. synsets: list of strings; each string is a unique WordNet ID
  346. labels: list of integer; each integer identifies the ground truth
  347. humans: list of strings; each string is a human-readable label
  348. bboxes: list of bounding boxes for each image. Note that each entry in this
  349. list might contain from 0+ entries corresponding to the number of bounding
  350. box annotations for the image.
  351. num_shards: integer number of shards for this data set.
  352. """
  353. assert len(filenames) == len(synsets)
  354. assert len(filenames) == len(labels)
  355. assert len(filenames) == len(humans)
  356. assert len(filenames) == len(bboxes)
  357. # Break all images into batches with a [ranges[i][0], ranges[i][1]].
  358. spacing = np.linspace(0, len(filenames), FLAGS.num_threads + 1).astype(np.int)
  359. ranges = []
  360. threads = []
  361. for i in xrange(len(spacing) - 1):
  362. ranges.append([spacing[i], spacing[i+1]])
  363. # Launch a thread for each batch.
  364. print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges))
  365. sys.stdout.flush()
  366. # Create a mechanism for monitoring when all threads are finished.
  367. coord = tf.train.Coordinator()
  368. # Create a generic TensorFlow-based utility for converting all image codings.
  369. coder = ImageCoder()
  370. threads = []
  371. for thread_index in xrange(len(ranges)):
  372. args = (coder, thread_index, ranges, name, filenames,
  373. synsets, labels, humans, bboxes, num_shards)
  374. t = threading.Thread(target=_process_image_files_batch, args=args)
  375. t.start()
  376. threads.append(t)
  377. # Wait for all the threads to terminate.
  378. coord.join(threads)
  379. print('%s: Finished writing all %d images in data set.' %
  380. (datetime.now(), len(filenames)))
  381. sys.stdout.flush()
  382. def _find_image_files(data_dir, labels_file):
  383. """Build a list of all images files and labels in the data set.
  384. Args:
  385. data_dir: string, path to the root directory of images.
  386. Assumes that the ImageNet data set resides in JPEG files located in
  387. the following directory structure.
  388. data_dir/n01440764/ILSVRC2012_val_00000293.JPEG
  389. data_dir/n01440764/ILSVRC2012_val_00000543.JPEG
  390. where 'n01440764' is the unique synset label associated with these images.
  391. labels_file: string, path to the labels file.
  392. The list of valid labels are held in this file. Assumes that the file
  393. contains entries as such:
  394. n01440764
  395. n01443537
  396. n01484850
  397. where each line corresponds to a label expressed as a synset. We map
  398. each synset contained in the file to an integer (based on the alphabetical
  399. ordering) starting with the integer 1 corresponding to the synset
  400. contained in the first line.
  401. The reason we start the integer labels at 1 is to reserve label 0 as an
  402. unused background class.
  403. Returns:
  404. filenames: list of strings; each string is a path to an image file.
  405. synsets: list of strings; each string is a unique WordNet ID.
  406. labels: list of integer; each integer identifies the ground truth.
  407. """
  408. print('Determining list of input files and labels from %s.' % data_dir)
  409. challenge_synsets = [l.strip() for l in
  410. tf.gfile.FastGFile(labels_file, 'r').readlines()]
  411. labels = []
  412. filenames = []
  413. synsets = []
  414. # Leave label index 0 empty as a background class.
  415. label_index = 1
  416. # Construct the list of JPEG files and labels.
  417. for synset in challenge_synsets:
  418. jpeg_file_path = '%s/%s/*.JPEG' % (data_dir, synset)
  419. matching_files = tf.gfile.Glob(jpeg_file_path)
  420. labels.extend([label_index] * len(matching_files))
  421. synsets.extend([synset] * len(matching_files))
  422. filenames.extend(matching_files)
  423. if not label_index % 100:
  424. print('Finished finding files in %d of %d classes.' % (
  425. label_index, len(challenge_synsets)))
  426. label_index += 1
  427. # Shuffle the ordering of all image files in order to guarantee
  428. # random ordering of the images with respect to label in the
  429. # saved TFRecord files. Make the randomization repeatable.
  430. shuffled_index = range(len(filenames))
  431. random.seed(12345)
  432. random.shuffle(shuffled_index)
  433. filenames = [filenames[i] for i in shuffled_index]
  434. synsets = [synsets[i] for i in shuffled_index]
  435. labels = [labels[i] for i in shuffled_index]
  436. print('Found %d JPEG files across %d labels inside %s.' %
  437. (len(filenames), len(challenge_synsets), data_dir))
  438. return filenames, synsets, labels
  439. def _find_human_readable_labels(synsets, synset_to_human):
  440. """Build a list of human-readable labels.
  441. Args:
  442. synsets: list of strings; each string is a unique WordNet ID.
  443. synset_to_human: dict of synset to human labels, e.g.,
  444. 'n02119022' --> 'red fox, Vulpes vulpes'
  445. Returns:
  446. List of human-readable strings corresponding to each synset.
  447. """
  448. humans = []
  449. for s in synsets:
  450. assert s in synset_to_human, ('Failed to find: %s' % s)
  451. humans.append(synset_to_human[s])
  452. return humans
  453. def _find_image_bounding_boxes(filenames, image_to_bboxes):
  454. """Find the bounding boxes for a given image file.
  455. Args:
  456. filenames: list of strings; each string is a path to an image file.
  457. image_to_bboxes: dictionary mapping image file names to a list of
  458. bounding boxes. This list contains 0+ bounding boxes.
  459. Returns:
  460. List of bounding boxes for each image. Note that each entry in this
  461. list might contain from 0+ entries corresponding to the number of bounding
  462. box annotations for the image.
  463. """
  464. num_image_bbox = 0
  465. bboxes = []
  466. for f in filenames:
  467. basename = os.path.basename(f)
  468. if basename in image_to_bboxes:
  469. bboxes.append(image_to_bboxes[basename])
  470. num_image_bbox += 1
  471. else:
  472. bboxes.append([])
  473. print('Found %d images with bboxes out of %d images' % (
  474. num_image_bbox, len(filenames)))
  475. return bboxes
  476. def _process_dataset(name, directory, num_shards, synset_to_human,
  477. image_to_bboxes):
  478. """Process a complete data set and save it as a TFRecord.
  479. Args:
  480. name: string, unique identifier specifying the data set.
  481. directory: string, root path to the data set.
  482. num_shards: integer number of shards for this data set.
  483. synset_to_human: dict of synset to human labels, e.g.,
  484. 'n02119022' --> 'red fox, Vulpes vulpes'
  485. image_to_bboxes: dictionary mapping image file names to a list of
  486. bounding boxes. This list contains 0+ bounding boxes.
  487. """
  488. filenames, synsets, labels = _find_image_files(directory, FLAGS.labels_file)
  489. humans = _find_human_readable_labels(synsets, synset_to_human)
  490. bboxes = _find_image_bounding_boxes(filenames, image_to_bboxes)
  491. _process_image_files(name, filenames, synsets, labels,
  492. humans, bboxes, num_shards)
  493. def _build_synset_lookup(imagenet_metadata_file):
  494. """Build lookup for synset to human-readable label.
  495. Args:
  496. imagenet_metadata_file: string, path to file containing mapping from
  497. synset to human-readable label.
  498. Assumes each line of the file looks like:
  499. n02119247 black fox
  500. n02119359 silver fox
  501. n02119477 red fox, Vulpes fulva
  502. where each line corresponds to a unique mapping. Note that each line is
  503. formatted as <synset>\t<human readable label>.
  504. Returns:
  505. Dictionary of synset to human labels, such as:
  506. 'n02119022' --> 'red fox, Vulpes vulpes'
  507. """
  508. lines = tf.gfile.FastGFile(imagenet_metadata_file, 'r').readlines()
  509. synset_to_human = {}
  510. for l in lines:
  511. if l:
  512. parts = l.strip().split('\t')
  513. assert len(parts) == 2
  514. synset = parts[0]
  515. human = parts[1]
  516. synset_to_human[synset] = human
  517. return synset_to_human
  518. def _build_bounding_box_lookup(bounding_box_file):
  519. """Build a lookup from image file to bounding boxes.
  520. Args:
  521. bounding_box_file: string, path to file with bounding boxes annotations.
  522. Assumes each line of the file looks like:
  523. n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940
  524. where each line corresponds to one bounding box annotation associated
  525. with an image. Each line can be parsed as:
  526. <JPEG file name>, <xmin>, <ymin>, <xmax>, <ymax>
  527. Note that there might exist mulitple bounding box annotations associated
  528. with an image file. This file is the output of process_bounding_boxes.py.
  529. Returns:
  530. Dictionary mapping image file names to a list of bounding boxes. This list
  531. contains 0+ bounding boxes.
  532. """
  533. lines = tf.gfile.FastGFile(bounding_box_file, 'r').readlines()
  534. images_to_bboxes = {}
  535. num_bbox = 0
  536. num_image = 0
  537. for l in lines:
  538. if l:
  539. parts = l.split(',')
  540. assert len(parts) == 5, ('Failed to parse: %s' % l)
  541. filename = parts[0]
  542. xmin = float(parts[1])
  543. ymin = float(parts[2])
  544. xmax = float(parts[3])
  545. ymax = float(parts[4])
  546. box = [xmin, ymin, xmax, ymax]
  547. if filename not in images_to_bboxes:
  548. images_to_bboxes[filename] = []
  549. num_image += 1
  550. images_to_bboxes[filename].append(box)
  551. num_bbox += 1
  552. print('Successfully read %d bounding boxes '
  553. 'across %d images.' % (num_bbox, num_image))
  554. return images_to_bboxes
  555. def main(unused_argv):
  556. assert not FLAGS.train_shards % FLAGS.num_threads, (
  557. 'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards')
  558. assert not FLAGS.validation_shards % FLAGS.num_threads, (
  559. 'Please make the FLAGS.num_threads commensurate with '
  560. 'FLAGS.validation_shards')
  561. print('Saving results to %s' % FLAGS.output_directory)
  562. # Build a map from synset to human-readable label.
  563. synset_to_human = _build_synset_lookup(FLAGS.imagenet_metadata_file)
  564. image_to_bboxes = _build_bounding_box_lookup(FLAGS.bounding_box_file)
  565. # Run it!
  566. _process_dataset('validation', FLAGS.validation_directory,
  567. FLAGS.validation_shards, synset_to_human, image_to_bboxes)
  568. _process_dataset('train', FLAGS.train_directory, FLAGS.train_shards,
  569. synset_to_human, image_to_bboxes)
  570. if __name__ == '__main__':
  571. tf.app.run()