inputs_test.py 76.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright 2017 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.
# ==============================================================================
"""Tests for object_detection.tflearn.inputs."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

21
import functools
22
import os
23
import unittest
24
from absl import logging
pkulzc's avatar
pkulzc committed
25
from absl.testing import parameterized
26
import numpy as np
27
import six
28
import tensorflow.compat.v1 as tf
29
30

from object_detection import inputs
31
from object_detection.core import preprocessor
32
33
from object_detection.core import standard_fields as fields
from object_detection.utils import config_util
pkulzc's avatar
pkulzc committed
34
from object_detection.utils import test_case
35
36
37
38
39
40
41
from object_detection.utils import test_utils
from object_detection.utils import tf_version

if six.PY2:
  import mock  # pylint: disable=g-import-not-at-top
else:
  from unittest import mock  # pylint: disable=g-import-not-at-top, g-importing-member
42
43
44
45
46
47

FLAGS = tf.flags.FLAGS


def _get_configs_for_model(model_name):
  """Returns configurations for model."""
Zhichao Lu's avatar
Zhichao Lu committed
48
49
50
51
52
53
  fname = os.path.join(tf.resource_loader.get_data_files_path(),
                       'samples/configs/' + model_name + '.config')
  label_map_path = os.path.join(tf.resource_loader.get_data_files_path(),
                                'data/pet_label_map.pbtxt')
  data_path = os.path.join(tf.resource_loader.get_data_files_path(),
                           'test_data/pets_examples.record')
54
  configs = config_util.get_configs_from_pipeline_file(fname)
55
56
57
58
59
  override_dict = {
      'train_input_path': data_path,
      'eval_input_path': data_path,
      'label_map_path': label_map_path
  }
60
  return config_util.merge_external_params_with_configs(
61
      configs, kwargs_dict=override_dict)
62
63


64
def _get_configs_for_model_sequence_example(model_name, frame_index=-1):
65
66
67
68
69
70
71
72
73
74
75
76
  """Returns configurations for model."""
  fname = os.path.join(tf.resource_loader.get_data_files_path(),
                       'test_data/' + model_name + '.config')
  label_map_path = os.path.join(tf.resource_loader.get_data_files_path(),
                                'data/snapshot_serengeti_label_map.pbtxt')
  data_path = os.path.join(
      tf.resource_loader.get_data_files_path(),
      'test_data/snapshot_serengeti_sequence_examples.record')
  configs = config_util.get_configs_from_pipeline_file(fname)
  override_dict = {
      'train_input_path': data_path,
      'eval_input_path': data_path,
77
78
      'label_map_path': label_map_path,
      'frame_index': frame_index
79
80
81
82
83
  }
  return config_util.merge_external_params_with_configs(
      configs, kwargs_dict=override_dict)


84
85
86
87
88
89
90
91
92
def _make_initializable_iterator(dataset):
  """Creates an iterator, and initializes tables.

  Args:
    dataset: A `tf.data.Dataset` object.

  Returns:
    A `tf.data.Iterator`.
  """
93
  iterator = tf.data.make_initializable_iterator(dataset)
94
95
96
97
  tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS, iterator.initializer)
  return iterator


98
99
@unittest.skipIf(tf_version.is_tf2(), 'Skipping TF1.X only tests under TF2.X.')
class InputFnTest(test_case.TestCase, parameterized.TestCase):
100
101
102
103

  def test_faster_rcnn_resnet50_train_input(self):
    """Tests the training input function for FasterRcnnResnet50."""
    configs = _get_configs_for_model('faster_rcnn_resnet50_pets')
104
105
    model_config = configs['model']
    model_config.faster_rcnn.num_classes = 37
106
    train_input_fn = inputs.create_train_input_fn(
107
        configs['train_config'], configs['train_input_config'], model_config)
108
    features, labels = _make_initializable_iterator(train_input_fn()).get_next()
109

110
    self.assertAllEqual([1, None, None, 3],
111
112
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
113
    self.assertAllEqual([1],
114
115
116
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
117
        [1, 100, 4],
118
119
120
121
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
122
        [1, 100, model_config.faster_rcnn.num_classes],
123
124
125
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
126
127
128
129
130
    self.assertAllEqual(
        [1, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_weights].dtype)
131
132
133
134
135
136
    self.assertAllEqual(
        [1, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_confidences].shape.as_list())
    self.assertEqual(
        tf.float32,
        labels[fields.InputDataFields.groundtruth_confidences].dtype)
137

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
  def test_faster_rcnn_resnet50_train_input_with_additional_channels(self):
    """Tests the training input function for FasterRcnnResnet50."""
    configs = _get_configs_for_model('faster_rcnn_resnet50_pets')
    model_config = configs['model']
    configs['train_input_config'].num_additional_channels = 2
    configs['train_config'].retain_original_images = True
    model_config.faster_rcnn.num_classes = 37
    train_input_fn = inputs.create_train_input_fn(
        configs['train_config'], configs['train_input_config'], model_config)
    features, labels = _make_initializable_iterator(train_input_fn()).get_next()

    self.assertAllEqual([1, None, None, 5],
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertAllEqual(
        [1, None, None, 3],
        features[fields.InputDataFields.original_image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual([1],
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
        [1, 100, 4],
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
        [1, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
    self.assertAllEqual(
        [1, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_weights].dtype)
    self.assertAllEqual(
        [1, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_confidences].shape.as_list())
    self.assertEqual(
        tf.float32,
        labels[fields.InputDataFields.groundtruth_confidences].dtype)

pkulzc's avatar
pkulzc committed
180
181
182
183
184
  @parameterized.parameters(
      {'eval_batch_size': 1},
      {'eval_batch_size': 8}
  )
  def test_faster_rcnn_resnet50_eval_input(self, eval_batch_size=1):
185
186
    """Tests the eval input function for FasterRcnnResnet50."""
    configs = _get_configs_for_model('faster_rcnn_resnet50_pets')
187
188
    model_config = configs['model']
    model_config.faster_rcnn.num_classes = 37
pkulzc's avatar
pkulzc committed
189
190
    eval_config = configs['eval_config']
    eval_config.batch_size = eval_batch_size
191
    eval_input_fn = inputs.create_eval_input_fn(
pkulzc's avatar
pkulzc committed
192
        eval_config, configs['eval_input_configs'][0], model_config)
193
    features, labels = _make_initializable_iterator(eval_input_fn()).get_next()
pkulzc's avatar
pkulzc committed
194
    self.assertAllEqual([eval_batch_size, None, None, 3],
195
196
197
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
198
        [eval_batch_size, None, None, 3],
199
200
201
        features[fields.InputDataFields.original_image].shape.as_list())
    self.assertEqual(tf.uint8,
                     features[fields.InputDataFields.original_image].dtype)
pkulzc's avatar
pkulzc committed
202
203
    self.assertAllEqual([eval_batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
204
205
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
206
        [eval_batch_size, 100, 4],
207
208
209
210
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
211
        [eval_batch_size, 100, model_config.faster_rcnn.num_classes],
212
213
214
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
215
    self.assertAllEqual(
216
217
        [eval_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
218
219
    self.assertEqual(
        tf.float32,
220
        labels[fields.InputDataFields.groundtruth_weights].dtype)
221
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
222
        [eval_batch_size, 100],
223
224
225
226
        labels[fields.InputDataFields.groundtruth_area].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_area].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
227
        [eval_batch_size, 100],
228
229
230
231
        labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list())
    self.assertEqual(
        tf.bool, labels[fields.InputDataFields.groundtruth_is_crowd].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
232
        [eval_batch_size, 100],
233
234
235
        labels[fields.InputDataFields.groundtruth_difficult].shape.as_list())
    self.assertEqual(
        tf.int32, labels[fields.InputDataFields.groundtruth_difficult].dtype)
236

237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
289
290
291
292
293
  def test_context_rcnn_resnet50_train_input_with_sequence_example(
      self, train_batch_size=8):
    """Tests the training input function for FasterRcnnResnet50."""
    configs = _get_configs_for_model_sequence_example(
        'context_rcnn_camera_trap')
    model_config = configs['model']
    train_config = configs['train_config']
    train_config.batch_size = train_batch_size
    train_input_fn = inputs.create_train_input_fn(
        train_config, configs['train_input_config'], model_config)
    features, labels = _make_initializable_iterator(train_input_fn()).get_next()

    self.assertAllEqual([train_batch_size, 640, 640, 3],
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual([train_batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
        [train_batch_size, 100, 4],
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
        [train_batch_size, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
    self.assertAllEqual(
        [train_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_weights].dtype)
    self.assertAllEqual(
        [train_batch_size, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_confidences].shape.as_list())
    self.assertEqual(
        tf.float32,
        labels[fields.InputDataFields.groundtruth_confidences].dtype)

  def test_context_rcnn_resnet50_eval_input_with_sequence_example(
      self, eval_batch_size=8):
    """Tests the eval input function for FasterRcnnResnet50."""
    configs = _get_configs_for_model_sequence_example(
        'context_rcnn_camera_trap')
    model_config = configs['model']
    eval_config = configs['eval_config']
    eval_config.batch_size = eval_batch_size
    eval_input_fn = inputs.create_eval_input_fn(
        eval_config, configs['eval_input_configs'][0], model_config)
    features, labels = _make_initializable_iterator(eval_input_fn()).get_next()
    self.assertAllEqual([eval_batch_size, 640, 640, 3],
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual(
        [eval_batch_size, 640, 640, 3],
        features[fields.InputDataFields.original_image].shape.as_list())
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
    self.assertEqual(tf.uint8,
                     features[fields.InputDataFields.original_image].dtype)
    self.assertAllEqual([eval_batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100, 4],
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
    self.assertEqual(
        tf.float32,
        labels[fields.InputDataFields.groundtruth_weights].dtype)

  def test_context_rcnn_resnet50_eval_input_with_sequence_example_image_id_list(
      self, eval_batch_size=8):
    """Tests the eval input function for FasterRcnnResnet50."""
    configs = _get_configs_for_model_sequence_example(
        'context_rcnn_camera_trap')
    model_config = configs['model']
    eval_config = configs['eval_config']
    eval_config.batch_size = eval_batch_size
    eval_input_config = configs['eval_input_configs'][0]
    eval_input_config.load_context_image_ids = True
    eval_input_fn = inputs.create_eval_input_fn(
        eval_config, eval_input_config, model_config)
    features, labels = _make_initializable_iterator(eval_input_fn()).get_next()
    self.assertAllEqual([eval_batch_size, 640, 640, 3],
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual(
        [eval_batch_size, 640, 640, 3],
        features[fields.InputDataFields.original_image].shape.as_list())
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
    self.assertEqual(tf.uint8,
                     features[fields.InputDataFields.original_image].dtype)
    self.assertAllEqual([eval_batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100, 4],
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
    self.assertEqual(
        tf.float32,
        labels[fields.InputDataFields.groundtruth_weights].dtype)

357
  def test_context_rcnn_resnet50_train_input_with_sequence_example_frame_index(
358
      self, train_batch_size=8):
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    """Tests the training input function for FasterRcnnResnet50."""
    configs = _get_configs_for_model_sequence_example(
        'context_rcnn_camera_trap', frame_index=2)
    model_config = configs['model']
    train_config = configs['train_config']
    train_config.batch_size = train_batch_size
    train_input_fn = inputs.create_train_input_fn(
        train_config, configs['train_input_config'], model_config)
    features, labels = _make_initializable_iterator(train_input_fn()).get_next()

    self.assertAllEqual([train_batch_size, 640, 640, 3],
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual([train_batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
        [train_batch_size, 100, 4],
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
379
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
380
381
382
383
    self.assertAllEqual(
        [train_batch_size, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
384
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
385
386
387
388
    self.assertAllEqual(
        [train_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
    self.assertEqual(tf.float32,
389
                     labels[fields.InputDataFields.groundtruth_weights].dtype)
390
391
392
393
394
395
396
    self.assertAllEqual(
        [train_batch_size, 100, model_config.faster_rcnn.num_classes],
        labels[fields.InputDataFields.groundtruth_confidences].shape.as_list())
    self.assertEqual(
        tf.float32,
        labels[fields.InputDataFields.groundtruth_confidences].dtype)

397
398
399
  def test_ssd_inceptionV2_train_input(self):
    """Tests the training input function for SSDInceptionV2."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
