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.

224 lines
10 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. """Evaluates Visual Relations Detection(VRD) result evaluation on an image.
  16. Annotate each VRD result as true positives or false positive according to
  17. a predefined IOU ratio. Multi-class detection is supported by default.
  18. Based on the settings, per image evaluation is performed either on phrase
  19. detection subtask or on relation detection subtask.
  20. """
  21. import numpy as np
  22. from object_detection.utils import np_box_list
  23. from object_detection.utils import np_box_list_ops
  24. class PerImageVRDEvaluation(object):
  25. """Evaluate vrd result of a single image."""
  26. def __init__(self, matching_iou_threshold=0.5):
  27. """Initialized PerImageVRDEvaluation by evaluation parameters.
  28. Args:
  29. matching_iou_threshold: A ratio of area intersection to union, which is
  30. the threshold to consider whether a detection is true positive or not;
  31. in phrase detection subtask.
  32. """
  33. self.matching_iou_threshold = matching_iou_threshold
  34. def compute_detection_tp_fp(self, detected_box_tuples, detected_scores,
  35. detected_class_tuples, groundtruth_box_tuples,
  36. groundtruth_class_tuples):
  37. """Evaluates VRD as being tp, fp from a single image.
  38. Args:
  39. detected_box_tuples: A numpy array of structures with shape [N,],
  40. representing N tuples, each tuple containing the same number of named
  41. bounding boxes.
  42. Each box is of the format [y_min, x_min, y_max, x_max].
  43. detected_scores: A float numpy array of shape [N,], representing
  44. the confidence scores of the detected N object instances.
  45. detected_class_tuples: A numpy array of structures shape [N,],
  46. representing the class labels of the corresponding bounding boxes and
  47. possibly additional classes.
  48. groundtruth_box_tuples: A float numpy array of structures with the shape
  49. [M,], representing M tuples, each tuple containing the same number
  50. of named bounding boxes.
  51. Each box is of the format [y_min, x_min, y_max, x_max].
  52. groundtruth_class_tuples: A numpy array of structures shape [M,],
  53. representing the class labels of the corresponding bounding boxes and
  54. possibly additional classes.
  55. Returns:
  56. scores: A single numpy array with shape [N,], representing N scores
  57. detected with object class, sorted in descentent order.
  58. tp_fp_labels: A single boolean numpy array of shape [N,], representing N
  59. True/False positive label, one label per tuple. The labels are sorted
  60. so that the order of the labels matches the order of the scores.
  61. result_mapping: A numpy array with shape [N,] with original index of each
  62. entry.
  63. """
  64. scores, tp_fp_labels, result_mapping = self._compute_tp_fp(
  65. detected_box_tuples=detected_box_tuples,
  66. detected_scores=detected_scores,
  67. detected_class_tuples=detected_class_tuples,
  68. groundtruth_box_tuples=groundtruth_box_tuples,
  69. groundtruth_class_tuples=groundtruth_class_tuples)
  70. return scores, tp_fp_labels, result_mapping
  71. def _compute_tp_fp(self, detected_box_tuples, detected_scores,
  72. detected_class_tuples, groundtruth_box_tuples,
  73. groundtruth_class_tuples):
  74. """Labels as true/false positives detection tuples across all classes.
  75. Args:
  76. detected_box_tuples: A numpy array of structures with shape [N,],
  77. representing N tuples, each tuple containing the same number of named
  78. bounding boxes.
  79. Each box is of the format [y_min, x_min, y_max, x_max]
  80. detected_scores: A float numpy array of shape [N,], representing
  81. the confidence scores of the detected N object instances.
  82. detected_class_tuples: A numpy array of structures shape [N,],
  83. representing the class labels of the corresponding bounding boxes and
  84. possibly additional classes.
  85. groundtruth_box_tuples: A float numpy array of structures with the shape
  86. [M,], representing M tuples, each tuple containing the same number
  87. of named bounding boxes.
  88. Each box is of the format [y_min, x_min, y_max, x_max]
  89. groundtruth_class_tuples: A numpy array of structures shape [M,],
  90. representing the class labels of the corresponding bounding boxes and
  91. possibly additional classes.
  92. Returns:
  93. scores: A single numpy array with shape [N,], representing N scores
  94. detected with object class, sorted in descentent order.
  95. tp_fp_labels: A single boolean numpy array of shape [N,], representing N
  96. True/False positive label, one label per tuple. The labels are sorted
  97. so that the order of the labels matches the order of the scores.
  98. result_mapping: A numpy array with shape [N,] with original index of each
  99. entry.
  100. """
  101. unique_gt_tuples = np.unique(
  102. np.concatenate((groundtruth_class_tuples, detected_class_tuples)))
  103. result_scores = []
  104. result_tp_fp_labels = []
  105. result_mapping = []
  106. for unique_tuple in unique_gt_tuples:
  107. detections_selector = (detected_class_tuples == unique_tuple)
  108. gt_selector = (groundtruth_class_tuples == unique_tuple)
  109. selector_mapping = np.where(detections_selector)[0]
  110. detection_scores_per_tuple = detected_scores[detections_selector]
  111. detection_box_per_tuple = detected_box_tuples[detections_selector]
  112. sorted_indices = np.argsort(detection_scores_per_tuple)
  113. sorted_indices = sorted_indices[::-1]
  114. tp_fp_labels = self._compute_tp_fp_for_single_class(
  115. detected_box_tuples=detection_box_per_tuple[sorted_indices],
  116. groundtruth_box_tuples=groundtruth_box_tuples[gt_selector])
  117. result_scores.append(detection_scores_per_tuple[sorted_indices])
  118. result_tp_fp_labels.append(tp_fp_labels)
  119. result_mapping.append(selector_mapping[sorted_indices])
  120. if result_scores:
  121. result_scores = np.concatenate(result_scores)
  122. result_tp_fp_labels = np.concatenate(result_tp_fp_labels)
  123. result_mapping = np.concatenate(result_mapping)
  124. else:
  125. result_scores = np.array([], dtype=float)
  126. result_tp_fp_labels = np.array([], dtype=bool)
  127. result_mapping = np.array([], dtype=int)
  128. sorted_indices = np.argsort(result_scores)
  129. sorted_indices = sorted_indices[::-1]
  130. return result_scores[sorted_indices], result_tp_fp_labels[
  131. sorted_indices], result_mapping[sorted_indices]
  132. def _get_overlaps_and_scores_relation_tuples(self, detected_box_tuples,
  133. groundtruth_box_tuples):
  134. """Computes overlaps and scores between detected and groundtruth tuples.
  135. Both detections and groundtruth boxes have the same class tuples.
  136. Args:
  137. detected_box_tuples: A numpy array of structures with shape [N,],
  138. representing N tuples, each tuple containing the same number of named
  139. bounding boxes.
  140. Each box is of the format [y_min, x_min, y_max, x_max]
  141. groundtruth_box_tuples: A float numpy array of structures with the shape
  142. [M,], representing M tuples, each tuple containing the same number
  143. of named bounding boxes.
  144. Each box is of the format [y_min, x_min, y_max, x_max]
  145. Returns:
  146. result_iou: A float numpy array of size
  147. [num_detected_tuples, num_gt_box_tuples].
  148. """
  149. result_iou = np.ones(
  150. (detected_box_tuples.shape[0], groundtruth_box_tuples.shape[0]),
  151. dtype=float)
  152. for field in detected_box_tuples.dtype.fields:
  153. detected_boxlist_field = np_box_list.BoxList(detected_box_tuples[field])
  154. gt_boxlist_field = np_box_list.BoxList(groundtruth_box_tuples[field])
  155. iou_field = np_box_list_ops.iou(detected_boxlist_field, gt_boxlist_field)
  156. result_iou = np.minimum(iou_field, result_iou)
  157. return result_iou
  158. def _compute_tp_fp_for_single_class(self, detected_box_tuples,
  159. groundtruth_box_tuples):
  160. """Labels boxes detected with the same class from the same image as tp/fp.
  161. Detection boxes are expected to be already sorted by score.
  162. Args:
  163. detected_box_tuples: A numpy array of structures with shape [N,],
  164. representing N tuples, each tuple containing the same number of named
  165. bounding boxes.
  166. Each box is of the format [y_min, x_min, y_max, x_max]
  167. groundtruth_box_tuples: A float numpy array of structures with the shape
  168. [M,], representing M tuples, each tuple containing the same number
  169. of named bounding boxes.
  170. Each box is of the format [y_min, x_min, y_max, x_max]
  171. Returns:
  172. tp_fp_labels: a boolean numpy array indicating whether a detection is a
  173. true positive.
  174. """
  175. if detected_box_tuples.size == 0:
  176. return np.array([], dtype=bool)
  177. min_iou = self._get_overlaps_and_scores_relation_tuples(
  178. detected_box_tuples, groundtruth_box_tuples)
  179. num_detected_tuples = detected_box_tuples.shape[0]
  180. tp_fp_labels = np.zeros(num_detected_tuples, dtype=bool)
  181. if min_iou.shape[1] > 0:
  182. max_overlap_gt_ids = np.argmax(min_iou, axis=1)
  183. is_gt_tuple_detected = np.zeros(min_iou.shape[1], dtype=bool)
  184. for i in range(num_detected_tuples):
  185. gt_id = max_overlap_gt_ids[i]
  186. if min_iou[i, gt_id] >= self.matching_iou_threshold:
  187. if not is_gt_tuple_detected[gt_id]:
  188. tp_fp_labels[i] = True
  189. is_gt_tuple_detected[gt_id] = True
  190. return tp_fp_labels