eval_util.py 54.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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.
# ==============================================================================
15
"""Common utility functions for evaluation."""
pkulzc's avatar
pkulzc committed
16
17
18
19
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

20
import collections
21
import os
22
import re
23
24
25
import time

import numpy as np
pkulzc's avatar
pkulzc committed
26
from six.moves import range
27
28
29
import tensorflow.compat.v1 as tf

import tf_slim as slim
30

31
32
33
34
from object_detection.core import box_list
from object_detection.core import box_list_ops
from object_detection.core import keypoint_ops
from object_detection.core import standard_fields as fields
35
from object_detection.metrics import coco_evaluation
36
from object_detection.metrics import lvis_evaluation
37
from object_detection.protos import eval_pb2
38
from object_detection.utils import label_map_util
39
from object_detection.utils import object_detection_evaluation
40
from object_detection.utils import ops
41
from object_detection.utils import shape_utils
42
43
from object_detection.utils import visualization_utils as vis_utils

44
EVAL_KEYPOINT_METRIC = 'coco_keypoint_metrics'
45

46
47
48
49
50
51
# A dictionary of metric names to classes that implement the metric. The classes
# in the dictionary must implement
# utils.object_detection_evaluation.DetectionEvaluator interface.
EVAL_METRICS_CLASS_DICT = {
    'coco_detection_metrics':
        coco_evaluation.CocoDetectionEvaluator,
52
53
    'coco_keypoint_metrics':
        coco_evaluation.CocoKeypointEvaluator,
54
55
    'coco_mask_metrics':
        coco_evaluation.CocoMaskEvaluator,
56
57
    'coco_panoptic_metrics':
        coco_evaluation.CocoPanopticSegmentationEvaluator,
58
59
    'lvis_mask_metrics':
        lvis_evaluation.LVISMaskEvaluator,
60
61
    'oid_challenge_detection_metrics':
        object_detection_evaluation.OpenImagesDetectionChallengeEvaluator,
62
63
64
    'oid_challenge_segmentation_metrics':
        object_detection_evaluation
        .OpenImagesInstanceSegmentationChallengeEvaluator,
65
66
67
68
    'pascal_voc_detection_metrics':
        object_detection_evaluation.PascalDetectionEvaluator,
    'weighted_pascal_voc_detection_metrics':
        object_detection_evaluation.WeightedPascalDetectionEvaluator,
69
70
    'precision_at_recall_detection_metrics':
        object_detection_evaluation.PrecisionAtRecallDetectionEvaluator,
71
72
73
74
75
76
    'pascal_voc_instance_segmentation_metrics':
        object_detection_evaluation.PascalInstanceSegmentationEvaluator,
    'weighted_pascal_voc_instance_segmentation_metrics':
        object_detection_evaluation.WeightedPascalInstanceSegmentationEvaluator,
    'oid_V2_detection_metrics':
        object_detection_evaluation.OpenImagesDetectionEvaluator,
77
78
79
80
}

EVAL_DEFAULT_METRIC = 'coco_detection_metrics'

81
82
83
84
85
86
87
88
89

def write_metrics(metrics, global_step, summary_dir):
  """Write metrics to a summary directory.

  Args:
    metrics: A dictionary containing metric names and values.
    global_step: Global step at which the metrics are computed.
    summary_dir: Directory to write tensorflow summaries to.
  """
90
  tf.logging.info('Writing metrics to tf summary.')
91
  summary_writer = tf.summary.FileWriterCache.get(summary_dir)
92
93
94
95
96
  for key in sorted(metrics):
    summary = tf.Summary(value=[
        tf.Summary.Value(tag=key, simple_value=metrics[key]),
    ])
    summary_writer.add_summary(summary, global_step)
97
98
    tf.logging.info('%s: %f', key, metrics[key])
  tf.logging.info('Metrics written to tf summary.')
99
100


101
# TODO(rathodv): Add tests.
102
103
104
105
106
107
108
109
def visualize_detection_results(result_dict,
                                tag,
                                global_step,
                                categories,
                                summary_dir='',
                                export_dir='',
                                agnostic_mode=False,
                                show_groundtruth=False,
110
                                groundtruth_box_visualization_color='black',
111
                                min_score_thresh=.5,
112
113
114
115
                                max_num_predictions=20,
                                skip_scores=False,
                                skip_labels=False,
                                keep_image_id_for_visualization_export=False):
116
117
118
119
120
121
122
123
124
125
126
127
  """Visualizes detection results and writes visualizations to image summaries.

  This function visualizes an image with its detected bounding boxes and writes
  to image summaries which can be viewed on tensorboard.  It optionally also
  writes images to a directory. In the case of missing entry in the label map,
  unknown class name in the visualization is shown as "N/A".

  Args:
    result_dict: a dictionary holding groundtruth and detection
      data corresponding to each image being evaluated.  The following keys
      are required:
        'original_image': a numpy array representing the image with shape
128
          [1, height, width, 3] or [1, height, width, 1]
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
        'detection_boxes': a numpy array of shape [N, 4]
        'detection_scores': a numpy array of shape [N]
        'detection_classes': a numpy array of shape [N]
      The following keys are optional:
        'groundtruth_boxes': a numpy array of shape [N, 4]
        'groundtruth_keypoints': a numpy array of shape [N, num_keypoints, 2]
      Detections are assumed to be provided in decreasing order of score and for
      display, and we assume that scores are probabilities between 0 and 1.
    tag: tensorboard tag (string) to associate with image.
    global_step: global step at which the visualization are generated.
    categories: a list of dictionaries representing all possible categories.
      Each dict in this list has the following keys:
          'id': (required) an integer id uniquely identifying this category
          'name': (required) string representing category name
            e.g., 'cat', 'dog', 'pizza'
          'supercategory': (optional) string representing the supercategory
            e.g., 'animal', 'vehicle', 'food', etc
    summary_dir: the output directory to which the image summaries are written.
    export_dir: the output directory to which images are written.  If this is
      empty (default), then images are not exported.
    agnostic_mode: boolean (default: False) controlling whether to evaluate in
      class-agnostic mode or not.
    show_groundtruth: boolean (default: False) controlling whether to show
      groundtruth boxes in addition to detected boxes
153
154
    groundtruth_box_visualization_color: box color for visualizing groundtruth
      boxes
155
156
    min_score_thresh: minimum score threshold for a box to be visualized
    max_num_predictions: maximum number of detections to visualize
157
158
159
160
    skip_scores: whether to skip score when drawing a single detection
    skip_labels: whether to skip label when drawing a single detection
    keep_image_id_for_visualization_export: whether to keep image identifier in
      filename when exported to export_dir
161
162
163
164
165
  Raises:
    ValueError: if result_dict does not contain the expected keys (i.e.,
      'original_image', 'detection_boxes', 'detection_scores',
      'detection_classes')
  """
166
167
  detection_fields = fields.DetectionResultFields
  input_fields = fields.InputDataFields
168
  if not set([
169
170
171
172
      input_fields.original_image,
      detection_fields.detection_boxes,
      detection_fields.detection_scores,
      detection_fields.detection_classes,
173
174
  ]).issubset(set(result_dict.keys())):
    raise ValueError('result_dict does not contain all expected keys.')
