build_cityscapes_data.py 6.52 KB
Newer Older
1
# Lint as: python2, python3
yukun's avatar
yukun committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
53
54
55
56
57
58
59
60
61
62
# 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.
# ==============================================================================

"""Converts Cityscapes data to TFRecord file format with Example protos.

The Cityscapes dataset is expected to have the following directory structure:

  + cityscapes
     - build_cityscapes_data.py (current working directiory).
     - build_data.py
     + cityscapesscripts
       + annotation
       + evaluation
       + helpers
       + preparation
       + viewer
     + gtFine
       + train
       + val
       + test
     + leftImg8bit
       + train
       + val
       + test
     + tfrecord

This script converts data into sharded data files and save at tfrecord folder.

Note that before running this script, the users should (1) register the
Cityscapes dataset website at https://www.cityscapes-dataset.com to
download the dataset, and (2) run the script provided by Cityscapes
`preparation/createTrainIdLabelImgs.py` to generate the training groundtruth.

Also note that the tensorflow model will be trained with `TrainId' instead
of `EvalId' used on the evaluation server. Thus, the users need to convert
the predicted labels to `EvalId` for evaluation on the server. See the
vis.py for more details.

The Example proto contains the following fields:

  image/encoded: encoded image content.
  image/filename: image filename.
  image/format: image file format.
  image/height: image height.
  image/width: image width.
  image/channels: image channels.
  image/segmentation/class/encoded: encoded semantic segmentation content.
  image/segmentation/class/format: semantic segmentation file format.
"""
63
64
65
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
yukun's avatar
yukun committed
66
67
68
69
70
71
import glob
import math
import os.path
import re
import sys
import build_data
72
from six.moves import range
yukun's avatar
yukun committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string('cityscapes_root',
                           './cityscapes',
                           'Cityscapes dataset root folder.')

tf.app.flags.DEFINE_string(
    'output_dir',
    './tfrecord',
    'Path to save converted SSTable of TensorFlow examples.')


_NUM_SHARDS = 10

# A map from data type to folder name that saves the data.
_FOLDERS_MAP = {
    'image': 'leftImg8bit',
    'label': 'gtFine',
}

# A map from data type to filename postfix.
_POSTFIX_MAP = {
    'image': '_leftImg8bit',
    'label': '_gtFine_labelTrainIds',
}

# A map from data type to data format.
_DATA_FORMAT_MAP = {
    'image': 'png',
    'label': 'png',
}

# Image file pattern.
_IMAGE_FILENAME_RE = re.compile('(.+)' + _POSTFIX_MAP['image'])


def _get_files(data, dataset_split):
  """Gets files for the specified data type and dataset split.

  Args:
    data: String, desired data ('image' or 'label').
116
    dataset_split: String, dataset split ('train_fine', 'val_fine', 'test_fine')
yukun's avatar
yukun committed
117
118
119
120
121

  Returns:
    A list of sorted file names or None when getting label for
      test set.
  """
122
123
124
125
126
127
128
129
  if dataset_split == 'train_fine':
    split_dir = 'train'
  elif dataset_split == 'val_fine':
    split_dir = 'val'
  elif dataset_split == 'test_fine':
    split_dir = 'test'
  else:
    raise RuntimeError("Split {} is not supported".format(dataset_split))
yukun's avatar
yukun committed
130
131
  pattern = '*%s.%s' % (_POSTFIX_MAP[data], _DATA_FORMAT_MAP[data])
  search_files = os.path.join(
132
      FLAGS.cityscapes_root, _FOLDERS_MAP[data], split_dir, '*', pattern)
yukun's avatar
yukun committed
133
134
135
136
137
138
139
140
  filenames = glob.glob(search_files)
  return sorted(filenames)


def _convert_dataset(dataset_split):
  """Converts the specified dataset split to TFRecord format.

  Args:
141
    dataset_split: The dataset split (e.g., train_fine, val_fine).
yukun's avatar
yukun committed
142
143
144
145
146
147
148
149
150

  Raises:
    RuntimeError: If loaded image and label have different shape, or if the
      image file with specified postfix could not be found.
  """
  image_files = _get_files('image', dataset_split)
  label_files = _get_files('label', dataset_split)

  num_images = len(image_files)
151
  num_labels = len(label_files)
152
  num_per_shard = int(math.ceil(num_images / _NUM_SHARDS))
yukun's avatar
yukun committed
153

154
155
156
  if num_images != num_labels:
    raise RuntimeError("The number of images and labels doesn't match: {} {}".format(num_images, num_labels))

yukun's avatar
yukun committed
157
158
159
160
  image_reader = build_data.ImageReader('png', channels=3)
  label_reader = build_data.ImageReader('png', channels=1)

  for shard_id in range(_NUM_SHARDS):
161
    shard_filename = '%s-%05d-of-%05d.tfrecord' % (
yukun's avatar
yukun committed
162
163
164
165
166
167
168
169
170
171
        dataset_split, shard_id, _NUM_SHARDS)
    output_filename = os.path.join(FLAGS.output_dir, shard_filename)
    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.
172
        image_data = tf.gfile.FastGFile(image_files[i], 'rb').read()
yukun's avatar
yukun committed
173
174
        height, width = image_reader.read_image_dims(image_data)
        # Read the semantic segmentation annotation.
175
        seg_data = tf.gfile.FastGFile(label_files[i], 'rb').read()
yukun's avatar
yukun committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
        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.
        re_match = _IMAGE_FILENAME_RE.search(image_files[i])
        if re_match is None:
          raise RuntimeError('Invalid image filename: ' + image_files[i])
        filename = os.path.basename(re_match.group(1))
        example = build_data.image_seg_to_tfexample(
            image_data, filename, height, width, seg_data)
        tfrecord_writer.write(example.SerializeToString())
    sys.stdout.write('\n')
    sys.stdout.flush()


def main(unused_argv):
192
193
  # Only support converting 'train_fine', 'val_fine' and 'test_fine' sets for now.
  for dataset_split in ['train_fine', 'val_fine', 'test_fine']:
yukun's avatar
yukun committed
194
195
196
197
198
    _convert_dataset(dataset_split)


if __name__ == '__main__':
  tf.app.run()