build_ade20k_data.py 4.31 KB
Newer Older
1
# Lint as: python2, python3
Yubin Ruan's avatar
Yubin Ruan committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

17
18
"""Converts ADE20K data to TFRecord file format with Example protos."""

19
20
21
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
Yubin Ruan's avatar
Yubin Ruan committed
22
23
24
25
26
import math
import os
import random
import sys
import build_data
27
from six.moves import range
Yubin Ruan's avatar
Yubin Ruan committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string(
    'train_image_folder',
    './ADE20K/ADEChallengeData2016/images/training',
    'Folder containing trainng images')
tf.app.flags.DEFINE_string(
    'train_image_label_folder',
    './ADE20K/ADEChallengeData2016/annotations/training',
    'Folder containing annotations for trainng images')

tf.app.flags.DEFINE_string(
    'val_image_folder',
    './ADE20K/ADEChallengeData2016/images/validation',
    'Folder containing validation images')

tf.app.flags.DEFINE_string(
    'val_image_label_folder',
    './ADE20K/ADEChallengeData2016/annotations/validation',
    'Folder containing annotations for validation')

tf.app.flags.DEFINE_string(
    'output_dir', './ADE20K/tfrecord',
53
    'Path to save converted tfrecord of Tensorflow example')
Yubin Ruan's avatar
Yubin Ruan committed
54
55
56

_NUM_SHARDS = 4

57

Yubin Ruan's avatar
Yubin Ruan committed
58
def _convert_dataset(dataset_split, dataset_dir, dataset_label_dir):
59
  """Converts the ADE20k dataset into into tfrecord format.
Yubin Ruan's avatar
Yubin Ruan committed
60
61

  Args:
62
63
64
    dataset_split: Dataset split (e.g., train, val).
    dataset_dir: Dir in which the dataset locates.
    dataset_label_dir: Dir in which the annotations locates.
Yubin Ruan's avatar
Yubin Ruan committed
65
66
67
68
69

  Raises:
    RuntimeError: If loaded image and label have different shape.
  """

70
  img_names = tf.gfile.Glob(os.path.join(dataset_dir, '*.jpg'))
Yubin Ruan's avatar
Yubin Ruan committed
71
72
73
74
  random.shuffle(img_names)
  seg_names = []
  for f in img_names:
    # get the filename without the extension
75
    basename = os.path.basename(f).split('.')[0]
Yubin Ruan's avatar
Yubin Ruan committed
76
77
78
79
80
    # cover its corresponding *_seg.png
    seg = os.path.join(dataset_label_dir, basename+'.png')
    seg_names.append(seg)

  num_images = len(img_names)
81
  num_per_shard = int(math.ceil(num_images / _NUM_SHARDS))
Yubin Ruan's avatar
Yubin Ruan committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

  image_reader = build_data.ImageReader('jpeg', channels=3)
  label_reader = build_data.ImageReader('png', channels=1)

  for shard_id in range(_NUM_SHARDS):
    output_filename = os.path.join(
        FLAGS.output_dir,
        '%s-%05d-of-%05d.tfrecord' % (dataset_split, shard_id, _NUM_SHARDS))
    with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer:
      start_idx = shard_id * num_per_shard
      end_idx = min((shard_id + 1) * num_per_shard, num_images)
      for i in range(start_idx, end_idx):
        sys.stdout.write('\r>> Converting image %d/%d shard %d' % (
            i + 1, num_images, shard_id))
        sys.stdout.flush()
        # Read the image.
        image_filename = img_names[i]
99
        image_data = tf.gfile.FastGFile(image_filename, 'rb').read()
Yubin Ruan's avatar
Yubin Ruan committed
100
101
102
        height, width = image_reader.read_image_dims(image_data)
        # Read the semantic segmentation annotation.
        seg_filename = seg_names[i]
103
        seg_data = tf.gfile.FastGFile(seg_filename, 'rb').read()
Yubin Ruan's avatar
Yubin Ruan committed
104
105
106
107
108
109
110
111
112
113
        seg_height, seg_width = label_reader.read_image_dims(seg_data)
        if height != seg_height or width != seg_width:
          raise RuntimeError('Shape mismatched between image and label.')
        # Convert to tf example.
        example = build_data.image_seg_to_tfexample(
            image_data, img_names[i], height, width, seg_data)
        tfrecord_writer.write(example.SerializeToString())
    sys.stdout.write('\n')
    sys.stdout.flush()

114

Yubin Ruan's avatar
Yubin Ruan committed
115
116
def main(unused_argv):
  tf.gfile.MakeDirs(FLAGS.output_dir)
117
118
  _convert_dataset(
      'train', FLAGS.train_image_folder, FLAGS.train_image_label_folder)
Yubin Ruan's avatar
Yubin Ruan committed
119
120
  _convert_dataset('val', FLAGS.val_image_folder, FLAGS.val_image_label_folder)

121

Yubin Ruan's avatar
Yubin Ruan committed
122
123
if __name__ == '__main__':
  tf.app.run()