175
  if show_groundtruth and input_fields.groundtruth_boxes not in result_dict:
176
177
    raise ValueError('If show_groundtruth is enabled, result_dict must contain '
                     'groundtruth_boxes.')
178
  tf.logging.info('Creating detection visualizations.')
179
180
  category_index = label_map_util.create_category_index(categories)

181
  image = np.squeeze(result_dict[input_fields.original_image], axis=0)
182
183
  if image.shape[2] == 1:  # If one channel image, repeat in RGB.
    image = np.tile(image, [1, 1, 3])
184
185
186
187
188
189
190
  detection_boxes = result_dict[detection_fields.detection_boxes]
  detection_scores = result_dict[detection_fields.detection_scores]
  detection_classes = np.int32((result_dict[
      detection_fields.detection_classes]))
  detection_keypoints = result_dict.get(detection_fields.detection_keypoints)
  detection_masks = result_dict.get(detection_fields.detection_masks)
  detection_boundaries = result_dict.get(detection_fields.detection_boundaries)
191
192
193

  # Plot groundtruth underneath detections
  if show_groundtruth:
194
195
    groundtruth_boxes = result_dict[input_fields.groundtruth_boxes]
    groundtruth_keypoints = result_dict.get(input_fields.groundtruth_keypoints)
196
    vis_utils.visualize_boxes_and_labels_on_image_array(
197
198
199
200
201
        image=image,
        boxes=groundtruth_boxes,
        classes=None,
        scores=None,
        category_index=category_index,
202
203
        keypoints=groundtruth_keypoints,
        use_normalized_coordinates=False,
204
205
        max_boxes_to_draw=None,
        groundtruth_box_visualization_color=groundtruth_box_visualization_color)
206
207
208
209
210
211
212
  vis_utils.visualize_boxes_and_labels_on_image_array(
      image,
      detection_boxes,
      detection_classes,
      detection_scores,
      category_index,
      instance_masks=detection_masks,
213
      instance_boundaries=detection_boundaries,
214
215
216
217
      keypoints=detection_keypoints,
      use_normalized_coordinates=False,
      max_boxes_to_draw=max_num_predictions,
      min_score_thresh=min_score_thresh,
218
219
220
      agnostic_mode=agnostic_mode,
      skip_scores=skip_scores,
      skip_labels=skip_labels)
221
222

  if export_dir:
223
224
225
226
227
228
229
    if keep_image_id_for_visualization_export and result_dict[fields.
                                                              InputDataFields()
                                                              .key]:
      export_path = os.path.join(export_dir, 'export-{}-{}.png'.format(
          tag, result_dict[fields.InputDataFields().key]))
    else:
      export_path = os.path.join(export_dir, 'export-{}.png'.format(tag))
230
231
232
    vis_utils.save_image_array_as_png(image, export_path)

  summary = tf.Summary(value=[
233
234
235
236
237
      tf.Summary.Value(
          tag=tag,
          image=tf.Summary.Image(
              encoded_image_string=vis_utils.encode_image_array_as_png_str(
                  image)))
238
  ])
239
  summary_writer = tf.summary.FileWriterCache.get(summary_dir)
240
241
  summary_writer.add_summary(summary, global_step)

242
243
  tf.logging.info('Detection visualizations written to summary with tag %s.',
                  tag)
244
245


246
247
248
249
250
251
252
253
254
def _run_checkpoint_once(tensor_dict,
                         evaluators=None,
                         batch_processor=None,
                         checkpoint_dirs=None,
                         variables_to_restore=None,
                         restore_fn=None,
                         num_batches=1,
                         master='',
                         save_graph=False,
255
                         save_graph_dir='',
256
                         losses_dict=None,
257
258
                         eval_export_path=None,
                         process_metrics_fn=None):
259
  """Evaluates metrics defined in evaluators and returns summaries.
260
261
262
263

  This function loads the latest checkpoint in checkpoint_dirs and evaluates
  all metrics defined in evaluators. The metrics are processed in batch by the
  batch_processor.
264
265
266
267

  Args:
    tensor_dict: a dictionary holding tensors representing a batch of detections
      and corresponding groundtruth annotations.
268
269
270
    evaluators: a list of object of type DetectionEvaluator to be used for
      evaluation. Note that the metric names produced by different evaluators
      must be unique.
271
272
273
274
275
276
277
278
279
280
281
    batch_processor: a function taking four arguments:
      1. tensor_dict: the same tensor_dict that is passed in as the first
        argument to this function.
      2. sess: a tensorflow session
      3. batch_index: an integer representing the index of the batch amongst
        all batches
      By default, batch_processor is None, which defaults to running:
        return sess.run(tensor_dict)
      To skip an image, it suffices to return an empty dictionary in place of
      result_dict.
    checkpoint_dirs: list of directories to load into an EnsembleModel. If it
282
283
      has only one directory, EnsembleModel will not be used --
        a DetectionModel
284
285
286
287
288
289
290
291
292
293
294
295
296
      will be instantiated directly. Not used if restore_fn is set.
    variables_to_restore: None, or a dictionary mapping variable names found in
      a checkpoint to model variables. The dictionary would normally be
      generated by creating a tf.train.ExponentialMovingAverage object and
      calling its variables_to_restore() method. Not used if restore_fn is set.
    restore_fn: None, or a function that takes a tf.Session object and correctly
      restores all necessary variables from the correct checkpoint file. If
      None, attempts to restore from the first directory in checkpoint_dirs.
    num_batches: the number of batches to use for evaluation.
    master: the location of the Tensorflow session.
    save_graph: whether or not the Tensorflow graph is stored as a pbtxt file.
    save_graph_dir: where to store the Tensorflow graph on disk. If save_graph
      is True this must be non-empty.
297
    losses_dict: optional dictionary of scalar detection losses.
298
299
    eval_export_path: Path for saving a json file that contains the detection
      results in json format.
300
301
302
303
304
305
    process_metrics_fn: a callback called with evaluation results after each
      evaluation is done.  It could be used e.g. to back up checkpoints with
      best evaluation scores, or to call an external system to update evaluation
      results in order to drive best hyper-parameter search.  Parameters are:
      int checkpoint_number, Dict[str, ObjectDetectionEvalMetrics] metrics,
      str checkpoint_file path.
306
307
308
309

  Returns:
    global_step: the count of global steps.
    all_evaluator_metrics: A dictionary containing metric names and values.
310
311
312
313
314
315
316
317
318
319
320

  Raises:
    ValueError: if restore_fn is None and checkpoint_dirs doesn't have at least
      one element.
    ValueError: if save_graph is True and save_graph_dir is not defined.
  """
  if save_graph and not save_graph_dir:
    raise ValueError('`save_graph_dir` must be defined.')
  sess = tf.Session(master, graph=tf.get_default_graph())
  sess.run(tf.global_variables_initializer())
  sess.run(tf.local_variables_initializer())
321
  sess.run(tf.tables_initializer())
322
  checkpoint_file = None
