tfexample_utils.py 11.4 KB
Newer Older
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
1
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
# Copyright 2022 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.

"""Utility functions to create tf.Example and tf.SequnceExample for test.

Example:video classification end-to-end test
i.e. from reading input file to train and eval.

```python
class FooTrainTest(tf.test.TestCase):

  def setUp(self):
    super(TrainTest, self).setUp()

    # Write the fake tf.train.SequenceExample to file for test.
    data_dir = os.path.join(self.get_temp_dir(), 'data')
    tf.io.gfile.makedirs(data_dir)
    self._data_path = os.path.join(data_dir, 'data.tfrecord')
    examples = [
        tfexample_utils.make_video_test_example(
            image_shape=(36, 36, 3),
            audio_shape=(20, 128),
            label=random.randint(0, 100)) for _ in range(2)
    ]
    tfexample_utils.dump_to_tfrecord(self._data_path, tf_examples=examples)

  def test_foo(self):
    dataset = tf.data.TFRecordDataset(self._data_path)
    ...

```

"""
from typing import Sequence, Union

import numpy as np
import tensorflow as tf

Jiageng Zhang's avatar
Jiageng Zhang committed
50
51
52
53
54
from official.core import file_writers
from official.vision.data import fake_feature_generator
from official.vision.data import image_utils
from official.vision.data import tf_example_builder

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
55
56
IMAGE_KEY = 'image/encoded'
CLASSIFICATION_LABEL_KEY = 'image/class/label'
Jiageng Zhang's avatar
Jiageng Zhang committed
57
DISTILLATION_LABEL_KEY = 'image/class/soft_labels'
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
58
59
LABEL_KEY = 'clip/label/index'
AUDIO_KEY = 'features/audio'
Jiageng Zhang's avatar
Jiageng Zhang committed
60
DUMP_SOURCE_ID = b'7435790'
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
61
62


Jiageng Zhang's avatar
Jiageng Zhang committed
63
64
def encode_image(image_array: np.ndarray, fmt: str) -> bytes:
  return image_utils.encode_image(image_array, fmt)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
65
66
67
68


def make_image_bytes(shape: Sequence[int], fmt: str = 'JPEG') -> bytes:
  """Generates image and return bytes in specified format."""
Jiageng Zhang's avatar
Jiageng Zhang committed
69
70
  image = fake_feature_generator.generate_image_np(*shape)
  return encode_image(image, fmt=fmt)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
71
72
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
116


def put_int64_to_context(seq_example: tf.train.SequenceExample,
                         label: int = 0,
                         key: str = LABEL_KEY):
  """Puts int64 to SequenceExample context with key."""
  seq_example.context.feature[key].int64_list.value[:] = [label]


def put_bytes_list_to_feature(seq_example: tf.train.SequenceExample,
                              raw_image_bytes: bytes,
                              key: str = IMAGE_KEY,
                              repeat_num: int = 2):
  """Puts bytes list to SequenceExample context with key."""
  for _ in range(repeat_num):
    seq_example.feature_lists.feature_list.get_or_create(
        key).feature.add().bytes_list.value[:] = [raw_image_bytes]


def put_float_list_to_feature(seq_example: tf.train.SequenceExample,
                              value: Sequence[Sequence[float]], key: str):
  """Puts float list to SequenceExample context with key."""
  for s in value:
    seq_example.feature_lists.feature_list.get_or_create(
        key).feature.add().float_list.value[:] = s


def make_video_test_example(image_shape: Sequence[int] = (263, 320, 3),
                            audio_shape: Sequence[int] = (10, 256),
                            label: int = 42):
  """Generates data for testing video models (inc. RGB, audio, & label)."""
  raw_image_bytes = make_image_bytes(shape=image_shape)
  random_audio = np.random.normal(size=audio_shape).tolist()

  seq_example = tf.train.SequenceExample()
  put_int64_to_context(seq_example, label=label, key=LABEL_KEY)
  put_bytes_list_to_feature(
      seq_example, raw_image_bytes, key=IMAGE_KEY, repeat_num=4)

  put_float_list_to_feature(seq_example, value=random_audio, key=AUDIO_KEY)
  return seq_example