400
401
    model_config = configs['model']
    model_config.ssd.num_classes = 37
402
403
    batch_size = configs['train_config'].batch_size
    train_input_fn = inputs.create_train_input_fn(
404
        configs['train_config'], configs['train_input_config'], model_config)
405
    features, labels = _make_initializable_iterator(train_input_fn()).get_next()
406
407
408
409
410
411
412
413
414
415
416
417
418

    self.assertAllEqual([batch_size, 300, 300, 3],
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual([batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
        [batch_size],
        labels[fields.InputDataFields.num_groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.int32,
                     labels[fields.InputDataFields.num_groundtruth_boxes].dtype)
    self.assertAllEqual(
419
        [batch_size, 100, 4],
420
421
422
423
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
424
        [batch_size, 100, model_config.ssd.num_classes],
425
426
427
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
428
    self.assertAllEqual(
429
        [batch_size, 100],
430
        labels[
431
            fields.InputDataFields.groundtruth_weights].shape.as_list())
432
433
    self.assertEqual(
        tf.float32,
434
        labels[fields.InputDataFields.groundtruth_weights].dtype)
435

pkulzc's avatar
pkulzc committed
436
437
438
439
440
  @parameterized.parameters(
      {'eval_batch_size': 1},
      {'eval_batch_size': 8}
  )
  def test_ssd_inceptionV2_eval_input(self, eval_batch_size=1):
441
442
    """Tests the eval input function for SSDInceptionV2."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
443
444
    model_config = configs['model']
    model_config.ssd.num_classes = 37
pkulzc's avatar
pkulzc committed
445
446
    eval_config = configs['eval_config']
    eval_config.batch_size = eval_batch_size
447
    eval_input_fn = inputs.create_eval_input_fn(
pkulzc's avatar
pkulzc committed
448
        eval_config, configs['eval_input_configs'][0], model_config)
449
    features, labels = _make_initializable_iterator(eval_input_fn()).get_next()
pkulzc's avatar
pkulzc committed
450
    self.assertAllEqual([eval_batch_size, 300, 300, 3],
451
452
453
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
454
        [eval_batch_size, 300, 300, 3],
455
456
457
        features[fields.InputDataFields.original_image].shape.as_list())
    self.assertEqual(tf.uint8,
                     features[fields.InputDataFields.original_image].dtype)
pkulzc's avatar
pkulzc committed
458
459
    self.assertAllEqual([eval_batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
460
461
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
462
        [eval_batch_size, 100, 4],
463
464
465
466
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
467
        [eval_batch_size, 100, model_config.ssd.num_classes],
468
469
470
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
471
    self.assertAllEqual(
472
        [eval_batch_size, 100],
473
        labels[
474
            fields.InputDataFields.groundtruth_weights].shape.as_list())
475
476
    self.assertEqual(
        tf.float32,
477
        labels[fields.InputDataFields.groundtruth_weights].dtype)
478
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
479
        [eval_batch_size, 100],
480
481
482
483
        labels[fields.InputDataFields.groundtruth_area].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_area].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
484
        [eval_batch_size, 100],
485
486
487
488
        labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list())
    self.assertEqual(
        tf.bool, labels[fields.InputDataFields.groundtruth_is_crowd].dtype)
    self.assertAllEqual(
pkulzc's avatar
pkulzc committed
489
        [eval_batch_size, 100],
490
491
492
        labels[fields.InputDataFields.groundtruth_difficult].shape.as_list())
    self.assertEqual(
        tf.int32, labels[fields.InputDataFields.groundtruth_difficult].dtype)
493

494
495
  def test_ssd_inceptionV2_eval_input_with_additional_channels(
      self, eval_batch_size=1):
496
    """Tests the eval input function for SSDInceptionV2 with additional channel.
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557

    Args:
      eval_batch_size: Batch size for eval set.
    """
    configs = _get_configs_for_model('ssd_inception_v2_pets')
    model_config = configs['model']
    model_config.ssd.num_classes = 37
    configs['eval_input_configs'][0].num_additional_channels = 1
    eval_config = configs['eval_config']
    eval_config.batch_size = eval_batch_size
    eval_config.retain_original_image_additional_channels = True
    eval_input_fn = inputs.create_eval_input_fn(
        eval_config, configs['eval_input_configs'][0], model_config)
    features, labels = _make_initializable_iterator(eval_input_fn()).get_next()
    self.assertAllEqual([eval_batch_size, 300, 300, 4],
                        features[fields.InputDataFields.image].shape.as_list())
    self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)
    self.assertAllEqual(
        [eval_batch_size, 300, 300, 3],
        features[fields.InputDataFields.original_image].shape.as_list())
    self.assertEqual(tf.uint8,
                     features[fields.InputDataFields.original_image].dtype)
    self.assertAllEqual([eval_batch_size, 300, 300, 1], features[
        fields.InputDataFields.image_additional_channels].shape.as_list())
    self.assertEqual(
        tf.uint8,
        features[fields.InputDataFields.image_additional_channels].dtype)
    self.assertAllEqual([eval_batch_size],
                        features[inputs.HASH_KEY].shape.as_list())
    self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100, 4],
        labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_boxes].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100, model_config.ssd.num_classes],
        labels[fields.InputDataFields.groundtruth_classes].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_classes].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_weights].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_area].shape.as_list())
    self.assertEqual(tf.float32,
                     labels[fields.InputDataFields.groundtruth_area].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list())
    self.assertEqual(tf.bool,
                     labels[fields.InputDataFields.groundtruth_is_crowd].dtype)
    self.assertAllEqual(
        [eval_batch_size, 100],
        labels[fields.InputDataFields.groundtruth_difficult].shape.as_list())
    self.assertEqual(tf.int32,
                     labels[fields.InputDataFields.groundtruth_difficult].dtype)

558
559
  def test_predict_input(self):
    """Tests the predict input function."""
560
561
    configs = _get_configs_for_model('ssd_inception_v2_pets')
    predict_input_fn = inputs.create_predict_input_fn(
562
        model_config=configs['model'],
563
        predict_input_config=configs['eval_input_configs'][0])
564
565
    serving_input_receiver = predict_input_fn()

566
    image = serving_input_receiver.features[fields.InputDataFields.image]
567
    receiver_tensors = serving_input_receiver.receiver_tensors[
568
569
        inputs.SERVING_FED_EXAMPLE_KEY]
    self.assertEqual([1, 300, 300, 3], image.shape.as_list())
570
571
572
    self.assertEqual(tf.float32, image.dtype)
    self.assertEqual(tf.string, receiver_tensors.dtype)

573
574
575
  def test_predict_input_with_additional_channels(self):
    """Tests the predict input function with additional channels."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
576
    configs['eval_input_configs'][0].num_additional_channels = 2
577
578
    predict_input_fn = inputs.create_predict_input_fn(
        model_config=configs['model'],
579
        predict_input_config=configs['eval_input_configs'][0])
580
581
582
583
584
585
586
587
588
589
    serving_input_receiver = predict_input_fn()

    image = serving_input_receiver.features[fields.InputDataFields.image]
    receiver_tensors = serving_input_receiver.receiver_tensors[
        inputs.SERVING_FED_EXAMPLE_KEY]
    # RGB + 2 additional channels = 5 channels.
    self.assertEqual([1, 300, 300, 5], image.shape.as_list())
    self.assertEqual(tf.float32, image.dtype)
    self.assertEqual(tf.string, receiver_tensors.dtype)

590
591
592
  def test_error_with_bad_train_config(self):
    """Tests that a TypeError is raised with improper train config."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
593
    configs['model'].ssd.num_classes = 37
594
595
    train_input_fn = inputs.create_train_input_fn(
        train_config=configs['eval_config'],  # Expecting `TrainConfig`.
596
597
        train_input_config=configs['train_input_config'],
        model_config=configs['model'])
598
599
600
601
602
603
    with self.assertRaises(TypeError):
      train_input_fn()

  def test_error_with_bad_train_input_config(self):
    """Tests that a TypeError is raised with improper train input config."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
604
605
606
607
608
609
610
611
612
613
614
615
    configs['model'].ssd.num_classes = 37
    train_input_fn = inputs.create_train_input_fn(
        train_config=configs['train_config'],
        train_input_config=configs['model'],  # Expecting `InputReader`.
        model_config=configs['model'])
    with self.assertRaises(TypeError):
      train_input_fn()

  def test_error_with_bad_train_model_config(self):
    """Tests that a TypeError is raised with improper train model config."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
    configs['model'].ssd.num_classes = 37
616
617
    train_input_fn = inputs.create_train_input_fn(
        train_config=configs['train_config'],
618
619
        train_input_config=configs['train_input_config'],
        model_config=configs['train_config'])  # Expecting `DetectionModel`.
620
621
622
623
624
625
    with self.assertRaises(TypeError):
      train_input_fn()

  def test_error_with_bad_eval_config(self):
    """Tests that a TypeError is raised with improper eval config."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
626
    configs['model'].ssd.num_classes = 37
627
628
    eval_input_fn = inputs.create_eval_input_fn(
        eval_config=configs['train_config'],  # Expecting `EvalConfig`.
629
        eval_input_config=configs['eval_input_configs'][0],
630
        model_config=configs['model'])
631
632
633
634
635
636
    with self.assertRaises(TypeError):
      eval_input_fn()

  def test_error_with_bad_eval_input_config(self):
    """Tests that a TypeError is raised with improper eval input config."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
637
    configs['model'].ssd.num_classes = 37
638
639
    eval_input_fn = inputs.create_eval_input_fn(
        eval_config=configs['eval_config'],
640
641
        eval_input_config=configs['model'],  # Expecting `InputReader`.
        model_config=configs['model'])
642
643
644
    with self.assertRaises(TypeError):
      eval_input_fn()

645
646
647
648
649
650
  def test_error_with_bad_eval_model_config(self):
    """Tests that a TypeError is raised with improper eval model config."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
    configs['model'].ssd.num_classes = 37
    eval_input_fn = inputs.create_eval_input_fn(
        eval_config=configs['eval_config'],
651
        eval_input_config=configs['eval_input_configs'][0],
652
653
654
655
        model_config=configs['eval_config'])  # Expecting `DetectionModel`.
    with self.assertRaises(TypeError):
      eval_input_fn()

656
657
658
659
660
  def test_output_equal_in_replace_empty_string_with_random_number(self):
    string_placeholder = tf.placeholder(tf.string, shape=[])
    replaced_string = inputs._replace_empty_string_with_random_number(
        string_placeholder)

661
    test_string = b'hello world'
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
    feed_dict = {string_placeholder: test_string}

    with self.test_session() as sess:
      out_string = sess.run(replaced_string, feed_dict=feed_dict)

    self.assertEqual(test_string, out_string)

  def test_output_is_integer_in_replace_empty_string_with_random_number(self):

    string_placeholder = tf.placeholder(tf.string, shape=[])
    replaced_string = inputs._replace_empty_string_with_random_number(
        string_placeholder)

    empty_string = ''
    feed_dict = {string_placeholder: empty_string}
    with self.test_session() as sess:
      out_string = sess.run(replaced_string, feed_dict=feed_dict)

680
681
682
683
684
685
686
    is_integer = True
    try:
      # Test whether out_string is a string which represents an integer, the
      # casting below will throw an error if out_string is not castable to int.
      int(out_string)
    except ValueError:
      is_integer = False
687

688
    self.assertTrue(is_integer)
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715

  def test_force_no_resize(self):
    """Tests the functionality of force_no_reisze option."""
    configs = _get_configs_for_model('ssd_inception_v2_pets')
    configs['eval_config'].force_no_resize = True

    eval_input_fn = inputs.create_eval_input_fn(
        eval_config=configs['eval_config'],
        eval_input_config=configs['eval_input_configs'][0],
        model_config=configs['model']
    )
    train_input_fn = inputs.create_train_input_fn(
        train_config=configs['train_config'],
        train_input_config=configs['train_input_config'],
        model_config=configs['model']
    )

    features_train, _ = _make_initializable_iterator(
        train_input_fn()).get_next()

    features_eval, _ = _make_initializable_iterator(
        eval_input_fn()).get_next()

    images_train, images_eval = features_train['image'], features_eval['image']

    self.assertEqual([1, None, None, 3], images_eval.shape.as_list())
    self.assertEqual([24, 300, 300, 3], images_train.shape.as_list())
716

717

pkulzc's avatar
pkulzc committed
718
class DataAugmentationFnTest(test_case.TestCase):
719
720
721
722
723
724
725
726
727
728
729
730
731

  def test_apply_image_and_box_augmentation(self):
    data_augmentation_options = [
        (preprocessor.resize_image, {
            'new_height': 20,
            'new_width': 20,
            'method': tf.image.ResizeMethod.NEAREST_NEIGHBOR
        }),
        (preprocessor.scale_boxes_to_pixel_coordinates, {}),
    ]
    data_augmentation_fn = functools.partial(
        inputs.augment_input_data,
        data_augmentation_options=data_augmentation_options)
732
733
734
735
736
737
738
739
740
741
742
743
744
745
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1., 1.]], np.float32))
      }
      augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict)
      return (augmented_tensor_dict[fields.InputDataFields.image],
              augmented_tensor_dict[fields.InputDataFields.
                                    groundtruth_boxes])
    image, groundtruth_boxes = self.execute_cpu(graph_fn, [])
    self.assertAllEqual(image.shape, [20, 20, 3])
    self.assertAllClose(groundtruth_boxes, [[10, 10, 20, 20]])
