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.

953 lines
42 KiB

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