def dump_to_tfrecord(record_file: str,
                     tf_examples: Sequence[Union[tf.train.Example,
                                                 tf.train.SequenceExample]]):
Jiageng Zhang's avatar
Jiageng Zhang committed
117
  """Writes serialized Example to TFRecord file with path.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
118

Jiageng Zhang's avatar
Jiageng Zhang committed
119
  Note that examples are expected to be not seriazlied.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
120

Jiageng Zhang's avatar
Jiageng Zhang committed
121
122
123
124
125
  Args:
    record_file: The name of the output file.
    tf_examples: A list of examples to be stored.
  """
  file_writers.write_small_dataset(tf_examples, record_file, 'tfrecord')
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
126
127
128
129
130
131


def create_classification_example(
    image_height: int,
    image_width: int,
    image_format: str = 'JPEG',
Jiageng Zhang's avatar
Jiageng Zhang committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    is_multilabel: bool = False,
    output_serialized_example: bool = True) -> tf.train.Example:
  """Creates image and labels for image classification input pipeline.

  Args:
    image_height: The height of test image.
    image_width: The width of test image.
    image_format: The format of test image.
    is_multilabel: A boolean flag represents whether the test image can have
      multiple labels.
    output_serialized_example: A boolean flag represents whether to return a
      serialized example.

  Returns:
    A tf.train.Example for testing.
  """
  image = fake_feature_generator.generate_image_np(image_height, image_width)
  labels = fake_feature_generator.generate_classes_np(2,
                                                      int(is_multilabel) +
                                                      1).tolist()
  builder = tf_example_builder.TfExampleBuilder()
  example = builder.add_image_matrix_feature(image,
                                             image_format).add_ints_feature(
                                                 CLASSIFICATION_LABEL_KEY,
                                                 labels).example
  if output_serialized_example:
    return example.SerializeToString()
  return example
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
160
161
162
163
164
165


def create_distillation_example(
    image_height: int,
    image_width: int,
    num_labels: int,
Jiageng Zhang's avatar
Jiageng Zhang committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    image_format: str = 'JPEG',
    output_serialized_example: bool = True) -> tf.train.Example:
  """Creates image and labels for image classification with distillation.

  Args:
    image_height: The height of test image.
    image_width: The width of test image.
    num_labels: The number of labels used in test image.
    image_format: The format of test image.
    output_serialized_example: A boolean flag represents whether to return a
      serialized example.

  Returns:
    A tf.train.Example for testing.
  """
  image = fake_feature_generator.generate_image_np(image_height, image_width)
  labels = fake_feature_generator.generate_classes_np(2, 1).tolist()
  soft_labels = (fake_feature_generator.generate_classes_np(1, num_labels) +
                 0.6).tolist()
  builder = tf_example_builder.TfExampleBuilder()
  example = builder.add_image_matrix_feature(image,
                                             image_format).add_ints_feature(
                                                 CLASSIFICATION_LABEL_KEY,
                                                 labels).add_floats_feature(
                                                     DISTILLATION_LABEL_KEY,
                                                     soft_labels).example
  if output_serialized_example:
    return example.SerializeToString()
  return example