746

747
748
749
750
751
752
753
754
755
756
757
758
  def test_apply_image_and_box_augmentation_with_scores(self):
    data_augmentation_options = [
        (preprocessor.resize_image, {
            'new_height': 20,
            'new_width': 20,
            'method': tf.image.ResizeMethod.NEAREST_NEIGHBOR
        }),
        (preprocessor.scale_boxes_to_pixel_coordinates, {}),
    ]
    data_augmentation_fn = functools.partial(
        inputs.augment_input_data,
        data_augmentation_options=data_augmentation_options)
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1., 1.]], np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1.0], np.float32)),
          fields.InputDataFields.groundtruth_weights:
              tf.constant(np.array([0.8], np.float32)),
      }
      augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict)
      return (augmented_tensor_dict[fields.InputDataFields.image],
              augmented_tensor_dict[fields.InputDataFields.groundtruth_boxes],
              augmented_tensor_dict[fields.InputDataFields.groundtruth_classes],
              augmented_tensor_dict[fields.InputDataFields.groundtruth_weights])
    (image, groundtruth_boxes,
     groundtruth_classes, groundtruth_weights) = self.execute_cpu(graph_fn, [])
    self.assertAllEqual(image.shape, [20, 20, 3])
    self.assertAllClose(groundtruth_boxes, [[10, 10, 20, 20]])
    self.assertAllClose(groundtruth_classes.shape, [1.0])
    self.assertAllClose(groundtruth_weights, [0.8])