323
324
325
326
327
328
329
330
331
332
333
334
335
  if restore_fn:
    restore_fn(sess)
  else:
    if not checkpoint_dirs:
      raise ValueError('`checkpoint_dirs` must have at least one entry.')
    checkpoint_file = tf.train.latest_checkpoint(checkpoint_dirs[0])
    saver = tf.train.Saver(variables_to_restore)
    saver.restore(sess, checkpoint_file)

  if save_graph:
    tf.train.write_graph(sess.graph_def, save_graph_dir, 'eval.pbtxt')

  counters = {'skipped': 0, 'success': 0}
336
  aggregate_result_losses_dict = collections.defaultdict(list)
337
  with slim.queues.QueueRunners(sess):
338
339
340
    try:
      for batch in range(int(num_batches)):
        if (batch + 1) % 100 == 0:
341
342
          tf.logging.info('Running eval ops batch %d/%d', batch + 1,
                          num_batches)
343
344
        if not batch_processor:
          try:
345
346
347
348
            if not losses_dict:
              losses_dict = {}
            result_dict, result_losses_dict = sess.run([tensor_dict,
                                                        losses_dict])
349
350
            counters['success'] += 1
          except tf.errors.InvalidArgumentError:
351
            tf.logging.info('Skipping image')
352
353
354
            counters['skipped'] += 1
            result_dict = {}
        else:
355
356
          result_dict, result_losses_dict = batch_processor(
              tensor_dict, sess, batch, counters, losses_dict=losses_dict)
357
358
        if not result_dict:
          continue
359
360
        for key, value in iter(result_losses_dict.items()):
          aggregate_result_losses_dict[key].append(value)
361
        for evaluator in evaluators:
362
          # TODO(b/65130867): Use image_id tensor once we fix the input data
363
          # decoders to return correct image_id.
364
          # TODO(akuznetsa): result_dict contains batches of images, while
365
          # add_single_ground_truth_image_info expects a single image. Fix
366
          if (isinstance(result_dict, dict) and
367
              fields.InputDataFields.key in result_dict and
368
369
370
371
              result_dict[fields.InputDataFields.key]):
            image_id = result_dict[fields.InputDataFields.key]
          else:
            image_id = batch
372
          evaluator.add_single_ground_truth_image_info(
373
              image_id=image_id, groundtruth_dict=result_dict)
374
          evaluator.add_single_detected_image_info(
375
376
              image_id=image_id, detections_dict=result_dict)
      tf.logging.info('Running eval batches done.')
377
    except tf.errors.OutOfRangeError:
378
      tf.logging.info('Done evaluating -- epoch limit reached')
379
380
    finally:
      # When done, ask the threads to stop.
381
382
      tf.logging.info('# success: %d', counters['success'])
      tf.logging.info('# skipped: %d', counters['skipped'])
383
      all_evaluator_metrics = {}
384
385
386
387
388
389
390
391
      if eval_export_path and eval_export_path is not None:
        for evaluator in evaluators:
          if (isinstance(evaluator, coco_evaluation.CocoDetectionEvaluator) or
              isinstance(evaluator, coco_evaluation.CocoMaskEvaluator)):
            tf.logging.info('Started dumping to json file.')
            evaluator.dump_detections_to_json_file(
                json_output_path=eval_export_path)
            tf.logging.info('Finished dumping to json file.')
392
393
394
395
396
397
398
      for evaluator in evaluators:
        metrics = evaluator.evaluate()
        evaluator.clear()
        if any(key in all_evaluator_metrics for key in metrics):
          raise ValueError('Metric names between evaluators must not collide.')
        all_evaluator_metrics.update(metrics)
      global_step = tf.train.global_step(sess, tf.train.get_global_step())
399
400
401

      for key, value in iter(aggregate_result_losses_dict.items()):
        all_evaluator_metrics['Losses/' + key] = np.mean(value)
402
403
404
405
406
407
408
409
410
      if process_metrics_fn and checkpoint_file:
        m = re.search(r'model.ckpt-(\d+)$', checkpoint_file)
        if not m:
          tf.logging.error('Failed to parse checkpoint number from: %s',
                           checkpoint_file)
        else:
          checkpoint_number = int(m.group(1))
          process_metrics_fn(checkpoint_number, all_evaluator_metrics,
                             checkpoint_file)
411
  sess.close()
412
  return (global_step, all_evaluator_metrics)
413
414


415
# TODO(rathodv): Add tests.
416
417
def repeated_checkpoint_run(tensor_dict,
                            summary_dir,
418
                            evaluators,
419
420
421
422
423
424
425
                            batch_processor=None,
                            checkpoint_dirs=None,
                            variables_to_restore=None,
                            restore_fn=None,
                            num_batches=1,
                            eval_interval_secs=120,
                            max_number_of_evaluations=None,
426
                            max_evaluation_global_step=None,
427
428
                            master='',
                            save_graph=False,
429
                            save_graph_dir='',
430
                            losses_dict=None,
431
432
                            eval_export_path=None,
                            process_metrics_fn=None):
433
434
435
436
437
438
439
440
441
442
443
  """Periodically evaluates desired tensors using checkpoint_dirs or restore_fn.

  This function repeatedly loads a checkpoint and evaluates a desired
  set of tensors (provided by tensor_dict) and hands the resulting numpy
  arrays to a function result_processor which can be used to further
  process/save/visualize the results.

  Args:
    tensor_dict: a dictionary holding tensors representing a batch of detections
      and corresponding groundtruth annotations.
    summary_dir: a directory to write metrics summaries.
444
445
446
    evaluators: a list of object of type DetectionEvaluator to be used for
      evaluation. Note that the metric names produced by different evaluators
      must be unique.
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
    batch_processor: a function taking three arguments:
      1. tensor_dict: the same tensor_dict that is passed in as the first
        argument to this function.
      2. sess: a tensorflow session
      3. batch_index: an integer representing the index of the batch amongst
        all batches
      By default, batch_processor is None, which defaults to running:
        return sess.run(tensor_dict)
    checkpoint_dirs: list of directories to load into a DetectionModel or an
      EnsembleModel if restore_fn isn't set. Also used to determine when to run
      next evaluation. Must have at least one element.
    variables_to_restore: None, or a dictionary mapping variable names found in
      a checkpoint to model variables. The dictionary would normally be
      generated by creating a tf.train.ExponentialMovingAverage object and
      calling its variables_to_restore() method. Not used if restore_fn is set.
    restore_fn: a function that takes a tf.Session object and correctly restores
      all necessary variables from the correct checkpoint file.
    num_batches: the number of batches to use for evaluation.
    eval_interval_secs: the number of seconds between each evaluation run.
    max_number_of_evaluations: the max number of iterations of the evaluation.
      If the value is left as None the evaluation continues indefinitely.
468
    max_evaluation_global_step: global step when evaluation stops.
469
470
471
472
    master: the location of the Tensorflow session.
    save_graph: whether or not the Tensorflow graph is saved as a pbtxt file.
    save_graph_dir: where to save on disk the Tensorflow graph. If store_graph
      is True this must be non-empty.
473
    losses_dict: optional dictionary of scalar detection losses.
474
475
    eval_export_path: Path for saving a json file that contains the detection
      results in json format.
476
477
478
479
480
481
    process_metrics_fn: a callback called with evaluation results after each
      evaluation is done.  It could be used e.g. to back up checkpoints with
      best evaluation scores, or to call an external system to update evaluation
      results in order to drive best hyper-parameter search.  Parameters are:
      int checkpoint_number, Dict[str, ObjectDetectionEvalMetrics] metrics,
      str checkpoint_file path.
482
483
484
485

  Returns:
    metrics: A dictionary containing metric names and values in the latest
      evaluation.
486
487
488
489
490
491
492

  Raises:
    ValueError: if max_num_of_evaluations is not None or a positive number.
    ValueError: if checkpoint_dirs doesn't have at least one element.
  """
  if max_number_of_evaluations and max_number_of_evaluations <= 0:
    raise ValueError(
493
494
495
496
        '`max_number_of_evaluations` must be either None or a positive number.')
  if max_evaluation_global_step and max_evaluation_global_step <= 0:
    raise ValueError(
        '`max_evaluation_global_step` must be either None or positive.')