def create_3d_image_test_example(
    image_height: int,
    image_width: int,
    image_volume: int,
    image_channel: int,
    output_serialized_example: bool = False) -> tf.train.Example:
  """Creates 3D image and label.

  Args:
    image_height: The height of test 3D image.
    image_width: The width of test 3D image.
    image_volume: The volume of test 3D image.
    image_channel: The channel of test 3D image.
    output_serialized_example: A boolean flag represents whether to return a
      serialized example.

  Returns:
    A tf.train.Example for testing.
  """
  image = fake_feature_generator.generate_image_np(image_height, image_width,
                                                   image_channel)
  images = image[:, :, np.newaxis, :]
  images = np.tile(images, [1, 1, image_volume, 1]).astype(np.float32)

  shape = [image_height, image_width, image_volume, image_channel]
  labels = fake_feature_generator.generate_classes_np(
      2, np.prod(shape)).reshape(shape).astype(np.float32)

  builder = tf_example_builder.TfExampleBuilder()
  example = builder.add_bytes_feature(IMAGE_KEY,
                                      images.tobytes()).add_bytes_feature(
                                          CLASSIFICATION_LABEL_KEY,
                                          labels.tobytes()).example
  if output_serialized_example:
    return example.SerializeToString()
  return example
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
233
234


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
235
236
237
238
239
def create_detection_test_example(
    image_height: int,
    image_width: int,
    image_channel: int,
    num_instances: int,
Jiageng Zhang's avatar
Jiageng Zhang committed
240
241
    fill_image_size: bool = True,
    output_serialized_example: bool = False) -> tf.train.Example:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
242
243
244
245
246
247
248
  """Creates and returns a test example containing box and mask annotations.

  Args:
    image_height: The height of test image.
    image_width: The width of test image.
    image_channel: The channel of test image.
    num_instances: The number of object instances per image.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
249
    fill_image_size: If image height and width will be added to the example.
Jiageng Zhang's avatar
Jiageng Zhang committed
250
251
    output_serialized_example: A boolean flag represents whether to return a
      serialized example.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
252
253
254
255

  Returns:
    A tf.train.Example for testing.
  """
Jiageng Zhang's avatar
Jiageng Zhang committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
  image = fake_feature_generator.generate_image_np(image_height, image_width,
                                                   image_channel)
  boxes = fake_feature_generator.generate_normalized_boxes_np(num_instances)
  ymins, xmins, ymaxs, xmaxs = boxes.T.tolist()
  is_crowds = [0] * num_instances
  labels = fake_feature_generator.generate_classes_np(
      2, size=num_instances).tolist()
  labels_text = [b'class_1'] * num_instances
  masks = fake_feature_generator.generate_instance_masks_np(
      image_height, image_width, boxes)

  builder = tf_example_builder.TfExampleBuilder()

  example = builder.add_image_matrix_feature(image).add_boxes_feature(
      xmins, xmaxs, ymins, ymaxs,
      labels).add_instance_mask_matrices_feature(masks).add_ints_feature(
          'image/object/is_crowd',
          is_crowds).add_bytes_feature('image/object/class/text',
                                       labels_text).example
  if not fill_image_size:
    del example.features.feature['image/height']
    del example.features.feature['image/width']

  if output_serialized_example:
    return example.SerializeToString()
  return example


def create_segmentation_test_example(
    image_height: int,
    image_width: int,
    image_channel: int,
    output_serialized_example: bool = False) -> tf.train.Example:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
289
290
291
292
293
294
  """Creates and returns a test example containing mask annotations.

  Args:
    image_height: The height of test image.
    image_width: The width of test image.
    image_channel: The channel of test image.
Jiageng Zhang's avatar
Jiageng Zhang committed
295
296
    output_serialized_example: A boolean flag represents whether to return a
      serialized example.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
297
298
299
300

  Returns:
    A tf.train.Example for testing.
  """
Jiageng Zhang's avatar
Jiageng Zhang committed
301
302
303
304
305
306
307
308
309
310
  image = fake_feature_generator.generate_image_np(image_height, image_width,
                                                   image_channel)
  mask = fake_feature_generator.generate_semantic_mask_np(
      image_height, image_width, 3)
  builder = tf_example_builder.TfExampleBuilder()
  example = builder.add_image_matrix_feature(
      image).add_semantic_mask_matrix_feature(mask).example
  if output_serialized_example:
    return example.SerializeToString()
  return example