781

782
783
784
785
786
787
788
789
790
791
792
  def test_include_masks_in_data_augmentation(self):
    data_augmentation_options = [
        (preprocessor.resize_image, {
            'new_height': 20,
            'new_width': 20,
            'method': tf.image.ResizeMethod.NEAREST_NEIGHBOR
        })
    ]
    data_augmentation_fn = functools.partial(
        inputs.augment_input_data,
        data_augmentation_options=data_augmentation_options)
793
794
795
796
797
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_instance_masks:
798
799
800
              tf.constant(np.zeros([2, 10, 10], np.uint8)),
          fields.InputDataFields.groundtruth_instance_mask_weights:
              tf.constant([1.0, 0.0], np.float32)
801
802
803
804
      }
      augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict)
      return (augmented_tensor_dict[fields.InputDataFields.image],
              augmented_tensor_dict[fields.InputDataFields.
805
806
807
808
                                    groundtruth_instance_masks],
              augmented_tensor_dict[fields.InputDataFields.
                                    groundtruth_instance_mask_weights])
    image, masks, mask_weights = self.execute_cpu(graph_fn, [])
809
810
    self.assertAllEqual(image.shape, [20, 20, 3])
    self.assertAllEqual(masks.shape, [2, 20, 20])
811
    self.assertAllClose(mask_weights, [1.0, 0.0])
812
813
814
815
816
817
818
819
820
821
822
823
824

  def test_include_keypoints_in_data_augmentation(self):
    data_augmentation_options = [
        (preprocessor.resize_image, {
            'new_height': 20,
            'new_width': 20,
            'method': tf.image.ResizeMethod.NEAREST_NEIGHBOR
        }),
        (preprocessor.scale_boxes_to_pixel_coordinates, {}),
    ]
    data_augmentation_fn = functools.partial(
        inputs.augment_input_data,
        data_augmentation_options=data_augmentation_options)
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1., 1.]], np.float32)),
          fields.InputDataFields.groundtruth_keypoints:
              tf.constant(np.array([[[0.5, 1.0], [0.5, 0.5]]], np.float32))
      }
      augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict)
      return (augmented_tensor_dict[fields.InputDataFields.image],
              augmented_tensor_dict[fields.InputDataFields.groundtruth_boxes],
              augmented_tensor_dict[fields.InputDataFields.
                                    groundtruth_keypoints])
    image, boxes, keypoints = self.execute_cpu(graph_fn, [])
    self.assertAllEqual(image.shape, [20, 20, 3])
    self.assertAllClose(boxes, [[10, 10, 20, 20]])
    self.assertAllClose(keypoints, [[[10, 20], [10, 10]]])
843
844
845
846
847
848
849
850
851
852


def _fake_model_preprocessor_fn(image):
  return (image, tf.expand_dims(tf.shape(image)[1:], axis=0))


def _fake_image_resizer_fn(image, mask):
  return (image, mask, tf.shape(image))


853
854
855
856
857
858
859
860
def _fake_resize50_preprocess_fn(image):
  image = image[0]
  image, shape = preprocessor.resize_to_range(
      image, min_dimension=50, max_dimension=50, pad_to_max_dimension=True)

  return tf.expand_dims(image, 0), tf.expand_dims(shape, axis=0)


861
class DataTransformationFnTest(test_case.TestCase, parameterized.TestCase):
862

863
864
865
  def test_combine_additional_channels_if_present(self):
    image = np.random.rand(4, 4, 3).astype(np.float32)
    additional_channels = np.random.rand(4, 4, 2).astype(np.float32)
866
867
868
869
870
871
872
    def graph_fn(image, additional_channels):
      tensor_dict = {
          fields.InputDataFields.image: image,
          fields.InputDataFields.image_additional_channels: additional_channels,
          fields.InputDataFields.groundtruth_classes:
              tf.constant([1, 1], tf.int32)
      }
873

874
875
876
877
878
879
880
881
882
883
884
885
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=1)
      out_tensors = input_transformation_fn(tensor_dict=tensor_dict)
      return out_tensors[fields.InputDataFields.image]
    out_image = self.execute_cpu(graph_fn, [image, additional_channels])
    self.assertAllEqual(out_image.dtype, tf.float32)
    self.assertAllEqual(out_image.shape, [4, 4, 5])
    self.assertAllClose(out_image, np.concatenate((image, additional_channels),
                                                  axis=2))
886

pkulzc's avatar
pkulzc committed
887
  def test_use_multiclass_scores_when_present(self):