497
498
499
500
501
502
503
504

  if not checkpoint_dirs:
    raise ValueError('`checkpoint_dirs` must have at least one entry.')

  last_evaluated_model_path = None
  number_of_evaluations = 0
  while True:
    start = time.time()
505
    tf.logging.info('Starting evaluation at ' + time.strftime(
506
        '%Y-%m-%d-%H:%M:%S', time.gmtime()))
507
508
    model_path = tf.train.latest_checkpoint(checkpoint_dirs[0])
    if not model_path:
509
510
      tf.logging.info('No model found in %s. Will try again in %d seconds',
                      checkpoint_dirs[0], eval_interval_secs)
511
    elif model_path == last_evaluated_model_path:
512
513
      tf.logging.info('Found already evaluated checkpoint. Will try again in '
                      '%d seconds', eval_interval_secs)
514
515
    else:
      last_evaluated_model_path = model_path
516
517
518
519
520
521
522
523
524
525
526
527
      global_step, metrics = _run_checkpoint_once(
          tensor_dict,
          evaluators,
          batch_processor,
          checkpoint_dirs,
          variables_to_restore,
          restore_fn,
          num_batches,
          master,
          save_graph,
          save_graph_dir,
          losses_dict=losses_dict,
528
529
          eval_export_path=eval_export_path,
          process_metrics_fn=process_metrics_fn)
530
      write_metrics(metrics, global_step, summary_dir)
531
532
533
534
      if (max_evaluation_global_step and
          global_step >= max_evaluation_global_step):
        tf.logging.info('Finished evaluation!')
        break
535
536
537
538
    number_of_evaluations += 1

    if (max_number_of_evaluations and
        number_of_evaluations >= max_number_of_evaluations):
539
      tf.logging.info('Finished evaluation!')
540
541
542
543
      break
    time_to_next_eval = start + eval_interval_secs - time.time()
    if time_to_next_eval > 0:
      time.sleep(time_to_next_eval)
544
545
546
547

  return metrics


548
549
550
551
552
553
def _scale_box_to_absolute(args):
  boxes, image_shape = args
  return box_list_ops.to_absolute_coordinates(
      box_list.BoxList(boxes), image_shape[0], image_shape[1]).get()


554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
def _resize_detection_masks(arg_tuple):
  """Resizes detection masks.

  Args:
    arg_tuple: A (detection_boxes, detection_masks, image_shape, pad_shape)
      tuple where
      detection_boxes is a tf.float32 tensor of size [num_masks, 4] containing
        the box corners. Row i contains [ymin, xmin, ymax, xmax] of the box
        corresponding to mask i. Note that the box corners are in
        normalized coordinates.
      detection_masks is a tensor of size
        [num_masks, mask_height, mask_width].
      image_shape is a tensor of shape [2]
      pad_shape is a tensor of shape [2] --- this is assumed to be greater
        than or equal to image_shape along both dimensions and represents a
        shape to-be-padded-to.

  Returns:
  """
  detection_boxes, detection_masks, image_shape, pad_shape = arg_tuple
574
575
  detection_masks_reframed = ops.reframe_box_masks_to_image_masks(
      detection_masks, detection_boxes, image_shape[0], image_shape[1])
576
577
578
579
580
581
582
583
  paddings = tf.concat(
      [tf.zeros([3, 1], dtype=tf.int32),
       tf.expand_dims(
           tf.concat([tf.zeros([1], dtype=tf.int32),
                      pad_shape-image_shape], axis=0),
           1)], axis=1)
  detection_masks_reframed = tf.pad(detection_masks_reframed, paddings)

584
585
586
587
588
  # If the masks are currently float, binarize them. Otherwise keep them as
  # integers, since they have already been thresholded.
  if detection_masks_reframed.dtype == tf.float32:
    detection_masks_reframed = tf.greater(detection_masks_reframed, 0.5)
  return tf.cast(detection_masks_reframed, tf.uint8)
589
590


591
592
593
594
595
596
597
598
599
600
def resize_detection_masks(detection_boxes, detection_masks,
                           original_image_spatial_shapes):
  """Resizes per-box detection masks to be relative to the entire image.

  Note that this function only works when the spatial size of all images in
  the batch is the same. If not, this function should be used with batch_size=1.

  Args:
    detection_boxes: A [batch_size, num_instances, 4] float tensor containing
      bounding boxes.
601
    detection_masks: A [batch_size, num_instances, height, width] float tensor
602
603
604
605
606
607
608
      containing binary instance masks per box.
    original_image_spatial_shapes: a [batch_size, 3] shaped int tensor
      holding the spatial dimensions of each image in the batch.
  Returns:
    masks: Masks resized to the spatial extents given by
      (original_image_spatial_shapes[0, 0], original_image_spatial_shapes[0, 1])
  """
609
610
611
612
613
614
615
616
  # modify original image spatial shapes to be max along each dim
  # in evaluator, should have access to original_image_spatial_shape field
  # in add_Eval_Dict
  max_spatial_shape = tf.reduce_max(
      original_image_spatial_shapes, axis=0, keep_dims=True)
  tiled_max_spatial_shape = tf.tile(
      max_spatial_shape,
      multiples=[tf.shape(original_image_spatial_shapes)[0], 1])
617
618
  return shape_utils.static_or_dynamic_map_fn(
      _resize_detection_masks,
619
620
621
622
      elems=[detection_boxes,
             detection_masks,
             original_image_spatial_shapes,
             tiled_max_spatial_shape],
623
624
625
      dtype=tf.uint8)


626
def _resize_groundtruth_masks(args):
627
628
  """Resizes groundtruth masks to the original image size."""
  mask, true_image_shape, original_image_shape, pad_shape = args
629
630
631
  true_height = true_image_shape[0]
  true_width = true_image_shape[1]
  mask = mask[:, :true_height, :true_width]
632
633
634
  mask = tf.expand_dims(mask, 3)
  mask = tf.image.resize_images(
      mask,
635
      original_image_shape,
636
637
      method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,
      align_corners=True)
