You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

942 lines
41 KiB

6 years ago
  1. # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Common utility functions for evaluation."""
  16. import collections
  17. import os
  18. import re
  19. import time
  20. import numpy as np
  21. import tensorflow as tf
  22. from object_detection.core import box_list
  23. from object_detection.core import box_list_ops
  24. from object_detection.core import keypoint_ops
  25. from object_detection.core import standard_fields as fields
  26. from object_detection.metrics import coco_evaluation
  27. from object_detection.utils import label_map_util
  28. from object_detection.utils import object_detection_evaluation
  29. from object_detection.utils import ops
  30. from object_detection.utils import shape_utils
  31. from object_detection.utils import visualization_utils as vis_utils
  32. slim = tf.contrib.slim
  33. # A dictionary of metric names to classes that implement the metric. The classes
  34. # in the dictionary must implement
  35. # utils.object_detection_evaluation.DetectionEvaluator interface.
  36. EVAL_METRICS_CLASS_DICT = {
  37. 'coco_detection_metrics':
  38. coco_evaluation.CocoDetectionEvaluator,
  39. 'coco_mask_metrics':
  40. coco_evaluation.CocoMaskEvaluator,
  41. 'oid_challenge_detection_metrics':
  42. object_detection_evaluation.OpenImagesDetectionChallengeEvaluator,
  43. 'pascal_voc_detection_metrics':
  44. object_detection_evaluation.PascalDetectionEvaluator,
  45. 'weighted_pascal_voc_detection_metrics':
  46. object_detection_evaluation.WeightedPascalDetectionEvaluator,
  47. 'pascal_voc_instance_segmentation_metrics':
  48. object_detection_evaluation.PascalInstanceSegmentationEvaluator,
  49. 'weighted_pascal_voc_instance_segmentation_metrics':
  50. object_detection_evaluation.WeightedPascalInstanceSegmentationEvaluator,
  51. 'oid_V2_detection_metrics':
  52. object_detection_evaluation.OpenImagesDetectionEvaluator,
  53. }
  54. EVAL_DEFAULT_METRIC = 'coco_detection_metrics'
  55. def write_metrics(metrics, global_step, summary_dir):
  56. """Write metrics to a summary directory.
  57. Args:
  58. metrics: A dictionary containing metric names and values.
  59. global_step: Global step at which the metrics are computed.
  60. summary_dir: Directory to write tensorflow summaries to.
  61. """
  62. tf.logging.info('Writing metrics to tf summary.')
  63. summary_writer = tf.summary.FileWriterCache.get(summary_dir)
  64. for key in sorted(metrics):
  65. summary = tf.Summary(value=[
  66. tf.Summary.Value(tag=key, simple_value=metrics[key]),
  67. ])
  68. summary_writer.add_summary(summary, global_step)
  69. tf.logging.info('%s: %f', key, metrics[key])
  70. tf.logging.info('Metrics written to tf summary.')
  71. # TODO(rathodv): Add tests.
  72. def visualize_detection_results(result_dict,
  73. tag,
  74. global_step,
  75. categories,
  76. summary_dir='',
  77. export_dir='',
  78. agnostic_mode=False,
  79. show_groundtruth=False,
  80. groundtruth_box_visualization_color='black',
  81. min_score_thresh=.5,
  82. max_num_predictions=20,
  83. skip_scores=False,
  84. skip_labels=False,
  85. keep_image_id_for_visualization_export=False):
  86. """Visualizes detection results and writes visualizations to image summaries.
  87. This function visualizes an image with its detected bounding boxes and writes
  88. to image summaries which can be viewed on tensorboard. It optionally also
  89. writes images to a directory. In the case of missing entry in the label map,
  90. unknown class name in the visualization is shown as "N/A".
  91. Args:
  92. result_dict: a dictionary holding groundtruth and detection
  93. data corresponding to each image being evaluated. The following keys
  94. are required:
  95. 'original_image': a numpy array representing the image with shape
  96. [1, height, width, 3] or [1, height, width, 1]
  97. 'detection_boxes': a numpy array of shape [N, 4]
  98. 'detection_scores': a numpy array of shape [N]
  99. 'detection_classes': a numpy array of shape [N]
  100. The following keys are optional:
  101. 'groundtruth_boxes': a numpy array of shape [N, 4]
  102. 'groundtruth_keypoints': a numpy array of shape [N, num_keypoints, 2]
  103. Detections are assumed to be provided in decreasing order of score and for
  104. display, and we assume that scores are probabilities between 0 and 1.
  105. tag: tensorboard tag (string) to associate with image.
  106. global_step: global step at which the visualization are generated.
  107. categories: a list of dictionaries representing all possible categories.
  108. Each dict in this list has the following keys:
  109. 'id': (required) an integer id uniquely identifying this category
  110. 'name': (required) string representing category name
  111. e.g., 'cat', 'dog', 'pizza'
  112. 'supercategory': (optional) string representing the supercategory
  113. e.g., 'animal', 'vehicle', 'food', etc
  114. summary_dir: the output directory to which the image summaries are written.
  115. export_dir: the output directory to which images are written. If this is
  116. empty (default), then images are not exported.
  117. agnostic_mode: boolean (default: False) controlling whether to evaluate in
  118. class-agnostic mode or not.
  119. show_groundtruth: boolean (default: False) controlling whether to show
  120. groundtruth boxes in addition to detected boxes
  121. groundtruth_box_visualization_color: box color for visualizing groundtruth
  122. boxes
  123. min_score_thresh: minimum score threshold for a box to be visualized
  124. max_num_predictions: maximum number of detections to visualize
  125. skip_scores: whether to skip score when drawing a single detection
  126. skip_labels: whether to skip label when drawing a single detection
  127. keep_image_id_for_visualization_export: whether to keep image identifier in
  128. filename when exported to export_dir
  129. Raises:
  130. ValueError: if result_dict does not contain the expected keys (i.e.,
  131. 'original_image', 'detection_boxes', 'detection_scores',
  132. 'detection_classes')
  133. """
  134. detection_fields = fields.DetectionResultFields
  135. input_fields = fields.InputDataFields
  136. if not set([
  137. input_fields.original_image,
  138. detection_fields.detection_boxes,
  139. detection_fields.detection_scores,
  140. detection_fields.detection_classes,
  141. ]).issubset(set(result_dict.keys())):
  142. raise ValueError('result_dict does not contain all expected keys.')
  143. if show_groundtruth and input_fields.groundtruth_boxes not in result_dict:
  144. raise ValueError('If show_groundtruth is enabled, result_dict must contain '
  145. 'groundtruth_boxes.')
  146. tf.logging.info('Creating detection visualizations.')
  147. category_index = label_map_util.create_category_index(categories)
  148. image = np.squeeze(result_dict[input_fields.original_image], axis=0)
  149. if image.shape[2] == 1: # If one channel image, repeat in RGB.
  150. image = np.tile(image, [1, 1, 3])
  151. detection_boxes = result_dict[detection_fields.detection_boxes]
  152. detection_scores = result_dict[detection_fields.detection_scores]
  153. detection_classes = np.int32((result_dict[
  154. detection_fields.detection_classes]))
  155. detection_keypoints = result_dict.get(detection_fields.detection_keypoints)
  156. detection_masks = result_dict.get(detection_fields.detection_masks)
  157. detection_boundaries = result_dict.get(detection_fields.detection_boundaries)
  158. # Plot groundtruth underneath detections
  159. if show_groundtruth:
  160. groundtruth_boxes = result_dict[input_fields.groundtruth_boxes]
  161. groundtruth_keypoints = result_dict.get(input_fields.groundtruth_keypoints)
  162. vis_utils.visualize_boxes_and_labels_on_image_array(
  163. image=image,
  164. boxes=groundtruth_boxes,
  165. classes=None,
  166. scores=None,
  167. category_index=category_index,
  168. keypoints=groundtruth_keypoints,
  169. use_normalized_coordinates=False,
  170. max_boxes_to_draw=None,
  171. groundtruth_box_visualization_color=groundtruth_box_visualization_color)
  172. vis_utils.visualize_boxes_and_labels_on_image_array(
  173. image,
  174. detection_boxes,
  175. detection_classes,
  176. detection_scores,
  177. category_index,
  178. instance_masks=detection_masks,
  179. instance_boundaries=detection_boundaries,
  180. keypoints=detection_keypoints,
  181. use_normalized_coordinates=False,
  182. max_boxes_to_draw=max_num_predictions,
  183. min_score_thresh=min_score_thresh,
  184. agnostic_mode=agnostic_mode,
  185. skip_scores=skip_scores,
  186. skip_labels=skip_labels)
  187. if export_dir:
  188. if keep_image_id_for_visualization_export and result_dict[fields.
  189. InputDataFields()
  190. .key]:
  191. export_path = os.path.join(export_dir, 'export-{}-{}.png'.format(
  192. tag, result_dict[fields.InputDataFields().key]))
  193. else:
  194. export_path = os.path.join(export_dir, 'export-{}.png'.format(tag))
  195. vis_utils.save_image_array_as_png(image, export_path)
  196. summary = tf.Summary(value=[
  197. tf.Summary.Value(
  198. tag=tag,
  199. image=tf.Summary.Image(
  200. encoded_image_string=vis_utils.encode_image_array_as_png_str(
  201. image)))
  202. ])
  203. summary_writer = tf.summary.FileWriterCache.get(summary_dir)
  204. summary_writer.add_summary(summary, global_step)
  205. tf.logging.info('Detection visualizations written to summary with tag %s.',
  206. tag)
  207. def _run_checkpoint_once(tensor_dict,
  208. evaluators=None,
  209. batch_processor=None,
  210. checkpoint_dirs=None,
  211. variables_to_restore=None,
  212. restore_fn=None,
  213. num_batches=1,
  214. master='',
  215. save_graph=False,
  216. save_graph_dir='',
  217. losses_dict=None,
  218. eval_export_path=None,
  219. process_metrics_fn=None):
  220. """Evaluates metrics defined in evaluators and returns summaries.
  221. This function loads the latest checkpoint in checkpoint_dirs and evaluates
  222. all metrics defined in evaluators. The metrics are processed in batch by the
  223. batch_processor.
  224. Args:
  225. tensor_dict: a dictionary holding tensors representing a batch of detections
  226. and corresponding groundtruth annotations.
  227. evaluators: a list of object of type DetectionEvaluator to be used for
  228. evaluation. Note that the metric names produced by different evaluators
  229. must be unique.
  230. batch_processor: a function taking four arguments:
  231. 1. tensor_dict: the same tensor_dict that is passed in as the first
  232. argument to this function.
  233. 2. sess: a tensorflow session
  234. 3. batch_index: an integer representing the index of the batch amongst
  235. all batches
  236. By default, batch_processor is None, which defaults to running:
  237. return sess.run(tensor_dict)
  238. To skip an image, it suffices to return an empty dictionary in place of
  239. result_dict.
  240. checkpoint_dirs: list of directories to load into an EnsembleModel. If it
  241. has only one directory, EnsembleModel will not be used --
  242. a DetectionModel
  243. will be instantiated directly. Not used if restore_fn is set.
  244. variables_to_restore: None, or a dictionary mapping variable names found in
  245. a checkpoint to model variables. The dictionary would normally be
  246. generated by creating a tf.train.ExponentialMovingAverage object and
  247. calling its variables_to_restore() method. Not used if restore_fn is set.
  248. restore_fn: None, or a function that takes a tf.Session object and correctly
  249. restores all necessary variables from the correct checkpoint file. If
  250. None, attempts to restore from the first directory in checkpoint_dirs.
  251. num_batches: the number of batches to use for evaluation.
  252. master: the location of the Tensorflow session.
  253. save_graph: whether or not the Tensorflow graph is stored as a pbtxt file.
  254. save_graph_dir: where to store the Tensorflow graph on disk. If save_graph
  255. is True this must be non-empty.
  256. losses_dict: optional dictionary of scalar detection losses.
  257. eval_export_path: Path for saving a json file that contains the detection
  258. results in json format.
  259. process_metrics_fn: a callback called with evaluation results after each
  260. evaluation is done. It could be used e.g. to back up checkpoints with
  261. best evaluation scores, or to call an external system to update evaluation
  262. results in order to drive best hyper-parameter search. Parameters are:
  263. int checkpoint_number, Dict[str, ObjectDetectionEvalMetrics] metrics,
  264. str checkpoint_file path.
  265. Returns:
  266. global_step: the count of global steps.
  267. all_evaluator_metrics: A dictionary containing metric names and values.
  268. Raises:
  269. ValueError: if restore_fn is None and checkpoint_dirs doesn't have at least
  270. one element.
  271. ValueError: if save_graph is True and save_graph_dir is not defined.
  272. """
  273. if save_graph and not save_graph_dir:
  274. raise ValueError('`save_graph_dir` must be defined.')
  275. sess = tf.Session(master, graph=tf.get_default_graph())
  276. sess.run(tf.global_variables_initializer())
  277. sess.run(tf.local_variables_initializer())
  278. sess.run(tf.tables_initializer())
  279. checkpoint_file = None
  280. if restore_fn:
  281. restore_fn(sess)
  282. else:
  283. if not checkpoint_dirs:
  284. raise ValueError('`checkpoint_dirs` must have at least one entry.')
  285. checkpoint_file = tf.train.latest_checkpoint(checkpoint_dirs[0])
  286. saver = tf.train.Saver(variables_to_restore)
  287. saver.restore(sess, checkpoint_file)
  288. if save_graph:
  289. tf.train.write_graph(sess.graph_def, save_graph_dir, 'eval.pbtxt')
  290. counters = {'skipped': 0, 'success': 0}
  291. aggregate_result_losses_dict = collections.defaultdict(list)
  292. with tf.contrib.slim.queues.QueueRunners(sess):
  293. try:
  294. for batch in range(int(num_batches)):
  295. if (batch + 1) % 100 == 0:
  296. tf.logging.info('Running eval ops batch %d/%d', batch + 1,
  297. num_batches)
  298. if not batch_processor:
  299. try:
  300. if not losses_dict:
  301. losses_dict = {}
  302. result_dict, result_losses_dict = sess.run([tensor_dict,
  303. losses_dict])
  304. counters['success'] += 1
  305. except tf.errors.InvalidArgumentError:
  306. tf.logging.info('Skipping image')
  307. counters['skipped'] += 1
  308. result_dict = {}
  309. else:
  310. result_dict, result_losses_dict = batch_processor(
  311. tensor_dict, sess, batch, counters, losses_dict=losses_dict)
  312. if not result_dict:
  313. continue
  314. for key, value in iter(result_losses_dict.items()):
  315. aggregate_result_losses_dict[key].append(value)
  316. for evaluator in evaluators:
  317. # TODO(b/65130867): Use image_id tensor once we fix the input data
  318. # decoders to return correct image_id.
  319. # TODO(akuznetsa): result_dict contains batches of images, while
  320. # add_single_ground_truth_image_info expects a single image. Fix
  321. if (isinstance(result_dict, dict) and
  322. fields.InputDataFields.key in result_dict and
  323. result_dict[fields.InputDataFields.key]):
  324. image_id = result_dict[fields.InputDataFields.key]
  325. else:
  326. image_id = batch
  327. evaluator.add_single_ground_truth_image_info(
  328. image_id=image_id, groundtruth_dict=result_dict)
  329. evaluator.add_single_detected_image_info(
  330. image_id=image_id, detections_dict=result_dict)
  331. tf.logging.info('Running eval batches done.')
  332. except tf.errors.OutOfRangeError:
  333. tf.logging.info('Done evaluating -- epoch limit reached')
  334. finally:
  335. # When done, ask the threads to stop.
  336. tf.logging.info('# success: %d', counters['success'])
  337. tf.logging.info('# skipped: %d', counters['skipped'])
  338. all_evaluator_metrics = {}
  339. if eval_export_path and eval_export_path is not None:
  340. for evaluator in evaluators:
  341. if (isinstance(evaluator, coco_evaluation.CocoDetectionEvaluator) or
  342. isinstance(evaluator, coco_evaluation.CocoMaskEvaluator)):
  343. tf.logging.info('Started dumping to json file.')
  344. evaluator.dump_detections_to_json_file(
  345. json_output_path=eval_export_path)
  346. tf.logging.info('Finished dumping to json file.')
  347. for evaluator in evaluators:
  348. metrics = evaluator.evaluate()
  349. evaluator.clear()
  350. if any(key in all_evaluator_metrics for key in metrics):
  351. raise ValueError('Metric names between evaluators must not collide.')
  352. all_evaluator_metrics.update(metrics)
  353. global_step = tf.train.global_step(sess, tf.train.get_global_step())
  354. for key, value in iter(aggregate_result_losses_dict.items()):
  355. all_evaluator_metrics['Losses/' + key] = np.mean(value)
  356. if process_metrics_fn and checkpoint_file:
  357. m = re.search(r'model.ckpt-(\d+)$', checkpoint_file)
  358. if not m:
  359. tf.logging.error('Failed to parse checkpoint number from: %s',
  360. checkpoint_file)
  361. else:
  362. checkpoint_number = int(m.group(1))
  363. process_metrics_fn(checkpoint_number, all_evaluator_metrics,
  364. checkpoint_file)
  365. sess.close()
  366. return (global_step, all_evaluator_metrics)
  367. # TODO(rathodv): Add tests.
  368. def repeated_checkpoint_run(tensor_dict,
  369. summary_dir,
  370. evaluators,
  371. batch_processor=None,
  372. checkpoint_dirs=None,
  373. variables_to_restore=None,
  374. restore_fn=None,
  375. num_batches=1,
  376. eval_interval_secs=120,
  377. max_number_of_evaluations=None,
  378. max_evaluation_global_step=None,
  379. master='',
  380. save_graph=False,
  381. save_graph_dir='',
  382. losses_dict=None,
  383. eval_export_path=None,
  384. process_metrics_fn=None):
  385. """Periodically evaluates desired tensors using checkpoint_dirs or restore_fn.
  386. This function repeatedly loads a checkpoint and evaluates a desired
  387. set of tensors (provided by tensor_dict) and hands the resulting numpy
  388. arrays to a function result_processor which can be used to further
  389. process/save/visualize the results.
  390. Args:
  391. tensor_dict: a dictionary holding tensors representing a batch of detections
  392. and corresponding groundtruth annotations.
  393. summary_dir: a directory to write metrics summaries.
  394. evaluators: a list of object of type DetectionEvaluator to be used for
  395. evaluation. Note that the metric names produced by different evaluators
  396. must be unique.
  397. batch_processor: a function taking three arguments:
  398. 1. tensor_dict: the same tensor_dict that is passed in as the first
  399. argument to this function.
  400. 2. sess: a tensorflow session
  401. 3. batch_index: an integer representing the index of the batch amongst
  402. all batches
  403. By default, batch_processor is None, which defaults to running:
  404. return sess.run(tensor_dict)
  405. checkpoint_dirs: list of directories to load into a DetectionModel or an
  406. EnsembleModel if restore_fn isn't set. Also used to determine when to run
  407. next evaluation. Must have at least one element.
  408. variables_to_restore: None, or a dictionary mapping variable names found in
  409. a checkpoint to model variables. The dictionary would normally be
  410. generated by creating a tf.train.ExponentialMovingAverage object and
  411. calling its variables_to_restore() method. Not used if restore_fn is set.
  412. restore_fn: a function that takes a tf.Session object and correctly restores
  413. all necessary variables from the correct checkpoint file.
  414. num_batches: the number of batches to use for evaluation.
  415. eval_interval_secs: the number of seconds between each evaluation run.
  416. max_number_of_evaluations: the max number of iterations of the evaluation.
  417. If the value is left as None the evaluation continues indefinitely.
  418. max_evaluation_global_step: global step when evaluation stops.
  419. master: the location of the Tensorflow session.
  420. save_graph: whether or not the Tensorflow graph is saved as a pbtxt file.
  421. save_graph_dir: where to save on disk the Tensorflow graph. If store_graph
  422. is True this must be non-empty.
  423. losses_dict: optional dictionary of scalar detection losses.
  424. eval_export_path: Path for saving a json file that contains the detection
  425. results in json format.
  426. process_metrics_fn: a callback called with evaluation results after each
  427. evaluation is done. It could be used e.g. to back up checkpoints with
  428. best evaluation scores, or to call an external system to update evaluation
  429. results in order to drive best hyper-parameter search. Parameters are:
  430. int checkpoint_number, Dict[str, ObjectDetectionEvalMetrics] metrics,
  431. str checkpoint_file path.
  432. Returns:
  433. metrics: A dictionary containing metric names and values in the latest
  434. evaluation.
  435. Raises:
  436. ValueError: if max_num_of_evaluations is not None or a positive number.
  437. ValueError: if checkpoint_dirs doesn't have at least one element.
  438. """
  439. if max_number_of_evaluations and max_number_of_evaluations <= 0:
  440. raise ValueError(
  441. '`max_number_of_evaluations` must be either None or a positive number.')
  442. if max_evaluation_global_step and max_evaluation_global_step <= 0:
  443. raise ValueError(
  444. '`max_evaluation_global_step` must be either None or positive.')
  445. if not checkpoint_dirs:
  446. raise ValueError('`checkpoint_dirs` must have at least one entry.')
  447. last_evaluated_model_path = None
  448. number_of_evaluations = 0
  449. while True:
  450. start = time.time()
  451. tf.logging.info('Starting evaluation at ' + time.strftime(
  452. '%Y-%m-%d-%H:%M:%S', time.gmtime()))
  453. model_path = tf.train.latest_checkpoint(checkpoint_dirs[0])
  454. if not model_path:
  455. tf.logging.info('No model found in %s. Will try again in %d seconds',
  456. checkpoint_dirs[0], eval_interval_secs)
  457. elif model_path == last_evaluated_model_path:
  458. tf.logging.info('Found already evaluated checkpoint. Will try again in '
  459. '%d seconds', eval_interval_secs)
  460. else:
  461. last_evaluated_model_path = model_path
  462. global_step, metrics = _run_checkpoint_once(
  463. tensor_dict,
  464. evaluators,
  465. batch_processor,
  466. checkpoint_dirs,
  467. variables_to_restore,
  468. restore_fn,
  469. num_batches,
  470. master,
  471. save_graph,
  472. save_graph_dir,
  473. losses_dict=losses_dict,
  474. eval_export_path=eval_export_path,
  475. process_metrics_fn=process_metrics_fn)
  476. write_metrics(metrics, global_step, summary_dir)
  477. if (max_evaluation_global_step and
  478. global_step >= max_evaluation_global_step):
  479. tf.logging.info('Finished evaluation!')
  480. break
  481. number_of_evaluations += 1
  482. if (max_number_of_evaluations and
  483. number_of_evaluations >= max_number_of_evaluations):
  484. tf.logging.info('Finished evaluation!')
  485. break
  486. time_to_next_eval = start + eval_interval_secs - time.time()
  487. if time_to_next_eval > 0:
  488. time.sleep(time_to_next_eval)
  489. return metrics
  490. def _scale_box_to_absolute(args):
  491. boxes, image_shape = args
  492. return box_list_ops.to_absolute_coordinates(
  493. box_list.BoxList(boxes), image_shape[0], image_shape[1]).get()
  494. def _resize_detection_masks(args):
  495. detection_boxes, detection_masks, image_shape = args
  496. detection_masks_reframed = ops.reframe_box_masks_to_image_masks(
  497. detection_masks, detection_boxes, image_shape[0], image_shape[1])
  498. return tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)
  499. def _resize_groundtruth_masks(args):
  500. mask, image_shape = args
  501. mask = tf.expand_dims(mask, 3)
  502. mask = tf.image.resize_images(
  503. mask,
  504. image_shape,
  505. method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,
  506. align_corners=True)
  507. return tf.cast(tf.squeeze(mask, 3), tf.uint8)
  508. def _scale_keypoint_to_absolute(args):
  509. keypoints, image_shape = args
  510. return keypoint_ops.scale(keypoints, image_shape[0], image_shape[1])
  511. def result_dict_for_single_example(image,
  512. key,
  513. detections,
  514. groundtruth=None,
  515. class_agnostic=False,
  516. scale_to_absolute=False):
  517. """Merges all detection and groundtruth information for a single example.
  518. Note that evaluation tools require classes that are 1-indexed, and so this
  519. function performs the offset. If `class_agnostic` is True, all output classes
  520. have label 1.
  521. Args:
  522. image: A single 4D uint8 image tensor of shape [1, H, W, C].
  523. key: A single string tensor identifying the image.
  524. detections: A dictionary of detections, returned from
  525. DetectionModel.postprocess().
  526. groundtruth: (Optional) Dictionary of groundtruth items, with fields:
  527. 'groundtruth_boxes': [num_boxes, 4] float32 tensor of boxes, in
  528. normalized coordinates.
  529. 'groundtruth_classes': [num_boxes] int64 tensor of 1-indexed classes.
  530. 'groundtruth_area': [num_boxes] float32 tensor of bbox area. (Optional)
  531. 'groundtruth_is_crowd': [num_boxes] int64 tensor. (Optional)
  532. 'groundtruth_difficult': [num_boxes] int64 tensor. (Optional)
  533. 'groundtruth_group_of': [num_boxes] int64 tensor. (Optional)
  534. 'groundtruth_instance_masks': 3D int64 tensor of instance masks
  535. (Optional).
  536. class_agnostic: Boolean indicating whether the detections are class-agnostic
  537. (i.e. binary). Default False.
  538. scale_to_absolute: Boolean indicating whether boxes and keypoints should be
  539. scaled to absolute coordinates. Note that for IoU based evaluations, it
  540. does not matter whether boxes are expressed in absolute or relative
  541. coordinates. Default False.
  542. Returns:
  543. A dictionary with:
  544. 'original_image': A [1, H, W, C] uint8 image tensor.
  545. 'key': A string tensor with image identifier.
  546. 'detection_boxes': [max_detections, 4] float32 tensor of boxes, in
  547. normalized or absolute coordinates, depending on the value of
  548. `scale_to_absolute`.
  549. 'detection_scores': [max_detections] float32 tensor of scores.
  550. 'detection_classes': [max_detections] int64 tensor of 1-indexed classes.
  551. 'detection_masks': [max_detections, H, W] float32 tensor of binarized
  552. masks, reframed to full image masks.
  553. 'groundtruth_boxes': [num_boxes, 4] float32 tensor of boxes, in
  554. normalized or absolute coordinates, depending on the value of
  555. `scale_to_absolute`. (Optional)
  556. 'groundtruth_classes': [num_boxes] int64 tensor of 1-indexed classes.
  557. (Optional)
  558. 'groundtruth_area': [num_boxes] float32 tensor of bbox area. (Optional)
  559. 'groundtruth_is_crowd': [num_boxes] int64 tensor. (Optional)
  560. 'groundtruth_difficult': [num_boxes] int64 tensor. (Optional)
  561. 'groundtruth_group_of': [num_boxes] int64 tensor. (Optional)
  562. 'groundtruth_instance_masks': 3D int64 tensor of instance masks
  563. (Optional).
  564. """
  565. if groundtruth:
  566. max_gt_boxes = tf.shape(
  567. groundtruth[fields.InputDataFields.groundtruth_boxes])[0]
  568. for gt_key in groundtruth:
  569. # expand groundtruth dict along the batch dimension.
  570. groundtruth[gt_key] = tf.expand_dims(groundtruth[gt_key], 0)
  571. for detection_key in detections:
  572. detections[detection_key] = tf.expand_dims(
  573. detections[detection_key][0], axis=0)
  574. batched_output_dict = result_dict_for_batched_example(
  575. image,
  576. tf.expand_dims(key, 0),
  577. detections,
  578. groundtruth,
  579. class_agnostic,
  580. scale_to_absolute,
  581. max_gt_boxes=max_gt_boxes)
  582. exclude_keys = [
  583. fields.InputDataFields.original_image,
  584. fields.DetectionResultFields.num_detections,
  585. fields.InputDataFields.num_groundtruth_boxes
  586. ]
  587. output_dict = {
  588. fields.InputDataFields.original_image:
  589. batched_output_dict[fields.InputDataFields.original_image]
  590. }
  591. for key in batched_output_dict:
  592. # remove the batch dimension.
  593. if key not in exclude_keys:
  594. output_dict[key] = tf.squeeze(batched_output_dict[key], 0)
  595. return output_dict
  596. def result_dict_for_batched_example(images,
  597. keys,
  598. detections,
  599. groundtruth=None,
  600. class_agnostic=False,
  601. scale_to_absolute=False,
  602. original_image_spatial_shapes=None,
  603. true_image_shapes=None,
  604. max_gt_boxes=None):
  605. """Merges all detection and groundtruth information for a single example.
  606. Note that evaluation tools require classes that are 1-indexed, and so this
  607. function performs the offset. If `class_agnostic` is True, all output classes
  608. have label 1.
  609. Args:
  610. images: A single 4D uint8 image tensor of shape [batch_size, H, W, C].
  611. keys: A [batch_size] string tensor with image identifier.
  612. detections: A dictionary of detections, returned from
  613. DetectionModel.postprocess().
  614. groundtruth: (Optional) Dictionary of groundtruth items, with fields:
  615. 'groundtruth_boxes': [batch_size, max_number_of_boxes, 4] float32 tensor
  616. of boxes, in normalized coordinates.
  617. 'groundtruth_classes': [batch_size, max_number_of_boxes] int64 tensor of
  618. 1-indexed classes.
  619. 'groundtruth_area': [batch_size, max_number_of_boxes] float32 tensor of
  620. bbox area. (Optional)
  621. 'groundtruth_is_crowd':[batch_size, max_number_of_boxes] int64
  622. tensor. (Optional)
  623. 'groundtruth_difficult': [batch_size, max_number_of_boxes] int64
  624. tensor. (Optional)
  625. 'groundtruth_group_of': [batch_size, max_number_of_boxes] int64
  626. tensor. (Optional)
  627. 'groundtruth_instance_masks': 4D int64 tensor of instance
  628. masks (Optional).
  629. class_agnostic: Boolean indicating whether the detections are class-agnostic
  630. (i.e. binary). Default False.
  631. scale_to_absolute: Boolean indicating whether boxes and keypoints should be
  632. scaled to absolute coordinates. Note that for IoU based evaluations, it
  633. does not matter whether boxes are expressed in absolute or relative
  634. coordinates. Default False.
  635. original_image_spatial_shapes: A 2D int32 tensor of shape [batch_size, 2]
  636. used to resize the image. When set to None, the image size is retained.
  637. true_image_shapes: A 2D int32 tensor of shape [batch_size, 3]
  638. containing the size of the unpadded original_image.
  639. max_gt_boxes: [batch_size] tensor representing the maximum number of
  640. groundtruth boxes to pad.
  641. Returns:
  642. A dictionary with:
  643. 'original_image': A [batch_size, H, W, C] uint8 image tensor.
  644. 'original_image_spatial_shape': A [batch_size, 2] tensor containing the
  645. original image sizes.
  646. 'true_image_shape': A [batch_size, 3] tensor containing the size of
  647. the unpadded original_image.
  648. 'key': A [batch_size] string tensor with image identifier.
  649. 'detection_boxes': [batch_size, max_detections, 4] float32 tensor of boxes,
  650. in normalized or absolute coordinates, depending on the value of
  651. `scale_to_absolute`.
  652. 'detection_scores': [batch_size, max_detections] float32 tensor of scores.
  653. 'detection_classes': [batch_size, max_detections] int64 tensor of 1-indexed
  654. classes.
  655. 'detection_masks': [batch_size, max_detections, H, W] float32 tensor of
  656. binarized masks, reframed to full image masks.
  657. 'num_detections': [batch_size] int64 tensor containing number of valid
  658. detections.
  659. 'groundtruth_boxes': [batch_size, num_boxes, 4] float32 tensor of boxes, in
  660. normalized or absolute coordinates, depending on the value of
  661. `scale_to_absolute`. (Optional)
  662. 'groundtruth_classes': [batch_size, num_boxes] int64 tensor of 1-indexed
  663. classes. (Optional)
  664. 'groundtruth_area': [batch_size, num_boxes] float32 tensor of bbox
  665. area. (Optional)
  666. 'groundtruth_is_crowd': [batch_size, num_boxes] int64 tensor. (Optional)
  667. 'groundtruth_difficult': [batch_size, num_boxes] int64 tensor. (Optional)
  668. 'groundtruth_group_of': [batch_size, num_boxes] int64 tensor. (Optional)
  669. 'groundtruth_instance_masks': 4D int64 tensor of instance masks
  670. (Optional).
  671. 'num_groundtruth_boxes': [batch_size] tensor containing the maximum number
  672. of groundtruth boxes per image.
  673. Raises:
  674. ValueError: if original_image_spatial_shape is not 2D int32 tensor of shape
  675. [2].
  676. ValueError: if true_image_shapes is not 2D int32 tensor of shape
  677. [3].
  678. """
  679. label_id_offset = 1 # Applying label id offset (b/63711816)
  680. input_data_fields = fields.InputDataFields
  681. if original_image_spatial_shapes is None:
  682. original_image_spatial_shapes = tf.tile(
  683. tf.expand_dims(tf.shape(images)[1:3], axis=0),
  684. multiples=[tf.shape(images)[0], 1])
  685. else:
  686. if (len(original_image_spatial_shapes.shape) != 2 and
  687. original_image_spatial_shapes.shape[1] != 2):
  688. raise ValueError(
  689. '`original_image_spatial_shape` should be a 2D tensor of shape '
  690. '[batch_size, 2].')
  691. if true_image_shapes is None:
  692. true_image_shapes = tf.tile(
  693. tf.expand_dims(tf.shape(images)[1:4], axis=0),
  694. multiples=[tf.shape(images)[0], 1])
  695. else:
  696. if (len(true_image_shapes.shape) != 2
  697. and true_image_shapes.shape[1] != 3):
  698. raise ValueError('`true_image_shapes` should be a 2D tensor of '
  699. 'shape [batch_size, 3].')
  700. output_dict = {
  701. input_data_fields.original_image:
  702. images,
  703. input_data_fields.key:
  704. keys,
  705. input_data_fields.original_image_spatial_shape: (
  706. original_image_spatial_shapes),
  707. input_data_fields.true_image_shape:
  708. true_image_shapes
  709. }
  710. detection_fields = fields.DetectionResultFields
  711. detection_boxes = detections[detection_fields.detection_boxes]
  712. detection_scores = detections[detection_fields.detection_scores]
  713. num_detections = tf.to_int32(detections[detection_fields.num_detections])
  714. if class_agnostic:
  715. detection_classes = tf.ones_like(detection_scores, dtype=tf.int64)
  716. else:
  717. detection_classes = (
  718. tf.to_int64(detections[detection_fields.detection_classes]) +
  719. label_id_offset)
  720. if scale_to_absolute:
  721. output_dict[detection_fields.detection_boxes] = (
  722. shape_utils.static_or_dynamic_map_fn(
  723. _scale_box_to_absolute,
  724. elems=[detection_boxes, original_image_spatial_shapes],
  725. dtype=tf.float32))
  726. else:
  727. output_dict[detection_fields.detection_boxes] = detection_boxes
  728. output_dict[detection_fields.detection_classes] = detection_classes
  729. output_dict[detection_fields.detection_scores] = detection_scores
  730. output_dict[detection_fields.num_detections] = num_detections
  731. if detection_fields.detection_masks in detections:
  732. detection_masks = detections[detection_fields.detection_masks]
  733. # TODO(rathodv): This should be done in model's postprocess
  734. # function ideally.
  735. output_dict[detection_fields.detection_masks] = (
  736. shape_utils.static_or_dynamic_map_fn(
  737. _resize_detection_masks,
  738. elems=[detection_boxes, detection_masks,
  739. original_image_spatial_shapes],
  740. dtype=tf.uint8))
  741. if detection_fields.detection_keypoints in detections:
  742. detection_keypoints = detections[detection_fields.detection_keypoints]
  743. output_dict[detection_fields.detection_keypoints] = detection_keypoints
  744. if scale_to_absolute:
  745. output_dict[detection_fields.detection_keypoints] = (
  746. shape_utils.static_or_dynamic_map_fn(
  747. _scale_keypoint_to_absolute,
  748. elems=[detection_keypoints, original_image_spatial_shapes],
  749. dtype=tf.float32))
  750. if groundtruth:
  751. if max_gt_boxes is None:
  752. if input_data_fields.num_groundtruth_boxes in groundtruth:
  753. max_gt_boxes = groundtruth[input_data_fields.num_groundtruth_boxes]
  754. else:
  755. raise ValueError(
  756. 'max_gt_boxes must be provided when processing batched examples.')
  757. if input_data_fields.groundtruth_instance_masks in groundtruth:
  758. masks = groundtruth[input_data_fields.groundtruth_instance_masks]
  759. groundtruth[input_data_fields.groundtruth_instance_masks] = (
  760. shape_utils.static_or_dynamic_map_fn(
  761. _resize_groundtruth_masks,
  762. elems=[masks, original_image_spatial_shapes],
  763. dtype=tf.uint8))
  764. output_dict.update(groundtruth)
  765. if scale_to_absolute:
  766. groundtruth_boxes = groundtruth[input_data_fields.groundtruth_boxes]
  767. output_dict[input_data_fields.groundtruth_boxes] = (
  768. shape_utils.static_or_dynamic_map_fn(
  769. _scale_box_to_absolute,
  770. elems=[groundtruth_boxes, original_image_spatial_shapes],
  771. dtype=tf.float32))
  772. # For class-agnostic models, groundtruth classes all become 1.
  773. if class_agnostic:
  774. groundtruth_classes = groundtruth[input_data_fields.groundtruth_classes]
  775. groundtruth_classes = tf.ones_like(groundtruth_classes, dtype=tf.int64)
  776. output_dict[input_data_fields.groundtruth_classes] = groundtruth_classes
  777. output_dict[input_data_fields.num_groundtruth_boxes] = max_gt_boxes
  778. return output_dict
  779. def get_evaluators(eval_config, categories, evaluator_options=None):
  780. """Returns the evaluator class according to eval_config, valid for categories.
  781. Args:
  782. eval_config: An `eval_pb2.EvalConfig`.
  783. categories: A list of dicts, each of which has the following keys -
  784. 'id': (required) an integer id uniquely identifying this category.
  785. 'name': (required) string representing category name e.g., 'cat', 'dog'.
  786. evaluator_options: A dictionary of metric names (see
  787. EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization
  788. keyword arguments. For example:
  789. evalator_options = {
  790. 'coco_detection_metrics': {'include_metrics_per_category': True}
  791. }
  792. Returns:
  793. An list of instances of DetectionEvaluator.
  794. Raises:
  795. ValueError: if metric is not in the metric class dictionary.
  796. """
  797. evaluator_options = evaluator_options or {}
  798. eval_metric_fn_keys = eval_config.metrics_set
  799. if not eval_metric_fn_keys:
  800. eval_metric_fn_keys = [EVAL_DEFAULT_METRIC]
  801. evaluators_list = []
  802. for eval_metric_fn_key in eval_metric_fn_keys:
  803. if eval_metric_fn_key not in EVAL_METRICS_CLASS_DICT:
  804. raise ValueError('Metric not found: {}'.format(eval_metric_fn_key))
  805. kwargs_dict = (evaluator_options[eval_metric_fn_key] if eval_metric_fn_key
  806. in evaluator_options else {})
  807. evaluators_list.append(EVAL_METRICS_CLASS_DICT[eval_metric_fn_key](
  808. categories,
  809. **kwargs_dict))
  810. return evaluators_list
  811. def get_eval_metric_ops_for_evaluators(eval_config,
  812. categories,
  813. eval_dict):
  814. """Returns eval metrics ops to use with `tf.estimator.EstimatorSpec`.
  815. Args:
  816. eval_config: An `eval_pb2.EvalConfig`.
  817. categories: A list of dicts, each of which has the following keys -
  818. 'id': (required) an integer id uniquely identifying this category.
  819. 'name': (required) string representing category name e.g., 'cat', 'dog'.
  820. eval_dict: An evaluation dictionary, returned from
  821. result_dict_for_single_example().
  822. Returns:
  823. A dictionary of metric names to tuple of value_op and update_op that can be
  824. used as eval metric ops in tf.EstimatorSpec.
  825. """
  826. eval_metric_ops = {}
  827. evaluator_options = evaluator_options_from_eval_config(eval_config)
  828. evaluators_list = get_evaluators(eval_config, categories, evaluator_options)
  829. for evaluator in evaluators_list:
  830. eval_metric_ops.update(evaluator.get_estimator_eval_metric_ops(
  831. eval_dict))
  832. return eval_metric_ops
  833. def evaluator_options_from_eval_config(eval_config):
  834. """Produces a dictionary of evaluation options for each eval metric.
  835. Args:
  836. eval_config: An `eval_pb2.EvalConfig`.
  837. Returns:
  838. evaluator_options: A dictionary of metric names (see
  839. EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization
  840. keyword arguments. For example:
  841. evalator_options = {
  842. 'coco_detection_metrics': {'include_metrics_per_category': True}
  843. }
  844. """
  845. eval_metric_fn_keys = eval_config.metrics_set
  846. evaluator_options = {}
  847. for eval_metric_fn_key in eval_metric_fn_keys:
  848. if eval_metric_fn_key in ('coco_detection_metrics', 'coco_mask_metrics'):
  849. evaluator_options[eval_metric_fn_key] = {
  850. 'include_metrics_per_category': (
  851. eval_config.include_metrics_per_category)
  852. }
  853. return evaluator_options