888
889
890
891
892
893
894
895
896
897
898
899
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image: tf.constant(np.random.rand(4, 4, 3).
                                                    astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]],
                                   np.float32)),
          fields.InputDataFields.multiclass_scores:
              tf.constant(np.array([0.2, 0.3, 0.5, 0.1, 0.6, 0.3], np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1, 2], np.int32))
      }
pkulzc's avatar
pkulzc committed
900

901
902
903
904
905
906
907
908
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=3, use_multiclass_scores=True)
      transformed_inputs = input_transformation_fn(tensor_dict=tensor_dict)
      return transformed_inputs[fields.InputDataFields.groundtruth_classes]
    groundtruth_classes = self.execute_cpu(graph_fn, [])
pkulzc's avatar
pkulzc committed
909
910
    self.assertAllClose(
        np.array([[0.2, 0.3, 0.5], [0.1, 0.6, 0.3]], np.float32),
911
        groundtruth_classes)
pkulzc's avatar
pkulzc committed
912

913
914
  @unittest.skipIf(tf_version.is_tf2(), ('Skipping due to different behaviour '
                                         'in TF 2.X'))
pkulzc's avatar
pkulzc committed
915
  def test_use_multiclass_scores_when_not_present(self):
916
917
918
919
920
921
922
923
924
925
926
927
928
    def graph_fn():
      zero_num_elements = tf.random.uniform([], minval=0, maxval=1,
                                            dtype=tf.int32)
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]],
                                   np.float32)),
          fields.InputDataFields.multiclass_scores: tf.zeros(zero_num_elements),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1, 2], np.int32))
      }
pkulzc's avatar
pkulzc committed
929

930
931
932
933
934
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=3, use_multiclass_scores=True)
pkulzc's avatar
pkulzc committed
935

936
937
938
      transformed_inputs = input_transformation_fn(tensor_dict=tensor_dict)
      return transformed_inputs[fields.InputDataFields.groundtruth_classes]
    groundtruth_classes = self.execute_cpu(graph_fn, [])
pkulzc's avatar
pkulzc committed
939
940
    self.assertAllClose(
        np.array([[0, 1, 0], [0, 0, 1]], np.float32),
941
        groundtruth_classes)
pkulzc's avatar
pkulzc committed
942

943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
  @parameterized.parameters(
      {'labeled_classes': [1, 2]},
      {'labeled_classes': []},
      {'labeled_classes': [1, -1, 2]}  # -1 denotes an unrecognized class
  )
  def test_use_labeled_classes(self, labeled_classes):

    def compute_fn(image, groundtruth_boxes, groundtruth_classes,
                   groundtruth_labeled_classes):
      tensor_dict = {
          fields.InputDataFields.image:
              image,
          fields.InputDataFields.groundtruth_boxes:
              groundtruth_boxes,
          fields.InputDataFields.groundtruth_classes:
              groundtruth_classes,
          fields.InputDataFields.groundtruth_labeled_classes:
              groundtruth_labeled_classes
      }

      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=3)
      return input_transformation_fn(tensor_dict=tensor_dict)

    image = np.random.rand(4, 4, 3).astype(np.float32)
    groundtruth_boxes = np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]], np.float32)
    groundtruth_classes = np.array([1, 2], np.int32)
    groundtruth_labeled_classes = np.array(labeled_classes, np.int32)

    transformed_inputs = self.execute_cpu(compute_fn, [
        image, groundtruth_boxes, groundtruth_classes,
        groundtruth_labeled_classes
    ])

    if labeled_classes == [1, 2] or labeled_classes == [1, -1, 2]:
      transformed_labeled_classes = [1, 1, 0]
    elif not labeled_classes:
      transformed_labeled_classes = [1, 1, 1]
    else:
      logging.exception('Unexpected labeled_classes %r', labeled_classes)

    self.assertAllEqual(
        np.array(transformed_labeled_classes, np.float32),
        transformed_inputs[fields.InputDataFields.groundtruth_labeled_classes])

991
  def test_returns_correct_class_label_encodings(self):
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[0, 0, 1, 1], [.5, .5, 1, 1]], np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, 1], np.int32))
      }
      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes)
      transformed_inputs = input_transformation_fn(tensor_dict=tensor_dict)
      return (transformed_inputs[fields.InputDataFields.groundtruth_classes],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_confidences])
    (groundtruth_classes, groundtruth_confidences) = self.execute_cpu(graph_fn,
                                                                      [])
    self.assertAllClose(groundtruth_classes, [[0, 0, 1], [1, 0, 0]])
    self.assertAllClose(groundtruth_confidences, [[0, 0, 1], [1, 0, 0]])
1015

1016
  def test_returns_correct_labels_with_unrecognized_class(self):
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(
                  np.array([[0, 0, 1, 1], [.2, .2, 4, 4], [.5, .5, 1, 1]],
                           np.float32)),
          fields.InputDataFields.groundtruth_area:
              tf.constant(np.array([.5, .4, .3])),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, -1, 1], np.int32)),
          fields.InputDataFields.groundtruth_keypoints:
              tf.constant(
                  np.array([[[.1, .1]], [[.2, .2]], [[.5, .5]]],
                           np.float32)),
          fields.InputDataFields.groundtruth_keypoint_visibilities:
              tf.constant([[True, True], [False, False], [True, True]]),
          fields.InputDataFields.groundtruth_instance_masks:
              tf.constant(np.random.rand(3, 4, 4).astype(np.float32)),
          fields.InputDataFields.groundtruth_is_crowd:
              tf.constant([False, True, False]),
          fields.InputDataFields.groundtruth_difficult:
              tf.constant(np.array([0, 0, 1], np.int32))
      }
1042

1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return (transformed_inputs[fields.InputDataFields.groundtruth_classes],
              transformed_inputs[fields.InputDataFields.num_groundtruth_boxes],
              transformed_inputs[fields.InputDataFields.groundtruth_area],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_confidences],
              transformed_inputs[fields.InputDataFields.groundtruth_boxes],
              transformed_inputs[fields.InputDataFields.groundtruth_keypoints],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_keypoint_visibilities],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_instance_masks],
              transformed_inputs[fields.InputDataFields.groundtruth_is_crowd],
              transformed_inputs[fields.InputDataFields.groundtruth_difficult])
    (groundtruth_classes, num_groundtruth_boxes, groundtruth_area,
     groundtruth_confidences, groundtruth_boxes, groundtruth_keypoints,
     groundtruth_keypoint_visibilities, groundtruth_instance_masks,
     groundtruth_is_crowd, groundtruth_difficult) = self.execute_cpu(graph_fn,
                                                                     [])

    self.assertAllClose(groundtruth_classes, [[0, 0, 1], [1, 0, 0]])
    self.assertAllEqual(num_groundtruth_boxes, 2)
    self.assertAllClose(groundtruth_area, [.5, .3])
    self.assertAllEqual(groundtruth_confidences, [[0, 0, 1], [1, 0, 0]])
    self.assertAllClose(groundtruth_boxes, [[0, 0, 1, 1], [.5, .5, 1, 1]])
    self.assertAllClose(groundtruth_keypoints, [[[.1, .1]], [[.5, .5]]])
    self.assertAllEqual(groundtruth_keypoint_visibilities,
                        [[True, True], [True, True]])
    self.assertAllEqual(groundtruth_instance_masks.shape, [2, 4, 4])
    self.assertAllEqual(groundtruth_is_crowd, [False, False])
    self.assertAllEqual(groundtruth_difficult, [0, 1])
1080

1081
  def test_returns_correct_merged_boxes(self):
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]],
                                   np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, 1], np.int32))
      }
1092

1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes,
          merge_multiple_boxes=True)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return (transformed_inputs[fields.InputDataFields.groundtruth_boxes],
              transformed_inputs[fields.InputDataFields.groundtruth_classes],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_confidences],
              transformed_inputs[fields.InputDataFields.num_groundtruth_boxes])
    (groundtruth_boxes, groundtruth_classes, groundtruth_confidences,
     num_groundtruth_boxes) = self.execute_cpu(graph_fn, [])