638
639
640
641
642
643
644
645
646

  paddings = tf.concat(
      [tf.zeros([3, 1], dtype=tf.int32),
       tf.expand_dims(
           tf.concat([tf.zeros([1], dtype=tf.int32),
                      pad_shape-original_image_shape], axis=0),
           1)], axis=1)
  mask = tf.pad(tf.squeeze(mask, 3), paddings)
  return tf.cast(mask, tf.uint8)
647
648


649
650
651
652
653
654
655
656
657
658
659
def _resize_surface_coordinate_masks(args):
  detection_boxes, surface_coords, image_shape = args
  surface_coords_v, surface_coords_u = tf.unstack(surface_coords, axis=-1)
  surface_coords_v_reframed = ops.reframe_box_masks_to_image_masks(
      surface_coords_v, detection_boxes, image_shape[0], image_shape[1])
  surface_coords_u_reframed = ops.reframe_box_masks_to_image_masks(
      surface_coords_u, detection_boxes, image_shape[0], image_shape[1])
  return tf.stack([surface_coords_v_reframed, surface_coords_u_reframed],
                  axis=-1)


660
661
662
663
664
def _scale_keypoint_to_absolute(args):
  keypoints, image_shape = args
  return keypoint_ops.scale(keypoints, image_shape[0], image_shape[1])


665
666
667
668
669
670
671
672
673
674
675
676
677
def result_dict_for_single_example(image,
                                   key,
                                   detections,
                                   groundtruth=None,
                                   class_agnostic=False,
                                   scale_to_absolute=False):
  """Merges all detection and groundtruth information for a single example.

  Note that evaluation tools require classes that are 1-indexed, and so this
  function performs the offset. If `class_agnostic` is True, all output classes
  have label 1.

  Args:
678
    image: A single 4D uint8 image tensor of shape [1, H, W, C].
679
680
681
682
683
684
685
686
687
688
689
690
691
    key: A single string tensor identifying the image.
    detections: A dictionary of detections, returned from
      DetectionModel.postprocess().
    groundtruth: (Optional) Dictionary of groundtruth items, with fields:
      'groundtruth_boxes': [num_boxes, 4] float32 tensor of boxes, in
        normalized coordinates.
      'groundtruth_classes': [num_boxes] int64 tensor of 1-indexed classes.
      'groundtruth_area': [num_boxes] float32 tensor of bbox area. (Optional)
      'groundtruth_is_crowd': [num_boxes] int64 tensor. (Optional)
      'groundtruth_difficult': [num_boxes] int64 tensor. (Optional)
      'groundtruth_group_of': [num_boxes] int64 tensor. (Optional)
      'groundtruth_instance_masks': 3D int64 tensor of instance masks
        (Optional).
692
693
      'groundtruth_keypoints': [num_boxes, num_keypoints, 2] float32 tensor with
        keypoints (Optional).
694
695
    class_agnostic: Boolean indicating whether the detections are class-agnostic
      (i.e. binary). Default False.
696
697
698
    scale_to_absolute: Boolean indicating whether boxes and keypoints should be
      scaled to absolute coordinates. Note that for IoU based evaluations, it
      does not matter whether boxes are expressed in absolute or relative
699
700
701
702
703
704
705
706
707
708
709
      coordinates. Default False.

  Returns:
    A dictionary with:
    'original_image': A [1, H, W, C] uint8 image tensor.
    'key': A string tensor with image identifier.
    'detection_boxes': [max_detections, 4] float32 tensor of boxes, in
      normalized or absolute coordinates, depending on the value of
      `scale_to_absolute`.
    'detection_scores': [max_detections] float32 tensor of scores.
    'detection_classes': [max_detections] int64 tensor of 1-indexed classes.
710
711
    'detection_masks': [max_detections, H, W] float32 tensor of binarized
      masks, reframed to full image masks.
712
713
714
715
716
717
718
719
720
721
722
    'groundtruth_boxes': [num_boxes, 4] float32 tensor of boxes, in
      normalized or absolute coordinates, depending on the value of
      `scale_to_absolute`. (Optional)
    'groundtruth_classes': [num_boxes] int64 tensor of 1-indexed classes.
      (Optional)
    'groundtruth_area': [num_boxes] float32 tensor of bbox area. (Optional)
    'groundtruth_is_crowd': [num_boxes] int64 tensor. (Optional)
    'groundtruth_difficult': [num_boxes] int64 tensor. (Optional)
    'groundtruth_group_of': [num_boxes] int64 tensor. (Optional)
    'groundtruth_instance_masks': 3D int64 tensor of instance masks
      (Optional).
723
724
    'groundtruth_keypoints': [num_boxes, num_keypoints, 2] float32 tensor with
      keypoints (Optional).
725
  """
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749

  if groundtruth:
    max_gt_boxes = tf.shape(
        groundtruth[fields.InputDataFields.groundtruth_boxes])[0]
    for gt_key in groundtruth:
      # expand groundtruth dict along the batch dimension.
      groundtruth[gt_key] = tf.expand_dims(groundtruth[gt_key], 0)

  for detection_key in detections:
    detections[detection_key] = tf.expand_dims(
        detections[detection_key][0], axis=0)

  batched_output_dict = result_dict_for_batched_example(
      image,
      tf.expand_dims(key, 0),
      detections,
      groundtruth,
      class_agnostic,
      scale_to_absolute,
      max_gt_boxes=max_gt_boxes)

  exclude_keys = [
      fields.InputDataFields.original_image,
      fields.DetectionResultFields.num_detections,
750
      fields.InputDataFields.num_groundtruth_boxes
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
  ]

  output_dict = {
      fields.InputDataFields.original_image:
          batched_output_dict[fields.InputDataFields.original_image]
  }

  for key in batched_output_dict:
    # remove the batch dimension.
    if key not in exclude_keys:
      output_dict[key] = tf.squeeze(batched_output_dict[key], 0)
  return output_dict


def result_dict_for_batched_example(images,
                                    keys,
                                    detections,
                                    groundtruth=None,
                                    class_agnostic=False,
                                    scale_to_absolute=False,
                                    original_image_spatial_shapes=None,
772
                                    true_image_shapes=None,
773
774
                                    max_gt_boxes=None,
                                    label_id_offset=1):