1108
    self.assertAllClose(
1109
        groundtruth_boxes,
1110
1111
        [[.5, .5, 1., 1.]])
    self.assertAllClose(
1112
        groundtruth_classes,
1113
        [[1, 0, 1]])
1114
    self.assertAllClose(
1115
        groundtruth_confidences,
1116
        [[1, 0, 1]])
1117
    self.assertAllClose(
1118
        num_groundtruth_boxes,
1119
        1)
1120

1121
  def test_returns_correct_groundtruth_confidences_when_input_present(self):
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[0, 0, 1, 1], [.5, .5, 1, 1]], np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, 1], np.int32)),
          fields.InputDataFields.groundtruth_confidences:
              tf.constant(np.array([1.0, -1.0], np.float32))
      }
      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return (transformed_inputs[fields.InputDataFields.groundtruth_classes],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_confidences])
    groundtruth_classes, groundtruth_confidences = self.execute_cpu(graph_fn,
                                                                    [])
1145
    self.assertAllClose(
1146
        groundtruth_classes,
1147
1148
        [[0, 0, 1], [1, 0, 0]])
    self.assertAllClose(
1149
        groundtruth_confidences,
1150
1151
        [[0, 0, 1], [-1, 0, 0]])

1152
  def test_returns_resized_masks(self):
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_instance_masks:
              tf.constant(np.random.rand(2, 4, 4).astype(np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, 1], np.int32)),
          fields.InputDataFields.original_image_spatial_shape:
              tf.constant(np.array([4, 4], np.int32))
      }
1164

1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
      def fake_image_resizer_fn(image, masks=None):
        resized_image = tf.image.resize_images(image, [8, 8])
        results = [resized_image]
        if masks is not None:
          resized_masks = tf.transpose(
              tf.image.resize_images(tf.transpose(masks, [1, 2, 0]), [8, 8]),
              [2, 0, 1])
          results.append(resized_masks)
        results.append(tf.shape(resized_image))
        return results

      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=fake_image_resizer_fn,
          num_classes=num_classes,
          retain_original_image=True)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return (transformed_inputs[fields.InputDataFields.original_image],
              transformed_inputs[fields.InputDataFields.
                                 original_image_spatial_shape],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_instance_masks])
    (original_image, original_image_shape,
     groundtruth_instance_masks) = self.execute_cpu(graph_fn, [])
    self.assertEqual(original_image.dtype, np.uint8)
    self.assertAllEqual(original_image_shape, [4, 4])
    self.assertAllEqual(original_image.shape, [8, 8, 3])
    self.assertAllEqual(groundtruth_instance_masks.shape, [2, 8, 8])
1195
1196
1197

  def test_applies_model_preprocess_fn_to_image_tensor(self):
    np_image = np.random.randint(256, size=(4, 4, 3))
1198
1199
1200
1201
1202
1203
    def graph_fn(image):
      tensor_dict = {
          fields.InputDataFields.image: image,
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, 1], np.int32))
      }
1204

1205
1206
      def fake_model_preprocessor_fn(image):
        return (image / 255., tf.expand_dims(tf.shape(image)[1:], axis=0))
1207

1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return (transformed_inputs[fields.InputDataFields.image],
              transformed_inputs[fields.InputDataFields.true_image_shape])
    image, true_image_shape = self.execute_cpu(graph_fn, [np_image])
    self.assertAllClose(image, np_image / 255.)
    self.assertAllClose(true_image_shape, [4, 4, 3])
1220
1221
1222

  def test_applies_data_augmentation_fn_to_tensor_dict(self):
    np_image = np.random.randint(256, size=(4, 4, 3))
1223
1224
1225
1226
1227
1228
    def graph_fn(image):
      tensor_dict = {
          fields.InputDataFields.image: image,
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, 1], np.int32))
      }
1229

1230
1231
      def add_one_data_augmentation_fn(tensor_dict):
        return {key: value + 1 for key, value in tensor_dict.items()}
1232

1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
      num_classes = 4
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes,
          data_augmentation_fn=add_one_data_augmentation_fn)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return (transformed_inputs[fields.InputDataFields.image],
              transformed_inputs[fields.InputDataFields.groundtruth_classes])
    image, groundtruth_classes = self.execute_cpu(graph_fn, [np_image])
    self.assertAllEqual(image, np_image + 1)
    self.assertAllEqual(
        groundtruth_classes,
1247
1248
1249
1250
        [[0, 0, 0, 1], [0, 1, 0, 0]])

  def test_applies_data_augmentation_fn_before_model_preprocess_fn(self):
    np_image = np.random.randint(256, size=(4, 4, 3))
1251
1252
1253
1254
1255
1256
    def graph_fn(image):
      tensor_dict = {
          fields.InputDataFields.image: image,
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([3, 1], np.int32))
      }
1257

1258
1259
      def mul_two_model_preprocessor_fn(image):
        return (image * 2, tf.expand_dims(tf.shape(image)[1:], axis=0))
1260

1261
1262
1263
      def add_five_to_image_data_augmentation_fn(tensor_dict):
        tensor_dict[fields.InputDataFields.image] += 5
        return tensor_dict
1264

1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
      num_classes = 4
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=mul_two_model_preprocessor_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes,
          data_augmentation_fn=add_five_to_image_data_augmentation_fn)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return transformed_inputs[fields.InputDataFields.image]
    image = self.execute_cpu(graph_fn, [np_image])
    self.assertAllEqual(image, (np_image + 5) * 2)
1276

1277
  def test_resize_with_padding(self):
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(100, 50, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.0, .0, .5, .5]],
                                   np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1, 2], np.int32)),
          fields.InputDataFields.groundtruth_keypoints:
              tf.constant([[[0.1, 0.2]], [[0.3, 0.4]]]),
      }
1290

1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_resize50_preprocess_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes,)
      transformed_inputs = input_transformation_fn(tensor_dict)
      return (transformed_inputs[fields.InputDataFields.groundtruth_boxes],
              transformed_inputs[fields.InputDataFields.groundtruth_keypoints])
    groundtruth_boxes, groundtruth_keypoints = self.execute_cpu(graph_fn, [])
1301
    self.assertAllClose(
1302
        groundtruth_boxes,
1303
1304
        [[.5, .25, 1., .5], [.0, .0, .5, .25]])
    self.assertAllClose(
1305
        groundtruth_keypoints,
1306
1307
1308
        [[[.1, .1]], [[.3, .2]]])

  def test_groundtruth_keypoint_weights(self):
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(100, 50, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.0, .0, .5, .5]],
                                   np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1, 2], np.int32)),
          fields.InputDataFields.groundtruth_keypoints:
              tf.constant([[[0.1, 0.2], [0.3, 0.4]],
                           [[0.5, 0.6], [0.7, 0.8]]]),
          fields.InputDataFields.groundtruth_keypoint_visibilities:
              tf.constant([[True, False], [True, True]]),
      }
1324

1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
      num_classes = 3
      keypoint_type_weight = [1.0, 2.0]
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_resize50_preprocess_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes,
          keypoint_type_weight=keypoint_type_weight)
      transformed_inputs = input_transformation_fn(tensor_dict=tensor_dict)
      return (transformed_inputs[fields.InputDataFields.groundtruth_keypoints],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_keypoint_weights])

    groundtruth_keypoints, groundtruth_keypoint_weights = self.execute_cpu(
        graph_fn, [])
1340
    self.assertAllClose(
1341
        groundtruth_keypoints,
1342
1343
1344
        [[[0.1, 0.1], [0.3, 0.2]],
         [[0.5, 0.3], [0.7, 0.4]]])
    self.assertAllClose(
1345
        groundtruth_keypoint_weights,
1346
1347
1348
        [[1.0, 0.0], [1.0, 2.0]])

  def test_groundtruth_keypoint_weights_default(self):
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(100, 50, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.0, .0, .5, .5]],
                                   np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1, 2], np.int32)),
          fields.InputDataFields.groundtruth_keypoints:
              tf.constant([[[0.1, 0.2], [0.3, 0.4]],
                           [[0.5, 0.6], [0.7, 0.8]]]),
      }