775
776
777
778
779
  """Merges all detection and groundtruth information for a single example.

  Note that evaluation tools require classes that are 1-indexed, and so this
  function performs the offset. If `class_agnostic` is True, all output classes
  have label 1.
780
781
782
783
  The groundtruth coordinates of boxes/keypoints in 'groundtruth' dictionary are
  normalized relative to the (potentially padded) input image, while the
  coordinates in 'detection' dictionary are normalized relative to the true
  image shape.
784
785
786

  Args:
    images: A single 4D uint8 image tensor of shape [batch_size, H, W, C].
787
    keys: A [batch_size] string/int tensor with image identifier.
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
    detections: A dictionary of detections, returned from
      DetectionModel.postprocess().
    groundtruth: (Optional) Dictionary of groundtruth items, with fields:
      'groundtruth_boxes': [batch_size, max_number_of_boxes, 4] float32 tensor
        of boxes, in normalized coordinates.
      'groundtruth_classes':  [batch_size, max_number_of_boxes] int64 tensor of
        1-indexed classes.
      'groundtruth_area': [batch_size, max_number_of_boxes] float32 tensor of
        bbox area. (Optional)
      'groundtruth_is_crowd':[batch_size, max_number_of_boxes] int64
        tensor. (Optional)
      'groundtruth_difficult': [batch_size, max_number_of_boxes] int64
        tensor. (Optional)
      'groundtruth_group_of': [batch_size, max_number_of_boxes] int64
        tensor. (Optional)
      'groundtruth_instance_masks': 4D int64 tensor of instance
        masks (Optional).
805
806
807
808
      'groundtruth_keypoints': [batch_size, max_number_of_boxes, num_keypoints,
        2] float32 tensor with keypoints (Optional).
      'groundtruth_keypoint_visibilities': [batch_size, max_number_of_boxes,
        num_keypoints] bool tensor with keypoint visibilities (Optional).
809
810
      'groundtruth_labeled_classes': [batch_size, num_classes] int64
        tensor of 1-indexed classes. (Optional)
811
812
813
814
815
816
      'groundtruth_dp_num_points': [batch_size, max_number_of_boxes] int32
        tensor. (Optional)
      'groundtruth_dp_part_ids': [batch_size, max_number_of_boxes,
        max_sampled_points] int32 tensor. (Optional)
      'groundtruth_dp_surface_coords_list': [batch_size, max_number_of_boxes,
        max_sampled_points, 4] float32 tensor. (Optional)
817
818
819
820
821
822
823
824
    class_agnostic: Boolean indicating whether the detections are class-agnostic
      (i.e. binary). Default False.
    scale_to_absolute: Boolean indicating whether boxes and keypoints should be
      scaled to absolute coordinates. Note that for IoU based evaluations, it
      does not matter whether boxes are expressed in absolute or relative
      coordinates. Default False.
    original_image_spatial_shapes: A 2D int32 tensor of shape [batch_size, 2]
      used to resize the image. When set to None, the image size is retained.
825
826
    true_image_shapes: A 2D int32 tensor of shape [batch_size, 3]
      containing the size of the unpadded original_image.
827
828
    max_gt_boxes: [batch_size] tensor representing the maximum number of
      groundtruth boxes to pad.
829
    label_id_offset: offset for class ids.
830
831
832
833
834
835

  Returns:
    A dictionary with:
    'original_image': A [batch_size, H, W, C] uint8 image tensor.
    'original_image_spatial_shape': A [batch_size, 2] tensor containing the
      original image sizes.
836
837
    'true_image_shape': A [batch_size, 3] tensor containing the size of
      the unpadded original_image.
838
839
840
841
842
843
844
    'key': A [batch_size] string tensor with image identifier.
    'detection_boxes': [batch_size, max_detections, 4] float32 tensor of boxes,
      in normalized or absolute coordinates, depending on the value of
      `scale_to_absolute`.
    'detection_scores': [batch_size, max_detections] float32 tensor of scores.
    'detection_classes': [batch_size, max_detections] int64 tensor of 1-indexed
      classes.
845
846
847
    'detection_masks': [batch_size, max_detections, H, W] uint8 tensor of
      instance masks, reframed to full image masks. Note that these may be
      binarized (e.g. {0, 1}), or may contain 1-indexed part labels. (Optional)
848
849
850
851
    'detection_keypoints': [batch_size, max_detections, num_keypoints, 2]
      float32 tensor containing keypoint coordinates. (Optional)
    'detection_keypoint_scores': [batch_size, max_detections, num_keypoints]
      float32 tensor containing keypoint scores. (Optional)
852
853
854
    'detection_surface_coords': [batch_size, max_detection, H, W, 2] float32
      tensor with normalized surface coordinates (e.g. DensePose UV
      coordinates). (Optional)
855
856
857
858
859
860
861
862
863
864
865
866
867
868
    'num_detections': [batch_size] int64 tensor containing number of valid
      detections.
    'groundtruth_boxes': [batch_size, num_boxes, 4] float32 tensor of boxes, in
      normalized or absolute coordinates, depending on the value of
      `scale_to_absolute`. (Optional)
    'groundtruth_classes': [batch_size, num_boxes] int64 tensor of 1-indexed
      classes. (Optional)
    'groundtruth_area': [batch_size, num_boxes] float32 tensor of bbox
      area. (Optional)
    'groundtruth_is_crowd': [batch_size, num_boxes] int64 tensor. (Optional)
    'groundtruth_difficult': [batch_size, num_boxes] int64 tensor. (Optional)
    'groundtruth_group_of': [batch_size, num_boxes] int64 tensor. (Optional)
    'groundtruth_instance_masks': 4D int64 tensor of instance masks
      (Optional).
869
870
871
872
    'groundtruth_keypoints': [batch_size, num_boxes, num_keypoints, 2] float32
      tensor with keypoints (Optional).
    'groundtruth_keypoint_visibilities': [batch_size, num_boxes, num_keypoints]
      bool tensor with keypoint visibilities (Optional).
873
874
    'groundtruth_labeled_classes': [batch_size, num_classes]  int64 tensor
      of 1-indexed classes. (Optional)
875
876
877
878
    'num_groundtruth_boxes': [batch_size] tensor containing the maximum number
      of groundtruth boxes per image.

  Raises:
879
880
881
882
    ValueError: if original_image_spatial_shape is not 2D int32 tensor of shape
      [2].
    ValueError: if true_image_shapes is not 2D int32 tensor of shape
      [3].
883
  """
884
  input_data_fields = fields.InputDataFields
885
886
887
888
889
890
891
892
893
894
895
  if original_image_spatial_shapes is None:
    original_image_spatial_shapes = tf.tile(
        tf.expand_dims(tf.shape(images)[1:3], axis=0),
        multiples=[tf.shape(images)[0], 1])
  else:
    if (len(original_image_spatial_shapes.shape) != 2 and
        original_image_spatial_shapes.shape[1] != 2):
      raise ValueError(
          '`original_image_spatial_shape` should be a 2D tensor of shape '
          '[batch_size, 2].')

896
897
898
899
900
901
902
903
904
905
  if true_image_shapes is None:
    true_image_shapes = tf.tile(
        tf.expand_dims(tf.shape(images)[1:4], axis=0),
        multiples=[tf.shape(images)[0], 1])
  else:
    if (len(true_image_shapes.shape) != 2
        and true_image_shapes.shape[1] != 3):
      raise ValueError('`true_image_shapes` should be a 2D tensor of '
                       'shape [batch_size, 3].')

906
  output_dict = {
907
908
909
910
      input_data_fields.original_image:
          images,
      input_data_fields.key:
          keys,
911
      input_data_fields.original_image_spatial_shape: (
912
913
914
          original_image_spatial_shapes),
      input_data_fields.true_image_shape:
          true_image_shapes
915
916
917
  }

  detection_fields = fields.DetectionResultFields
918
919
  detection_boxes = detections[detection_fields.detection_boxes]
  detection_scores = detections[detection_fields.detection_scores]