1362

1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
      num_classes = 3
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_resize50_preprocess_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes)
      transformed_inputs = input_transformation_fn(tensor_dict=tensor_dict)
      return (transformed_inputs[fields.InputDataFields.groundtruth_keypoints],
              transformed_inputs[fields.InputDataFields.
                                 groundtruth_keypoint_weights])
    groundtruth_keypoints, groundtruth_keypoint_weights = self.execute_cpu(
        graph_fn, [])
1375
    self.assertAllClose(
1376
        groundtruth_keypoints,
1377
1378
1379
        [[[0.1, 0.1], [0.3, 0.2]],
         [[0.5, 0.3], [0.7, 0.4]]])
    self.assertAllClose(
1380
        groundtruth_keypoint_weights,
1381
        [[1.0, 1.0], [1.0, 1.0]])
1382

1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
  def test_groundtruth_dense_pose(self):
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(100, 50, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.0, .0, .5, .5]],
                                   np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1, 2], np.int32)),
          fields.InputDataFields.groundtruth_dp_num_points:
              tf.constant([0, 2], dtype=tf.int32),
          fields.InputDataFields.groundtruth_dp_part_ids:
              tf.constant([[0, 0], [4, 23]], dtype=tf.int32),
          fields.InputDataFields.groundtruth_dp_surface_coords:
              tf.constant([[[0., 0., 0., 0.,], [0., 0., 0., 0.,]],
                           [[0.1, 0.2, 0.3, 0.4,], [0.6, 0.8, 0.6, 0.7,]]],
                          dtype=tf.float32),
      }

      num_classes = 1
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_resize50_preprocess_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes)
      transformed_inputs = input_transformation_fn(tensor_dict=tensor_dict)
      transformed_dp_num_points = transformed_inputs[
          fields.InputDataFields.groundtruth_dp_num_points]
      transformed_dp_part_ids = transformed_inputs[
          fields.InputDataFields.groundtruth_dp_part_ids]
      transformed_dp_surface_coords = transformed_inputs[
          fields.InputDataFields.groundtruth_dp_surface_coords]
      return (transformed_dp_num_points, transformed_dp_part_ids,
              transformed_dp_surface_coords)

    dp_num_points, dp_part_ids, dp_surface_coords = self.execute_cpu(
        graph_fn, [])
    self.assertAllEqual(dp_num_points, [0, 2])
    self.assertAllEqual(dp_part_ids, [[0, 0], [4, 23]])
    self.assertAllClose(
        dp_surface_coords,
        [[[0., 0., 0., 0.,], [0., 0., 0., 0.,]],
         [[0.1, 0.1, 0.3, 0.4,], [0.6, 0.4, 0.6, 0.7,]]])

1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
  def test_groundtruth_keypoint_depths(self):
    def graph_fn():
      tensor_dict = {
          fields.InputDataFields.image:
              tf.constant(np.random.rand(100, 50, 3).astype(np.float32)),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant(np.array([[.5, .5, 1, 1], [.0, .0, .5, .5]],
                                   np.float32)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant(np.array([1, 2], np.int32)),
          fields.InputDataFields.groundtruth_keypoints:
              tf.constant([[[0.1, 0.2], [0.3, 0.4]],
                           [[0.5, 0.6], [0.7, 0.8]]]),
          fields.InputDataFields.groundtruth_keypoint_visibilities:
              tf.constant([[True, False], [True, True]]),
          fields.InputDataFields.groundtruth_keypoint_depths:
              tf.constant([[1.0, 0.9], [0.8, 0.7]]),
          fields.InputDataFields.groundtruth_keypoint_depth_weights:
              tf.constant([[0.7, 0.8], [0.9, 1.0]]),
      }

      num_classes = 3
      keypoint_type_weight = [1.0, 2.0]
      input_transformation_fn = functools.partial(
          inputs.transform_input_data,
          model_preprocess_fn=_fake_resize50_preprocess_fn,
          image_resizer_fn=_fake_image_resizer_fn,
          num_classes=num_classes,
          keypoint_type_weight=keypoint_type_weight)
      transformed_inputs = input_transformation_fn(tensor_dict=tensor_dict)
      return (transformed_inputs[
          fields.InputDataFields.groundtruth_keypoint_depths],
              transformed_inputs[
                  fields.InputDataFields.groundtruth_keypoint_depth_weights])

    keypoint_depths, keypoint_depth_weights = self.execute_cpu(graph_fn, [])
    self.assertAllClose(
        keypoint_depths,
        [[1.0, 0.9], [0.8, 0.7]])
    self.assertAllClose(
        keypoint_depth_weights,
        [[0.7, 0.8], [0.9, 1.0]])

1471

pkulzc's avatar
pkulzc committed
1472
class PadInputDataToStaticShapesFnTest(test_case.TestCase):
1473
1474
1475
1476

  def test_pad_images_boxes_and_classes(self):
    input_tensor_dict = {
        fields.InputDataFields.image:
1477
            tf.random.uniform([3, 3, 3]),
1478
        fields.InputDataFields.groundtruth_boxes:
1479
            tf.random.uniform([2, 4]),
1480
        fields.InputDataFields.groundtruth_classes:
1481
            tf.random.uniform([2, 3], minval=0, maxval=2, dtype=tf.int32),
pkulzc's avatar
pkulzc committed
1482
        fields.InputDataFields.true_image_shape:
1483
            tf.constant([3, 3, 3]),
pkulzc's avatar
pkulzc committed
1484
        fields.InputDataFields.original_image_spatial_shape:
1485
            tf.constant([3, 3])
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
    }
    padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
        tensor_dict=input_tensor_dict,
        max_num_boxes=3,
        num_classes=3,
        spatial_image_shape=[5, 6])

    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.image].shape.as_list(),
        [5, 6, 3])
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.true_image_shape]
        .shape.as_list(), [3])
pkulzc's avatar
pkulzc committed
1499
1500
1501
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.original_image_spatial_shape]
        .shape.as_list(), [2])
1502
1503
1504
1505
1506
1507
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.groundtruth_boxes]
        .shape.as_list(), [3, 4])
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.groundtruth_classes]
        .shape.as_list(), [3, 3])
1508
1509

  def test_clip_boxes_and_classes(self):
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
    def graph_fn():
      input_tensor_dict = {
          fields.InputDataFields.groundtruth_boxes:
              tf.random.uniform([5, 4]),
          fields.InputDataFields.groundtruth_classes:
              tf.random.uniform([2, 3], maxval=10, dtype=tf.int32),
          fields.InputDataFields.num_groundtruth_boxes:
              tf.constant(5)
      }
      padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
          tensor_dict=input_tensor_dict,
          max_num_boxes=3,
          num_classes=3,
          spatial_image_shape=[5, 6])
      return (padded_tensor_dict[fields.InputDataFields.groundtruth_boxes],
              padded_tensor_dict[fields.InputDataFields.groundtruth_classes],
              padded_tensor_dict[fields.InputDataFields.num_groundtruth_boxes])
    (groundtruth_boxes, groundtruth_classes,
     num_groundtruth_boxes) = self.execute_cpu(graph_fn, [])
    self.assertAllEqual(groundtruth_boxes.shape, [3, 4])
    self.assertAllEqual(groundtruth_classes.shape, [3, 3])
    self.assertEqual(num_groundtruth_boxes, 3)
1532
1533
1534
1535

  def test_images_and_additional_channels(self):
    input_tensor_dict = {
        fields.InputDataFields.image:
1536
            test_utils.image_with_dynamic_shape(4, 3, 5),
1537
        fields.InputDataFields.image_additional_channels:
1538
            test_utils.image_with_dynamic_shape(4, 3, 2),
1539
1540
1541
1542
1543
1544
1545
    }
    padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
        tensor_dict=input_tensor_dict,
        max_num_boxes=3,
        num_classes=3,
        spatial_image_shape=[5, 6])

1546
1547
    # pad_input_data_to_static_shape assumes that image is already concatenated
    # with additional channels.
1548
1549
1550
1551
1552
1553
1554
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.image].shape.as_list(),
        [5, 6, 5])
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.image_additional_channels]
        .shape.as_list(), [5, 6, 2])

1555
1556
1557
  def test_images_and_additional_channels_errors(self):
    input_tensor_dict = {
        fields.InputDataFields.image:
1558
            test_utils.image_with_dynamic_shape(10, 10, 3),
1559
        fields.InputDataFields.image_additional_channels:
1560
            test_utils.image_with_dynamic_shape(10, 10, 2),
1561
        fields.InputDataFields.original_image:
1562
            test_utils.image_with_dynamic_shape(10, 10, 3),
1563
1564
1565
1566
1567
1568
1569
1570
    }
    with self.assertRaises(ValueError):
      _ = inputs.pad_input_data_to_static_shapes(
          tensor_dict=input_tensor_dict,
          max_num_boxes=3,
          num_classes=3,
          spatial_image_shape=[5, 6])

1571
1572
1573
  def test_gray_images(self):
    input_tensor_dict = {
        fields.InputDataFields.image:
1574
            test_utils.image_with_dynamic_shape(4, 4, 1),
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
    }
    padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
        tensor_dict=input_tensor_dict,
        max_num_boxes=3,
        num_classes=3,
        spatial_image_shape=[5, 6])

    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.image].shape.as_list(),
        [5, 6, 1])

  def test_gray_images_and_additional_channels(self):
    input_tensor_dict = {
        fields.InputDataFields.image:
1589
            test_utils.image_with_dynamic_shape(4, 4, 3),
1590
        fields.InputDataFields.image_additional_channels:
1591
            test_utils.image_with_dynamic_shape(4, 4, 2),
1592
    }
1593
1594
    # pad_input_data_to_static_shape assumes that image is already concatenated
    # with additional channels.
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
    padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
        tensor_dict=input_tensor_dict,
        max_num_boxes=3,
        num_classes=3,
        spatial_image_shape=[5, 6])

    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.image].shape.as_list(),
        [5, 6, 3])
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.image_additional_channels]
        .shape.as_list(), [5, 6, 2])

1608
  def test_keypoints(self):
1609
1610
1611
    keypoints = test_utils.keypoints_with_dynamic_shape(10, 16, 4)
    visibilities = tf.cast(tf.random.uniform(tf.shape(keypoints)[:-1], minval=0,
                                             maxval=2, dtype=tf.int32), tf.bool)
1612
1613
    input_tensor_dict = {
        fields.InputDataFields.groundtruth_keypoints:
1614
            test_utils.keypoints_with_dynamic_shape(10, 16, 4),
1615
        fields.InputDataFields.groundtruth_keypoint_visibilities:
1616
            visibilities
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
    }
    padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
        tensor_dict=input_tensor_dict,
        max_num_boxes=3,
        num_classes=3,
        spatial_image_shape=[5, 6])

    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.groundtruth_keypoints]
        .shape.as_list(), [3, 16, 4])
    self.assertAllEqual(
        padded_tensor_dict[
            fields.InputDataFields.groundtruth_keypoint_visibilities]
        .shape.as_list(), [3, 16])

1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
  def test_dense_pose(self):
    input_tensor_dict = {
        fields.InputDataFields.groundtruth_dp_num_points:
            tf.constant([0, 2], dtype=tf.int32),
        fields.InputDataFields.groundtruth_dp_part_ids:
            tf.constant([[0, 0], [4, 23]], dtype=tf.int32),
        fields.InputDataFields.groundtruth_dp_surface_coords:
            tf.constant([[[0., 0., 0., 0.,], [0., 0., 0., 0.,]],
                         [[0.1, 0.2, 0.3, 0.4,], [0.6, 0.8, 0.6, 0.7,]]],
                        dtype=tf.float32),
    }

    padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
        tensor_dict=input_tensor_dict,
        max_num_boxes=3,
        num_classes=1,
        spatial_image_shape=[128, 128],
        max_dp_points=200)

    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.groundtruth_dp_num_points]
        .shape.as_list(), [3])
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.groundtruth_dp_part_ids]
        .shape.as_list(), [3, 200])
    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.groundtruth_dp_surface_coords]
        .shape.as_list(), [3, 200, 4])

1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
  def test_pad_input_data_to_static_shapes_for_trackid(self):
    input_tensor_dict = {
        fields.InputDataFields.groundtruth_track_ids:
            tf.constant([0, 1], dtype=tf.int32),
    }

    padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
        tensor_dict=input_tensor_dict,
        max_num_boxes=3,
        num_classes=1,
        spatial_image_shape=[128, 128])

    self.assertAllEqual(
        padded_tensor_dict[fields.InputDataFields.groundtruth_track_ids]
        .shape.as_list(), [3])

1677
1678
1679
1680
  def test_context_features(self):
    context_memory_size = 8
    context_feature_length = 10
    max_num_context_features = 20
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
    def graph_fn():
      input_tensor_dict = {
          fields.InputDataFields.context_features:
              tf.ones([context_memory_size, context_feature_length]),
          fields.InputDataFields.context_feature_length:
              tf.constant(context_feature_length)
      }
      padded_tensor_dict = inputs.pad_input_data_to_static_shapes(
          tensor_dict=input_tensor_dict,
          max_num_boxes=3,
          num_classes=3,
          spatial_image_shape=[5, 6],
          max_num_context_features=max_num_context_features,
          context_feature_length=context_feature_length)
1695

1696
1697
1698
1699
1700
      self.assertAllEqual(
          padded_tensor_dict[
              fields.InputDataFields.context_features].shape.as_list(),
          [max_num_context_features, context_feature_length])
      return padded_tensor_dict[fields.InputDataFields.valid_context_size]
1701

1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
    valid_context_size = self.execute_cpu(graph_fn, [])
    self.assertEqual(valid_context_size, context_memory_size)


class NegativeSizeTest(test_case.TestCase):
  """Test for inputs and related funcitons."""

  def test_negative_size_error(self):
    """Test that error is raised for negative size boxes."""

    def graph_fn():
      tensors = {
          fields.InputDataFields.image: tf.zeros((128, 128, 3)),
          fields.InputDataFields.groundtruth_classes:
              tf.constant([1, 1], tf.int32),
          fields.InputDataFields.groundtruth_boxes:
              tf.constant([[0.5, 0.5, 0.4, 0.5]], tf.float32)
1719
      }
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
      tensors = inputs.transform_input_data(
          tensors, _fake_model_preprocessor_fn, _fake_image_resizer_fn,
          num_classes=10)
      return tensors[fields.InputDataFields.groundtruth_boxes]
    with self.assertRaises(tf.errors.InvalidArgumentError):
      self.execute_cpu(graph_fn, [])

  def test_negative_size_no_assert(self):
    """Test that negative size boxes are filtered out without assert.

    This test simulates the behaviour when we run on TPU and Assert ops are
    not supported.
    """
1733

1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
    tensors = {
        fields.InputDataFields.image: tf.zeros((128, 128, 3)),
        fields.InputDataFields.groundtruth_classes:
            tf.constant([1, 1], tf.int32),
        fields.InputDataFields.groundtruth_boxes:
            tf.constant([[0.5, 0.5, 0.4, 0.5], [0.5, 0.5, 0.6, 0.6]],
                        tf.float32)
    }

    with mock.patch.object(tf, 'Assert') as tf_assert:
      tf_assert.return_value = tf.no_op()
      tensors = inputs.transform_input_data(
          tensors, _fake_model_preprocessor_fn, _fake_image_resizer_fn,
          num_classes=10)

      self.assertAllClose(tensors[fields.InputDataFields.groundtruth_boxes],
                          [[0.5, 0.5, 0.6, 0.6]])
1751

1752

1753
1754
if __name__ == '__main__':
  tf.test.main()