920
921
  num_detections = tf.cast(detections[detection_fields.num_detections],
                           dtype=tf.int32)
922
923
924
925
926

  if class_agnostic:
    detection_classes = tf.ones_like(detection_scores, dtype=tf.int64)
  else:
    detection_classes = (
927
        tf.to_int64(detections[detection_fields.detection_classes]) +
928
        label_id_offset)
929

930
931
  if scale_to_absolute:
    output_dict[detection_fields.detection_boxes] = (
932
933
934
935
        shape_utils.static_or_dynamic_map_fn(
            _scale_box_to_absolute,
            elems=[detection_boxes, original_image_spatial_shapes],
            dtype=tf.float32))
936
937
  else:
    output_dict[detection_fields.detection_boxes] = detection_boxes
938
  output_dict[detection_fields.detection_classes] = detection_classes
939
  output_dict[detection_fields.detection_scores] = detection_scores
940
  output_dict[detection_fields.num_detections] = num_detections
941
942

  if detection_fields.detection_masks in detections:
943
    detection_masks = detections[detection_fields.detection_masks]
944
945
946
    output_dict[detection_fields.detection_masks] = resize_detection_masks(
        detection_boxes, detection_masks, original_image_spatial_shapes)

947
948
949
950
951
952
953
954
955
    if detection_fields.detection_surface_coords in detections:
      detection_surface_coords = detections[
          detection_fields.detection_surface_coords]
      output_dict[detection_fields.detection_surface_coords] = (
          shape_utils.static_or_dynamic_map_fn(
              _resize_surface_coordinate_masks,
              elems=[detection_boxes, detection_surface_coords,
                     original_image_spatial_shapes],
              dtype=tf.float32))
956

957
  if detection_fields.detection_keypoints in detections:
958
    detection_keypoints = detections[detection_fields.detection_keypoints]
959
960
961
    output_dict[detection_fields.detection_keypoints] = detection_keypoints
    if scale_to_absolute:
      output_dict[detection_fields.detection_keypoints] = (
962
963
964
965
          shape_utils.static_or_dynamic_map_fn(
              _scale_keypoint_to_absolute,
              elems=[detection_keypoints, original_image_spatial_shapes],
              dtype=tf.float32))
966
967
968
969
970
971
    if detection_fields.detection_keypoint_scores in detections:
      output_dict[detection_fields.detection_keypoint_scores] = detections[
          detection_fields.detection_keypoint_scores]
    else:
      output_dict[detection_fields.detection_keypoint_scores] = tf.ones_like(
          detections[detection_fields.detection_keypoints][:, :, :, 0])
972
973

  if groundtruth:
974
975
976
977
978
979
980
    if max_gt_boxes is None:
      if input_data_fields.num_groundtruth_boxes in groundtruth:
        max_gt_boxes = groundtruth[input_data_fields.num_groundtruth_boxes]
      else:
        raise ValueError(
            'max_gt_boxes must be provided when processing batched examples.')

981
    if input_data_fields.groundtruth_instance_masks in groundtruth:
982
      masks = groundtruth[input_data_fields.groundtruth_instance_masks]
983
984
985
986
987
      max_spatial_shape = tf.reduce_max(
          original_image_spatial_shapes, axis=0, keep_dims=True)
      tiled_max_spatial_shape = tf.tile(
          max_spatial_shape,
          multiples=[tf.shape(original_image_spatial_shapes)[0], 1])
988
989
990
      groundtruth[input_data_fields.groundtruth_instance_masks] = (
          shape_utils.static_or_dynamic_map_fn(
              _resize_groundtruth_masks,
991
992
993
              elems=[masks, true_image_shapes,
                     original_image_spatial_shapes,
                     tiled_max_spatial_shape],
994
995
              dtype=tf.uint8))

996
    output_dict.update(groundtruth)
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016

    image_shape = tf.cast(tf.shape(images), tf.float32)
    image_height, image_width = image_shape[1], image_shape[2]

    def _scale_box_to_normalized_true_image(args):
      """Scale the box coordinates to be relative to the true image shape."""
      boxes, true_image_shape = args
      true_image_shape = tf.cast(true_image_shape, tf.float32)
      true_height, true_width = true_image_shape[0], true_image_shape[1]
      normalized_window = tf.stack([0.0, 0.0, true_height / image_height,
                                    true_width / image_width])
      return box_list_ops.change_coordinate_frame(
          box_list.BoxList(boxes), normalized_window).get()

    groundtruth_boxes = groundtruth[input_data_fields.groundtruth_boxes]
    groundtruth_boxes = shape_utils.static_or_dynamic_map_fn(
        _scale_box_to_normalized_true_image,
        elems=[groundtruth_boxes, true_image_shapes], dtype=tf.float32)
    output_dict[input_data_fields.groundtruth_boxes] = groundtruth_boxes

1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
    if input_data_fields.groundtruth_keypoints in groundtruth:
      # If groundtruth_keypoints is in the groundtruth dictionary. Update the
      # coordinates to conform with the true image shape.
      def _scale_keypoints_to_normalized_true_image(args):
        """Scale the box coordinates to be relative to the true image shape."""
        keypoints, true_image_shape = args
        true_image_shape = tf.cast(true_image_shape, tf.float32)
        true_height, true_width = true_image_shape[0], true_image_shape[1]
        normalized_window = tf.stack(
            [0.0, 0.0, true_height / image_height, true_width / image_width])
        return keypoint_ops.change_coordinate_frame(keypoints,
                                                    normalized_window)

      groundtruth_keypoints = groundtruth[
          input_data_fields.groundtruth_keypoints]
      groundtruth_keypoints = shape_utils.static_or_dynamic_map_fn(
          _scale_keypoints_to_normalized_true_image,
          elems=[groundtruth_keypoints, true_image_shapes],
          dtype=tf.float32)
      output_dict[
          input_data_fields.groundtruth_keypoints] = groundtruth_keypoints

1039
    if scale_to_absolute:
1040
      groundtruth_boxes = output_dict[input_data_fields.groundtruth_boxes]
1041
      output_dict[input_data_fields.groundtruth_boxes] = (
1042
1043
1044
1045
          shape_utils.static_or_dynamic_map_fn(
              _scale_box_to_absolute,
              elems=[groundtruth_boxes, original_image_spatial_shapes],
              dtype=tf.float32))
1046
1047
1048
1049
1050
1051
1052
1053
      if input_data_fields.groundtruth_keypoints in groundtruth:
        groundtruth_keypoints = output_dict[
            input_data_fields.groundtruth_keypoints]
        output_dict[input_data_fields.groundtruth_keypoints] = (
            shape_utils.static_or_dynamic_map_fn(
                _scale_keypoint_to_absolute,
                elems=[groundtruth_keypoints, original_image_spatial_shapes],
                dtype=tf.float32))
1054

1055
1056
1057
1058
1059
1060
    # For class-agnostic models, groundtruth classes all become 1.
    if class_agnostic:
      groundtruth_classes = groundtruth[input_data_fields.groundtruth_classes]
      groundtruth_classes = tf.ones_like(groundtruth_classes, dtype=tf.int64)
      output_dict[input_data_fields.groundtruth_classes] = groundtruth_classes

1061
1062
    output_dict[input_data_fields.num_groundtruth_boxes] = max_gt_boxes

1063
  return output_dict
1064
1065


1066
1067
1068
1069
1070
1071
1072
1073
def get_evaluators(eval_config, categories, evaluator_options=None):
  """Returns the evaluator class according to eval_config, valid for categories.

  Args:
    eval_config: An `eval_pb2.EvalConfig`.
    categories: A list of dicts, each of which has the following keys -
        'id': (required) an integer id uniquely identifying this category.
        'name': (required) string representing category name e.g., 'cat', 'dog'.
1074
1075
        'keypoints': (optional) dict mapping this category's keypoints to unique
          ids.
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
    evaluator_options: A dictionary of metric names (see
      EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization
      keyword arguments. For example:
      evalator_options = {
        'coco_detection_metrics': {'include_metrics_per_category': True}
      }

  Returns:
    An list of instances of DetectionEvaluator.

  Raises:
    ValueError: if metric is not in the metric class dictionary.
  """
  evaluator_options = evaluator_options or {}
  eval_metric_fn_keys = eval_config.metrics_set
  if not eval_metric_fn_keys:
    eval_metric_fn_keys = [EVAL_DEFAULT_METRIC]
  evaluators_list = []
  for eval_metric_fn_key in eval_metric_fn_keys:
    if eval_metric_fn_key not in EVAL_METRICS_CLASS_DICT:
      raise ValueError('Metric not found: {}'.format(eval_metric_fn_key))
    kwargs_dict = (evaluator_options[eval_metric_fn_key] if eval_metric_fn_key
                   in evaluator_options else {})
    evaluators_list.append(EVAL_METRICS_CLASS_DICT[eval_metric_fn_key](
        categories,
        **kwargs_dict))
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127

  if isinstance(eval_config, eval_pb2.EvalConfig):
    parameterized_metrics = eval_config.parameterized_metric
    for parameterized_metric in parameterized_metrics:
      assert parameterized_metric.HasField('parameterized_metric')
      if parameterized_metric.WhichOneof(
          'parameterized_metric') == EVAL_KEYPOINT_METRIC:
        keypoint_metrics = parameterized_metric.coco_keypoint_metrics
        # Create category to keypoints mapping dict.
        category_keypoints = {}
        class_label = keypoint_metrics.class_label
        category = None
        for cat in categories:
          if cat['name'] == class_label:
            category = cat
            break
        if not category:
          continue
        keypoints_for_this_class = category['keypoints']
        category_keypoints = [{
            'id': keypoints_for_this_class[kp_name], 'name': kp_name
        } for kp_name in keypoints_for_this_class]
        # Create keypoint evaluator for this category.
        evaluators_list.append(EVAL_METRICS_CLASS_DICT[EVAL_KEYPOINT_METRIC](
            category['id'], category_keypoints, class_label,
            keypoint_metrics.keypoint_label_to_sigmas))
1128
1129
1130
1131
  return evaluators_list


def get_eval_metric_ops_for_evaluators(eval_config,
1132
                                       categories,
1133
1134
                                       eval_dict):
  """Returns eval metrics ops to use with `tf.estimator.EstimatorSpec`.
1135
1136

  Args:
1137
    eval_config: An `eval_pb2.EvalConfig`.
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
    categories: A list of dicts, each of which has the following keys -
        'id': (required) an integer id uniquely identifying this category.
        'name': (required) string representing category name e.g., 'cat', 'dog'.
    eval_dict: An evaluation dictionary, returned from
      result_dict_for_single_example().

  Returns:
    A dictionary of metric names to tuple of value_op and update_op that can be
    used as eval metric ops in tf.EstimatorSpec.
  """
  eval_metric_ops = {}
1149
1150
1151
1152
1153
  evaluator_options = evaluator_options_from_eval_config(eval_config)
  evaluators_list = get_evaluators(eval_config, categories, evaluator_options)
  for evaluator in evaluators_list:
    eval_metric_ops.update(evaluator.get_estimator_eval_metric_ops(
        eval_dict))
1154
  return eval_metric_ops
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173


def evaluator_options_from_eval_config(eval_config):
  """Produces a dictionary of evaluation options for each eval metric.

  Args:
    eval_config: An `eval_pb2.EvalConfig`.

  Returns:
    evaluator_options: A dictionary of metric names (see
      EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization
      keyword arguments. For example:
      evalator_options = {
        'coco_detection_metrics': {'include_metrics_per_category': True}
      }
  """
  eval_metric_fn_keys = eval_config.metrics_set
  evaluator_options = {}
  for eval_metric_fn_key in eval_metric_fn_keys:
1174
1175
    if eval_metric_fn_key in (
        'coco_detection_metrics', 'coco_mask_metrics', 'lvis_mask_metrics'):
1176
1177
1178
1179
      evaluator_options[eval_metric_fn_key] = {
          'include_metrics_per_category': (
              eval_config.include_metrics_per_category)
      }
1180
1181
1182
1183
1184
1185

      if (hasattr(eval_config, 'all_metrics_per_category') and
          eval_config.all_metrics_per_category):
        evaluator_options[eval_metric_fn_key].update({
            'all_metrics_per_category': eval_config.all_metrics_per_category
        })
1186
1187
1188
1189
1190
1191
1192
1193
1194
      # For coco detection eval, if the eval_config proto contains the
      # "skip_predictions_for_unlabeled_class" field, include this field in
      # evaluator_options.
      if eval_metric_fn_key == 'coco_detection_metrics' and hasattr(
          eval_config, 'skip_predictions_for_unlabeled_class'):
        evaluator_options[eval_metric_fn_key].update({
            'skip_predictions_for_unlabeled_class':
                (eval_config.skip_predictions_for_unlabeled_class)
        })
1195
1196
1197
1198
1199
1200
      for super_category in eval_config.super_categories:
        if 'super_categories' not in evaluator_options[eval_metric_fn_key]:
          evaluator_options[eval_metric_fn_key]['super_categories'] = {}
        key = super_category
        value = eval_config.super_categories[key].split(',')
        evaluator_options[eval_metric_fn_key]['super_categories'][key] = value
1201
1202
1203
1204
1205
      if eval_metric_fn_key == 'lvis_mask_metrics' and hasattr(
          eval_config, 'export_path'):
        evaluator_options[eval_metric_fn_key].update({
            'export_path': eval_config.export_path
        })
1206

1207
1208
1209
1210
1211
    elif eval_metric_fn_key == 'precision_at_recall_detection_metrics':
      evaluator_options[eval_metric_fn_key] = {
          'recall_lower_bound': (eval_config.recall_lower_bound),
          'recall_upper_bound': (eval_config.recall_upper_bound)
      }
1212
  return evaluator_options
1213
1214
1215
1216
1217


def has_densepose(eval_dict):
  return (fields.DetectionResultFields.detection_masks in eval_dict and
          fields.DetectionResultFields.detection_surface_coords in eval_dict)